char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Pasha KhosraviAdd Q2_0 quantization: type definition and CPU backend (#24448)bec4772f6

char/aliceai-t5-moe
222.9 KiB5667 linesraw
1#define GGML_COMMON_IMPL_C
2#include "ggml-common.h"
3
4#include "ggml-quants.h"
5#include "ggml-impl.h"
6#include "ggml-cpu/ggml-cpu-impl.h"
7#include "ggml-cpu.h"
8
9#include <math.h>
10#include <string.h>
11#include <assert.h>
12#include <float.h>
13#include <stdlib.h> // for qsort
14#include <stdio.h>  // for GGML_ASSERT
15
16#ifdef GGML_USE_OPENMP
17#include <omp.h>
18#endif
19
20#define GROUP_MAX_EPS 1e-15f
21#define GROUP_MAX_EPS_IQ3_XXS 1e-8f
22#define GROUP_MAX_EPS_IQ2_S 1e-8f
23#define GROUP_MAX_EPS_IQ1_M 1e-7f
24#define GROUP_MAX_EPS_IQ1_S 1e-12f
25
26#define UNUSED GGML_UNUSED
27
28static inline int best_index_int8(int n, const int8_t * val, float x) {
29    if (x <= val[0]) return 0;
30    if (x >= val[n-1]) return n-1;
31    int ml = 0, mu = n-1;
32    while (mu-ml > 1) {
33        int mav = (ml+mu)/2;
34        if (x < val[mav]) mu = mav; else ml = mav;
35    }
36    return x - val[mu-1] < val[mu] - x ? mu-1 : mu;
37}
38
39// reference implementation for deterministic creation of model files
40void quantize_row_q1_0_ref(const float * GGML_RESTRICT x, block_q1_0 * GGML_RESTRICT y, int64_t k) {
41    static const int qk = QK1_0;
42
43    assert(k % qk == 0);
44
45    const int nb = k / qk;
46
47    for (int i = 0; i < nb; i++) {
48        float sum_abs = 0.0f;
49        for (int j = 0; j < qk; j++) {
50            sum_abs += fabsf(x[i*qk + j]);
51        }
52        const float d = sum_abs / qk;
53
54        y[i].d = GGML_FP32_TO_FP16(d);
55
56        // Clear all bits first
57        for (int j = 0; j < qk / 8; ++j) {
58            y[i].qs[j] = 0;
59        }
60
61        // Just store sign of each weight directly (no normalization)
62        for (int j = 0; j < qk; ++j) {
63            const int bit_index = j;
64            const int byte_index = bit_index / 8;
65            const int bit_offset = bit_index % 8;
66
67            if (x[i*qk + j] >= 0.0f) {
68                y[i].qs[byte_index] |= (1 << bit_offset);
69            }
70        }
71    }
72}
73
74void quantize_row_q2_0_ref(const float * GGML_RESTRICT x, block_q2_0 * GGML_RESTRICT y, int64_t k) {
75    static const int qk = QK2_0;
76
77    assert(k % qk == 0);
78
79    const int nb = k / qk;
80
81    for (int i = 0; i < nb; i++) {
82        // Compute scale as max absolute value in the block
83        float amax = 0.0f;
84        for (int j = 0; j < qk; j++) {
85            const float a = fabsf(x[i*qk + j]);
86            if (a > amax) amax = a;
87        }
88        const float d = amax;
89        const float id = d > 0.0f ? 1.0f / d : 0.0f;
90
91        y[i].d = GGML_FP32_TO_FP16(d);
92
93        // Clear quant bytes
94        for (int j = 0; j < qk / 4; ++j) {
95            y[i].qs[j] = 0;
96        }
97
98        // Encode 2-bit values: round(w/d) clamped to [-1, 2], then add 1
99        // 00 (-1) = -scale, 01 (0) = 0, 10 (+1) = +scale, 11 (+2) = 2*scale
100        for (int j = 0; j < qk; ++j) {
101            const float w = x[i*qk + j];
102            int q = (int)roundf(w * id) + 1;
103            if (q < 0) q = 0;
104            if (q > 3) q = 3;
105            const int byte_index = j / 4;
106            const int bit_offset = (j % 4) * 2;
107            y[i].qs[byte_index] |= ((uint8_t)q << bit_offset);
108        }
109    }
110}
111
112// reference implementation for deterministic creation of model files
113void quantize_row_q4_0_ref(const float * GGML_RESTRICT x, block_q4_0 * GGML_RESTRICT y, int64_t k) {
114    static const int qk = QK4_0;
115
116    assert(k % qk == 0);
117
118    const int nb = k / qk;
119
120    for (int i = 0; i < nb; i++) {
121        float amax = 0.0f; // absolute max
122        float max  = 0.0f;
123
124        for (int j = 0; j < qk; j++) {
125            const float v = x[i*qk + j];
126            if (amax < fabsf(v)) {
127                amax = fabsf(v);
128                max  = v;
129            }
130        }
131
132        const float d  = max / -8;
133        const float id = d ? 1.0f/d : 0.0f;
134
135        y[i].d = GGML_FP32_TO_FP16(d);
136
137        for (int j = 0; j < qk/2; ++j) {
138            const float x0 = x[i*qk + 0    + j]*id;
139            const float x1 = x[i*qk + qk/2 + j]*id;
140
141            const uint8_t xi0 = MIN(15, (int8_t)(x0 + 8.5f));
142            const uint8_t xi1 = MIN(15, (int8_t)(x1 + 8.5f));
143
144            y[i].qs[j]  = xi0;
145            y[i].qs[j] |= xi1 << 4;
146        }
147    }
148}
149
150void quantize_row_q4_1_ref(const float * GGML_RESTRICT x, block_q4_1 * GGML_RESTRICT y, int64_t k) {
151    const int qk = QK4_1;
152
153    assert(k % qk == 0);
154
155    const int nb = k / qk;
156
157    for (int i = 0; i < nb; i++) {
158        float min = FLT_MAX;
159        float max = -FLT_MAX;
160
161        for (int j = 0; j < qk; j++) {
162            const float v = x[i*qk + j];
163
164            if (v < min) min = v;
165            if (v > max) max = v;
166        }
167
168        const float d  = (max - min) / ((1 << 4) - 1);
169        const float id = d ? 1.0f/d : 0.0f;
170
171        y[i].d = GGML_FP32_TO_FP16(d);
172        y[i].m = GGML_FP32_TO_FP16(min);
173
174        for (int j = 0; j < qk/2; ++j) {
175            const float x0 = (x[i*qk + 0    + j] - min)*id;
176            const float x1 = (x[i*qk + qk/2 + j] - min)*id;
177
178            const uint8_t xi0 = MIN(15, (int8_t)(x0 + 0.5f));
179            const uint8_t xi1 = MIN(15, (int8_t)(x1 + 0.5f));
180
181            y[i].qs[j]  = xi0;
182            y[i].qs[j] |= xi1 << 4;
183        }
184    }
185}
186
187void quantize_row_q5_0_ref(const float * GGML_RESTRICT x, block_q5_0 * GGML_RESTRICT y, int64_t k) {
188    static const int qk = QK5_0;
189
190    assert(k % qk == 0);
191
192    const int nb = k / qk;
193
194    for (int i = 0; i < nb; i++) {
195        float amax = 0.0f; // absolute max
196        float max  = 0.0f;
197
198        for (int j = 0; j < qk; j++) {
199            const float v = x[i*qk + j];
200            if (amax < fabsf(v)) {
201                amax = fabsf(v);
202                max  = v;
203            }
204        }
205
206        const float d  = max / -16;
207        const float id = d ? 1.0f/d : 0.0f;
208
209        y[i].d = GGML_FP32_TO_FP16(d);
210
211        uint32_t qh = 0;
212
213        for (int j = 0; j < qk/2; ++j) {
214            const float x0 = x[i*qk + 0    + j]*id;
215            const float x1 = x[i*qk + qk/2 + j]*id;
216
217            const uint8_t xi0 = MIN(31, (int8_t)(x0 + 16.5f));
218            const uint8_t xi1 = MIN(31, (int8_t)(x1 + 16.5f));
219
220            y[i].qs[j] = (xi0 & 0x0F) | ((xi1 & 0x0F) << 4);
221
222            // get the 5-th bit and store it in qh at the right position
223            qh |= ((xi0 & 0x10u) >> 4) << (j + 0);
224            qh |= ((xi1 & 0x10u) >> 4) << (j + qk/2);
225        }
226
227        memcpy(&y[i].qh, &qh, sizeof(qh));
228    }
229}
230
231void quantize_row_q5_1_ref(const float * GGML_RESTRICT x, block_q5_1 * GGML_RESTRICT y, int64_t k) {
232    const int qk = QK5_1;
233
234    assert(k % qk == 0);
235
236    const int nb = k / qk;
237
238    for (int i = 0; i < nb; i++) {
239        float min = FLT_MAX;
240        float max = -FLT_MAX;
241
242        for (int j = 0; j < qk; j++) {
243            const float v = x[i*qk + j];
244
245            if (v < min) min = v;
246            if (v > max) max = v;
247        }
248
249        const float d  = (max - min) / ((1 << 5) - 1);
250        const float id = d ? 1.0f/d : 0.0f;
251
252        y[i].d = GGML_FP32_TO_FP16(d);
253        y[i].m = GGML_FP32_TO_FP16(min);
254
255        uint32_t qh = 0;
256
257        for (int j = 0; j < qk/2; ++j) {
258            const float x0 = (x[i*qk + 0    + j] - min)*id;
259            const float x1 = (x[i*qk + qk/2 + j] - min)*id;
260
261            const uint8_t xi0 = (uint8_t)(x0 + 0.5f);
262            const uint8_t xi1 = (uint8_t)(x1 + 0.5f);
263
264            y[i].qs[j] = (xi0 & 0x0F) | ((xi1 & 0x0F) << 4);
265
266            // get the 5-th bit and store it in qh at the right position
267            qh |= ((xi0 & 0x10u) >> 4) << (j + 0);
268            qh |= ((xi1 & 0x10u) >> 4) << (j + qk/2);
269        }
270
271        memcpy(&y[i].qh, &qh, sizeof(y[i].qh));
272    }
273}
274
275// reference implementation for deterministic creation of model files
276void quantize_row_q8_0_ref(const float * GGML_RESTRICT x, block_q8_0 * GGML_RESTRICT y, int64_t k) {
277    assert(k % QK8_0 == 0);
278    const int nb = k / QK8_0;
279
280    for (int i = 0; i < nb; i++) {
281        float amax = 0.0f; // absolute max
282
283        for (int j = 0; j < QK8_0; j++) {
284            const float v = x[i*QK8_0 + j];
285            amax = MAX(amax, fabsf(v));
286        }
287
288        const float d = amax / ((1 << 7) - 1);
289        const float id = d ? 1.0f/d : 0.0f;
290
291        y[i].d = GGML_FP32_TO_FP16(d);
292
293        for (int j = 0; j < QK8_0; ++j) {
294            const float x0 = x[i*QK8_0 + j]*id;
295
296            y[i].qs[j] = roundf(x0);
297        }
298    }
299}
300
301// reference implementation for deterministic creation of model files
302void quantize_row_q8_1_ref(const float * GGML_RESTRICT x, block_q8_1 * GGML_RESTRICT y, int64_t k) {
303    assert(QK8_1 == 32);
304    assert(k % QK8_1 == 0);
305    const int nb = k / QK8_1;
306
307    for (int i = 0; i < nb; i++) {
308        float amax = 0.0f; // absolute max
309
310        for (int j = 0; j < QK8_1; j++) {
311            const float v = x[i*QK8_1 + j];
312            amax = MAX(amax, fabsf(v));
313        }
314
315        const float d = amax / ((1 << 7) - 1);
316        const float id = d ? 1.0f/d : 0.0f;
317
318        y[i].d = GGML_FP32_TO_FP16(d);
319
320        int sum = 0;
321
322        for (int j = 0; j < QK8_1/2; ++j) {
323            const float v0 = x[i*QK8_1           + j]*id;
324            const float v1 = x[i*QK8_1 + QK8_1/2 + j]*id;
325
326            y[i].qs[          j] = roundf(v0);
327            y[i].qs[QK8_1/2 + j] = roundf(v1);
328
329            sum += y[i].qs[          j];
330            sum += y[i].qs[QK8_1/2 + j];
331        }
332
333        y[i].s = GGML_FP32_TO_FP16(sum*d);
334    }
335}
336
337static inline int best_index_mxfp4(float x, float e) {
338    int best_index = 0;
339    float best_err = fabsf(kvalues_mxfp4[0]*e - x);
340    for (int i = 1; i < 16; i++) {
341        float err = fabsf(kvalues_mxfp4[i]*e - x);
342        if (err < best_err) {
343            best_index = i;
344            best_err = err;
345        }
346    }
347    return best_index;
348}
349
350void quantize_row_mxfp4_ref(const float * GGML_RESTRICT x, block_mxfp4 * GGML_RESTRICT y, int64_t k) {
351    static const int qk = QK_MXFP4;
352
353    assert(k % qk == 0);
354
355    const int nb = k / qk;
356
357    for (int i = 0; i < nb; i++) {
358        float amax = 0.0f; // absolute max
359
360        for (int j = 0; j < qk; j++) {
361            const float v = x[i*qk + j];
362
363            if (amax < fabsf(v)) {
364                amax = fabsf(v);
365            }
366        }
367
368        const uint8_t e = amax > 0.0f ? (uint8_t) (floorf(log2f(amax)) - 2 + 127) : 0;
369
370        const float d = GGML_E8M0_TO_FP32_HALF(e);
371
372        y[i].e = e;
373
374        for (int j = 0; j < qk/2; ++j) {
375            const uint8_t x0 = best_index_mxfp4(x[i*qk + 0    + j], d);
376            const uint8_t x1 = best_index_mxfp4(x[i*qk + qk/2 + j], d);
377
378            y[i].qs[j]  = x0;
379            y[i].qs[j] |= x1 << 4;
380        }
381    }
382}
383
384void quantize_row_nvfp4_ref(const float * GGML_RESTRICT x, block_nvfp4 * GGML_RESTRICT y, int64_t k) {
385    static const int qk = QK_NVFP4;
386    static const int qk_sub = QK_NVFP4_SUB;
387    static const int n_sub = QK_NVFP4 / QK_NVFP4_SUB;
388
389    assert(k % qk == 0);
390
391    const int nb = k / qk;
392
393    for (int i = 0; i < nb; i++) {
394        for (int s = 0; s < n_sub; s++) {
395            const float * xb = x + i*qk + s*qk_sub;
396
397            float amax = 0.0f;
398            for (int j = 0; j < qk_sub; j++) {
399                if (amax < fabsf(xb[j])) {
400                    amax = fabsf(xb[j]);
401                }
402            }
403
404            // UE4M3 scale: amax / 6.0 maps the max E2M1 value (6.0) to amax
405            const uint8_t ue = ggml_fp32_to_ue4m3(amax / 6.0f);
406            y[i].d[s] = ue;
407            const float d = ggml_ue4m3_to_fp32(ue);
408
409            for (int j = 0; j < qk_sub/2; ++j) {
410                const uint8_t x0 = best_index_mxfp4(xb[0        + j], d);
411                const uint8_t x1 = best_index_mxfp4(xb[qk_sub/2 + j], d);
412
413                y[i].qs[s*(qk_sub/2) + j] = x0 | (x1 << 4);
414            }
415        }
416    }
417}
418
419void dequantize_row_q1_0(const block_q1_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
420    static const int qk = QK1_0;
421
422    assert(k % qk == 0);
423
424    const int nb = k / qk;
425
426    for (int i = 0; i < nb; i++) {
427        const float d = GGML_FP16_TO_FP32(x[i].d);
428        const float neg_d = -d;
429
430        for (int j = 0; j < qk; ++j) {
431            const int byte_index = j / 8;
432            const int bit_offset = j % 8;
433            const uint8_t bit = (x[i].qs[byte_index] >> bit_offset) & 1;
434            y[i*qk + j] = bit ? d : neg_d;
435        }
436    }
437}
438
439void dequantize_row_q2_0(const block_q2_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
440    static const int qk = QK2_0;
441
442    assert(k % qk == 0);
443
444    const int nb = k / qk;
445
446    for (int i = 0; i < nb; i++) {
447        const float d = GGML_FP16_TO_FP32(x[i].d);
448
449        for (int j = 0; j < qk; ++j) {
450            const int byte_index = j / 4;
451            const int bit_offset = (j % 4) * 2;
452            const uint8_t q = (x[i].qs[byte_index] >> bit_offset) & 0x03;
453            // 00=-1, 01=0, 10=+1, 11=+2
454            y[i*qk + j] = ((int)q - 1) * d;
455        }
456    }
457}
458
459void dequantize_row_q4_0(const block_q4_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
460    static const int qk = QK4_0;
461
462    assert(k % qk == 0);
463
464    const int nb = k / qk;
465
466    for (int i = 0; i < nb; i++) {
467        const float d = GGML_FP16_TO_FP32(x[i].d);
468
469        for (int j = 0; j < qk/2; ++j) {
470            const int x0 = (x[i].qs[j] & 0x0F) - 8;
471            const int x1 = (x[i].qs[j] >>   4) - 8;
472
473            y[i*qk + j + 0   ] = x0*d;
474            y[i*qk + j + qk/2] = x1*d;
475        }
476    }
477}
478
479void dequantize_row_q4_1(const block_q4_1 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
480    static const int qk = QK4_1;
481
482    assert(k % qk == 0);
483
484    const int nb = k / qk;
485
486    for (int i = 0; i < nb; i++) {
487        const float d = GGML_FP16_TO_FP32(x[i].d);
488        const float m = GGML_FP16_TO_FP32(x[i].m);
489
490        for (int j = 0; j < qk/2; ++j) {
491            const int x0 = (x[i].qs[j] & 0x0F);
492            const int x1 = (x[i].qs[j] >>   4);
493
494            y[i*qk + j + 0   ] = x0*d + m;
495            y[i*qk + j + qk/2] = x1*d + m;
496        }
497    }
498}
499
500void dequantize_row_q5_0(const block_q5_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
501    static const int qk = QK5_0;
502
503    assert(k % qk == 0);
504
505    const int nb = k / qk;
506
507    for (int i = 0; i < nb; i++) {
508        const float d = GGML_FP16_TO_FP32(x[i].d);
509
510        uint32_t qh;
511        memcpy(&qh, x[i].qh, sizeof(qh));
512
513        for (int j = 0; j < qk/2; ++j) {
514            const uint8_t xh_0 = ((qh >> (j +  0)) << 4) & 0x10;
515            const uint8_t xh_1 = ((qh >> (j + 12))     ) & 0x10;
516
517            const int32_t x0 = ((x[i].qs[j] & 0x0F) | xh_0) - 16;
518            const int32_t x1 = ((x[i].qs[j] >>   4) | xh_1) - 16;
519
520            y[i*qk + j + 0   ] = x0*d;
521            y[i*qk + j + qk/2] = x1*d;
522        }
523    }
524}
525
526void dequantize_row_q5_1(const block_q5_1 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
527    static const int qk = QK5_1;
528
529    assert(k % qk == 0);
530
531    const int nb = k / qk;
532
533    for (int i = 0; i < nb; i++) {
534        const float d = GGML_FP16_TO_FP32(x[i].d);
535        const float m = GGML_FP16_TO_FP32(x[i].m);
536
537        uint32_t qh;
538        memcpy(&qh, x[i].qh, sizeof(qh));
539
540        for (int j = 0; j < qk/2; ++j) {
541            const uint8_t xh_0 = ((qh >> (j +  0)) << 4) & 0x10;
542            const uint8_t xh_1 = ((qh >> (j + 12))     ) & 0x10;
543
544            const int x0 = (x[i].qs[j] & 0x0F) | xh_0;
545            const int x1 = (x[i].qs[j] >>   4) | xh_1;
546
547            y[i*qk + j + 0   ] = x0*d + m;
548            y[i*qk + j + qk/2] = x1*d + m;
549        }
550    }
551}
552
553void dequantize_row_q8_0(const block_q8_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
554    static const int qk = QK8_0;
555
556    assert(k % qk == 0);
557
558    const int nb = k / qk;
559
560    for (int i = 0; i < nb; i++) {
561        const float d = GGML_FP16_TO_FP32(x[i].d);
562
563        for (int j = 0; j < qk; ++j) {
564            y[i*qk + j] = x[i].qs[j]*d;
565        }
566    }
567}
568
569void dequantize_row_mxfp4(const block_mxfp4 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
570    static const int qk = QK_MXFP4;
571
572    assert(k % qk == 0);
573
574    const int nb = k / qk;
575
576    for (int i = 0; i < nb; i++) {
577        const float d = GGML_E8M0_TO_FP32_HALF(x[i].e);
578
579        for (int j = 0; j < qk/2; ++j) {
580            const int8_t x0 = kvalues_mxfp4[x[i].qs[j] & 0x0F];
581            const int8_t x1 = kvalues_mxfp4[x[i].qs[j] >>   4];
582
583            y[i*qk + j + 0   ] = x0*d;
584            y[i*qk + j + qk/2] = x1*d;
585        }
586    }
587}
588
589void dequantize_row_nvfp4(const block_nvfp4 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
590    static const int qk = QK_NVFP4;
591    static const int qk_sub = QK_NVFP4_SUB;
592    static const int n_sub = QK_NVFP4 / QK_NVFP4_SUB;
593
594    assert(k % qk == 0);
595
596    const int nb = k / qk;
597
598    for (int i = 0; i < nb; i++) {
599        for (int s = 0; s < n_sub; s++) {
600            const float d = ggml_ue4m3_to_fp32(x[i].d[s]);
601            float * yb = y + i*qk + s*qk_sub;
602
603            for (int j = 0; j < qk_sub/2; ++j) {
604                const int8_t v0 = kvalues_mxfp4[x[i].qs[s*(qk_sub/2) + j] & 0x0F];
605                const int8_t v1 = kvalues_mxfp4[x[i].qs[s*(qk_sub/2) + j] >>   4];
606
607                yb[j + 0       ] = v0*d;
608                yb[j + qk_sub/2] = v1*d;
609            }
610        }
611    }
612}
613
614//
615// 2-6 bit quantization in super-blocks
616//
617
618//
619// ===================== Helper functions
620//
621static inline int nearest_int(float fval) {
622    assert(fabsf(fval) <= 4194303.f);
623    float val = fval + 12582912.f;
624    int i; memcpy(&i, &val, sizeof(int));
625    return (i & 0x007fffff) - 0x00400000;
626}
627
628static float make_qx_quants(int n, int nmax, const float * GGML_RESTRICT x, int8_t * GGML_RESTRICT L, int rmse_type,
629        const float * GGML_RESTRICT qw) {
630    float max = 0;
631    float amax = 0;
632    for (int i = 0; i < n; ++i) {
633        float ax = fabsf(x[i]);
634        if (ax > amax) { amax = ax; max = x[i]; }
635    }
636    if (amax < GROUP_MAX_EPS) { // all zero
637        for (int i = 0; i < n; ++i) {
638            L[i] = 0;
639        }
640        return 0.f;
641    }
642    float iscale = -nmax / max;
643    if (rmse_type == 0) {
644        for (int i = 0; i < n; ++i) {
645            int l = nearest_int(iscale * x[i]);
646            L[i] = nmax + MAX(-nmax, MIN(nmax-1, l));
647        }
648        return 1/iscale;
649    }
650    bool return_early = false;
651    if (rmse_type < 0) {
652        rmse_type = -rmse_type;
653        return_early = true;
654    }
655    float sumlx = 0;
656    float suml2 = 0;
657#ifdef HAVE_BUGGY_APPLE_LINKER
658    // use 'volatile' to prevent unroll and work around a bug in Apple ld64 1015.7
659    for (volatile int i = 0; i < n; ++i) {
660#else
661    for (int i = 0; i < n; ++i) {
662#endif
663        int l = nearest_int(iscale * x[i]);
664        l = MAX(-nmax, MIN(nmax-1, l));
665        L[i] = l + nmax;
666        float w = qw ? qw[i] : rmse_type == 1 ? x[i] * x[i] : rmse_type == 2 ? 1 : rmse_type == 3 ? fabsf(x[i]) : sqrtf(fabsf(x[i]));
667        sumlx += w*x[i]*l;
668        suml2 += w*l*l;
669    }
670    float scale = suml2 ? sumlx/suml2 : 0.0f;
671    if (return_early) return suml2 > 0 ? 0.5f*(scale + 1/iscale) : 1/iscale;
672    float best = scale * sumlx;
673    for (int is = -9; is <= 9; ++is) {
674        if (is == 0) {
675            continue;
676        }
677        iscale = -(nmax + 0.1f*is) / max;
678        sumlx = suml2 = 0;
679        for (int i = 0; i < n; ++i) {
680            int l = nearest_int(iscale * x[i]);
681            l = MAX(-nmax, MIN(nmax-1, l));
682            float w = qw ? qw[i] : rmse_type == 1 ? x[i] * x[i] : rmse_type == 2 ? 1 : rmse_type == 3 ? fabsf(x[i]) : sqrtf(fabsf(x[i]));
683            sumlx += w*x[i]*l;
684            suml2 += w*l*l;
685        }
686        if (suml2 > 0 && sumlx*sumlx > best*suml2) {
687            for (int i = 0; i < n; ++i) {
688                int l = nearest_int(iscale * x[i]);
689                L[i] = nmax + MAX(-nmax, MIN(nmax-1, l));
690            }
691            scale = sumlx/suml2; best = scale*sumlx;
692        }
693    }
694    return scale;
695}
696
697static float make_q3_quants(int n, int nmax, const float * GGML_RESTRICT x, int8_t * GGML_RESTRICT L, bool do_rmse) {
698    float max = 0;
699    float amax = 0;
700    for (int i = 0; i < n; ++i) {
701        float ax = fabsf(x[i]);
702        if (ax > amax) { amax = ax; max = x[i]; }
703    }
704    if (amax < GROUP_MAX_EPS) { // all zero
705        for (int i = 0; i < n; ++i) { L[i] = 0; }
706        return 0.f;
707    }
708    float iscale = -nmax / max;
709    if (do_rmse) {
710        float sumlx = 0;
711        float suml2 = 0;
712        for (int i = 0; i < n; ++i) {
713            int l = nearest_int(iscale * x[i]);
714            l = MAX(-nmax, MIN(nmax-1, l));
715            L[i] = l;
716            float w = x[i]*x[i];
717            sumlx += w*x[i]*l;
718            suml2 += w*l*l;
719        }
720        for (int itry = 0; itry < 5; ++itry) {
721            int n_changed = 0;
722            for (int i = 0; i < n; ++i) {
723                float w = x[i]*x[i];
724                float slx = sumlx - w*x[i]*L[i];
725                if (slx > 0) {
726                    float sl2 = suml2 - w*L[i]*L[i];
727                    int new_l = nearest_int(x[i] * sl2 / slx);
728                    new_l = MAX(-nmax, MIN(nmax-1, new_l));
729                    if (new_l != L[i]) {
730                        slx += w*x[i]*new_l;
731                        sl2 += w*new_l*new_l;
732                        if (sl2 > 0 && slx*slx*suml2 > sumlx*sumlx*sl2) {
733                            L[i] = new_l; sumlx = slx; suml2 = sl2;
734                            ++n_changed;
735                        }
736                    }
737                }
738            }
739            if (!n_changed) {
740                break;
741            }
742        }
743        for (int i = 0; i < n; ++i) {
744            L[i] += nmax;
745        }
746        return suml2 > 0.0f ? sumlx / suml2 : 0.0f;
747    }
748    for (int i = 0; i < n; ++i) {
749        int l = nearest_int(iscale * x[i]);
750        l = MAX(-nmax, MIN(nmax-1, l));
751        L[i] = l + nmax;
752    }
753    return 1/iscale;
754}
755
756static float make_qkx1_quants(int n, int nmax, const float * GGML_RESTRICT x, uint8_t * GGML_RESTRICT L, float * GGML_RESTRICT the_min,
757        int ntry, float alpha) {
758    float min = x[0];
759    float max = x[0];
760    for (int i = 1; i < n; ++i) {
761        if (x[i] < min) min = x[i];
762        if (x[i] > max) max = x[i];
763    }
764    if (max == min) {
765        for (int i = 0; i < n; ++i) L[i] = 0;
766        *the_min = 0;
767        return 0.f;
768    }
769    if (min > 0) min = 0;
770    float iscale = nmax/(max - min);
771    float scale = 1/iscale;
772    for (int itry = 0; itry < ntry; ++itry) {
773        float sumlx = 0; int suml2 = 0;
774        bool did_change = false;
775        for (int i = 0; i < n; ++i) {
776            int l = nearest_int(iscale*(x[i] - min));
777            l = MAX(0, MIN(nmax, l));
778            if (l != L[i]) {
779                L[i] = l;
780                did_change = true;
781            }
782            sumlx += (x[i] - min)*l;
783            suml2 += l*l;
784        }
785        scale = sumlx/suml2;
786        float sum = 0;
787        for (int i = 0; i < n; ++i) {
788            sum += x[i] - scale*L[i];
789        }
790        min = alpha*min + (1 - alpha)*sum/n;
791        if (min > 0) min = 0;
792        iscale = 1/scale;
793        if (!did_change) break;
794    }
795    *the_min = -min;
796    return scale;
797}
798
799static float make_qkx2_quants(int n, int nmax, const float * GGML_RESTRICT x, const float * GGML_RESTRICT weights,
800        uint8_t * GGML_RESTRICT L, float * GGML_RESTRICT the_min, uint8_t * GGML_RESTRICT Laux,
801        float rmin, float rdelta, int nstep, bool use_mad) {
802    float min = x[0];
803    float max = x[0];
804    float sum_w = weights[0];
805    float sum_x = sum_w * x[0];
806#ifdef HAVE_BUGGY_APPLE_LINKER
807    // use 'volatile' to prevent unroll and work around a bug in Apple ld64 1015.7
808    for (volatile int i = 1; i < n; ++i) {
809#else
810    for (int i = 1; i < n; ++i) {
811#endif
812        if (x[i] < min) min = x[i];
813        if (x[i] > max) max = x[i];
814        float w = weights[i];
815        sum_w += w;
816        sum_x += w * x[i];
817    }
818    if (min > 0) min = 0;
819    if (max == min) {
820        for (int i = 0; i < n; ++i) L[i] = 0;
821        *the_min = -min;
822        return 0.f;
823    }
824    float iscale = nmax/(max - min);
825    float scale = 1/iscale;
826    float best_error = 0;
827    for (int i = 0; i < n; ++i) {
828        int l = nearest_int(iscale*(x[i] - min));
829        L[i] = MAX(0, MIN(nmax, l));
830        float diff = scale * L[i] + min - x[i];
831        diff = use_mad ? fabsf(diff) : diff * diff;
832        float w = weights[i];
833        best_error += w * diff;
834    }
835    if (nstep < 1) {
836        *the_min = -min;
837        return scale;
838    }
839    for (int is = 0; is <= nstep; ++is) {
840        iscale = (rmin + rdelta*is + nmax)/(max - min);
841        float sum_l = 0, sum_l2 = 0, sum_xl = 0;
842        for (int i = 0; i < n; ++i) {
843            int l = nearest_int(iscale*(x[i] - min));
844            l = MAX(0, MIN(nmax, l));
845            Laux[i] = l;
846            float w = weights[i];
847            sum_l += w*l;
848            sum_l2 += w*l*l;
849            sum_xl += w*l*x[i];
850        }
851        float D = sum_w * sum_l2 - sum_l * sum_l;
852        if (D > 0) {
853            float this_scale = (sum_w * sum_xl - sum_x * sum_l)/D;
854            float this_min   = (sum_l2 * sum_x - sum_l * sum_xl)/D;
855            if (this_min > 0) {
856                this_min = 0;
857                this_scale = sum_xl / sum_l2;
858            }
859            float cur_error = 0;
860            for (int i = 0; i < n; ++i) {
861                float diff = this_scale * Laux[i] + this_min - x[i];
862                diff = use_mad ? fabsf(diff) : diff * diff;
863                float w = weights[i];
864                cur_error += w * diff;
865            }
866            if (cur_error < best_error) {
867                for (int i = 0; i < n; ++i) {
868                    L[i] = Laux[i];
869                }
870                best_error = cur_error;
871                scale = this_scale;
872                min = this_min;
873            }
874        }
875    }
876    *the_min = -min;
877    return scale;
878}
879
880static inline void get_scale_min_k4(int j, const uint8_t * GGML_RESTRICT q, uint8_t * GGML_RESTRICT d, uint8_t * GGML_RESTRICT m) {
881    if (j < 4) {
882        *d = q[j] & 63; *m = q[j + 4] & 63;
883    } else {
884        *d = (q[j+4] & 0xF) | ((q[j-4] >> 6) << 4);
885        *m = (q[j+4] >>  4) | ((q[j-0] >> 6) << 4);
886    }
887}
888
889//========================- 2-bit (de)-quantization
890
891void quantize_row_q2_K_ref(const float * GGML_RESTRICT x, block_q2_K * GGML_RESTRICT y, int64_t k) {
892    assert(k % QK_K == 0);
893    const int nb = k / QK_K;
894
895    uint8_t L[QK_K];
896    uint8_t Laux[16];
897    float   weights[16];
898    float mins[QK_K/16];
899    float scales[QK_K/16];
900
901    const float q4scale = 15.f;
902
903    for (int i = 0; i < nb; i++) {
904        float max_scale = 0; // as we are deducting the min, scales are always positive
905        float max_min = 0;
906        for (int j = 0; j < QK_K/16; ++j) {
907            for (int l = 0; l < 16; ++l) weights[l] = fabsf(x[16*j + l]);
908            scales[j] = make_qkx2_quants(16, 3, x + 16*j, weights, L + 16*j, &mins[j], Laux, -0.5f, 0.1f, 15, true);
909            float scale = scales[j];
910            if (scale > max_scale) {
911                max_scale = scale;
912            }
913            float min = mins[j];
914            if (min > max_min) {
915                max_min = min;
916            }
917        }
918
919        if (max_scale > 0) {
920            float iscale = q4scale/max_scale;
921            for (int j = 0; j < QK_K/16; ++j) {
922                int l = nearest_int(iscale*scales[j]);
923                y[i].scales[j] = l;
924            }
925            y[i].d = GGML_FP32_TO_FP16(max_scale/q4scale);
926        } else {
927            for (int j = 0; j < QK_K/16; ++j) y[i].scales[j] = 0;
928            y[i].d = GGML_FP32_TO_FP16(0.f);
929        }
930        if (max_min > 0) {
931            float iscale = q4scale/max_min;
932            for (int j = 0; j < QK_K/16; ++j) {
933                int l = nearest_int(iscale*mins[j]);
934                y[i].scales[j] |= (l << 4);
935            }
936            y[i].dmin = GGML_FP32_TO_FP16(max_min/q4scale);
937        } else {
938            y[i].dmin = GGML_FP32_TO_FP16(0.f);
939        }
940        for (int j = 0; j < QK_K/16; ++j) {
941            const float d = GGML_FP16_TO_FP32(y[i].d) * (y[i].scales[j] & 0xF);
942            if (!d) continue;
943            const float dm = GGML_FP16_TO_FP32(y[i].dmin) * (y[i].scales[j] >> 4);
944            for (int ii = 0; ii < 16; ++ii) {
945                int l = nearest_int((x[16*j + ii] + dm)/d);
946                l = MAX(0, MIN(3, l));
947                L[16*j + ii] = l;
948            }
949        }
950
951        for (int j = 0; j < QK_K; j += 128) {
952            for (int l = 0; l < 32; ++l) {
953                y[i].qs[j/4 + l] = L[j + l] | (L[j + l + 32] << 2) | (L[j + l + 64] << 4) | (L[j + l + 96] << 6);
954            }
955        }
956
957        x += QK_K;
958    }
959}
960
961void dequantize_row_q2_K(const block_q2_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
962    assert(k % QK_K == 0);
963    const int nb = k / QK_K;
964
965    for (int i = 0; i < nb; i++) {
966
967        const float d = GGML_FP16_TO_FP32(x[i].d);
968        const float min = GGML_FP16_TO_FP32(x[i].dmin);
969
970        const uint8_t * q = x[i].qs;
971
972        int is = 0;
973        float dl, ml;
974        for (int n = 0; n < QK_K; n += 128) {
975            int shift = 0;
976            for (int j = 0; j < 4; ++j) {
977
978                uint8_t sc = x[i].scales[is++];
979                dl = d * (sc & 0xF); ml = min * (sc >> 4);
980                for (int l = 0; l < 16; ++l) *y++ = dl * ((int8_t)((q[l] >> shift) & 3)) - ml;
981
982                sc = x[i].scales[is++];
983                dl = d * (sc & 0xF); ml = min * (sc >> 4);
984                for (int l = 0; l < 16; ++l) *y++ = dl * ((int8_t)((q[l+16] >> shift) & 3)) - ml;
985
986                shift += 2;
987            }
988            q += 32;
989        }
990    }
991}
992
993static float make_qkx3_quants(int n, int nmax, const float * GGML_RESTRICT x, const float * GGML_RESTRICT weights,
994        uint8_t * GGML_RESTRICT L, float * GGML_RESTRICT the_min, uint8_t * GGML_RESTRICT Laux,
995        float rmin, float rdelta, int nstep, bool use_mad) {
996    float min = x[0];
997    float max = x[0];
998    float sum_w = weights ? weights[0] : x[0]*x[0];
999    float sum_x = sum_w * x[0];
1000#ifdef HAVE_BUGGY_APPLE_LINKER
1001    // use 'volatile' to prevent unroll and work around a bug in Apple ld64 1015.7
1002    for (volatile int i = 1; i < n; ++i) {
1003#else
1004    for (int i = 1; i < n; ++i) {
1005#endif
1006        if (x[i] < min) min = x[i];
1007        if (x[i] > max) max = x[i];
1008        float w = weights ? weights[i] : x[i]*x[i];
1009        sum_w += w;
1010        sum_x += w * x[i];
1011    }
1012    if (min > 0) {
1013        min = 0;
1014    }
1015    if (max <= min) {
1016        memset(L, 0, n);
1017        *the_min = -min;
1018        return 0.f;
1019    }
1020    float iscale = nmax/(max - min);
1021    float scale = 1/iscale;
1022    float best_mad = 0;
1023    for (int i = 0; i < n; ++i) {
1024        int l = nearest_int(iscale*(x[i] - min));
1025        L[i] = MAX(0, MIN(nmax, l));
1026        float diff = scale * L[i] + min - x[i];
1027        diff = use_mad ? fabsf(diff) : diff*diff;
1028        float w = weights ? weights[i] : x[i]*x[i];
1029        best_mad += w * diff;
1030    }
1031    if (nstep < 1) {
1032        *the_min = -min;
1033        return scale;
1034    }
1035    for (int is = 0; is <= nstep; ++is) {
1036        iscale = (rmin + rdelta*is + nmax)/(max - min);
1037        float sum_l = 0, sum_l2 = 0, sum_xl = 0;
1038        for (int i = 0; i < n; ++i) {
1039            int l = nearest_int(iscale*(x[i] - min));
1040            l = MAX(0, MIN(nmax, l));
1041            Laux[i] = l;
1042            float w = weights ? weights[i] : x[i]*x[i];
1043            sum_l  += w*l;
1044            sum_l2 += w*l*l;
1045            sum_xl += w*l*x[i];
1046        }
1047        float D = sum_w * sum_l2 - sum_l * sum_l;
1048        if (D > 0) {
1049            float this_scale = (sum_w * sum_xl - sum_x * sum_l)/D;
1050            float this_min   = (sum_l2 * sum_x - sum_l * sum_xl)/D;
1051            if (this_min > 0) {
1052                this_min = 0;
1053                this_scale = sum_xl / sum_l2;
1054            }
1055            float mad = 0;
1056            for (int i = 0; i < n; ++i) {
1057                float diff = this_scale * Laux[i] + this_min - x[i];
1058                diff = use_mad ? fabsf(diff) : diff*diff;
1059                float w = weights ? weights[i] : x[i]*x[i];
1060                mad += w * diff;
1061            }
1062            if (mad < best_mad) {
1063                for (int i = 0; i < n; ++i) {
1064                    L[i] = Laux[i];
1065                }
1066                best_mad = mad;
1067                scale = this_scale;
1068                min = this_min;
1069            }
1070        }
1071    }
1072    *the_min = -min;
1073    return scale;
1074}
1075
1076static float make_qp_quants(int n, int nmax, const float * GGML_RESTRICT x, uint8_t * GGML_RESTRICT L, const float * quant_weights) {
1077    float max = 0;
1078    for (int i = 0; i < n; ++i) {
1079        max = MAX(max, x[i]);
1080    }
1081    if (max < GROUP_MAX_EPS) { // all zero
1082        for (int i = 0; i < n; ++i) { L[i] = 0; }
1083        return 0.f;
1084    }
1085    float iscale = nmax / max;
1086    for (int i = 0; i < n; ++i) {
1087        L[i] = nearest_int(iscale * x[i]);
1088    }
1089    float scale = 1/iscale;
1090    float best_mse = 0;
1091    for (int i = 0; i < n; ++i) {
1092        float diff = x[i] - scale*L[i];
1093        float w = quant_weights[i];
1094        best_mse += w*diff*diff;
1095    }
1096    for (int is = -4; is <= 4; ++is) {
1097        if (is == 0) continue;
1098        float iscale_is = (0.1f*is + nmax)/max;
1099        float scale_is = 1/iscale_is;
1100        float mse = 0;
1101        for (int i = 0; i < n; ++i) {
1102            int l = nearest_int(iscale_is*x[i]);
1103            l = MIN(nmax, l);
1104            float diff = x[i] - scale_is*l;
1105            float w = quant_weights[i];
1106            mse += w*diff*diff;
1107        }
1108        if (mse < best_mse) {
1109            best_mse = mse;
1110            iscale = iscale_is;
1111        }
1112    }
1113    float sumlx = 0;
1114    float suml2 = 0;
1115    for (int i = 0; i < n; ++i) {
1116        int l = nearest_int(iscale * x[i]);
1117        l = MIN(nmax, l);
1118        L[i] = l;
1119        float w = quant_weights[i];
1120        sumlx += w*x[i]*l;
1121        suml2 += w*l*l;
1122    }
1123    for (int itry = 0; itry < 5; ++itry) {
1124        int n_changed = 0;
1125        for (int i = 0; i < n; ++i) {
1126            float w = quant_weights[i];
1127            float slx = sumlx - w*x[i]*L[i];
1128            float sl2 = suml2 - w*L[i]*L[i];
1129            if (slx > 0 && sl2 > 0) {
1130                int new_l = nearest_int(x[i] * sl2 / slx);
1131                new_l = MIN(nmax, new_l);
1132                if (new_l != L[i]) {
1133                    slx += w*x[i]*new_l;
1134                    sl2 += w*new_l*new_l;
1135                    if (slx*slx*suml2 > sumlx*sumlx*sl2) {
1136                        L[i] = new_l; sumlx = slx; suml2 = sl2;
1137                        ++n_changed;
1138                    }
1139                }
1140            }
1141        }
1142        if (!n_changed) {
1143            break;
1144        }
1145    }
1146    return suml2 > 0.0f ? sumlx / suml2 : 0.0f;
1147}
1148
1149static void quantize_row_q2_K_impl(const float * GGML_RESTRICT x, block_q2_K * GGML_RESTRICT y, int k, const float * GGML_RESTRICT quant_weights) {
1150    GGML_ASSERT(quant_weights);
1151    assert(k % QK_K == 0);
1152    const int nb = k / QK_K;
1153    const bool requantize = true;
1154
1155    uint8_t L[QK_K];
1156    uint8_t Laux[16];
1157    float mins[QK_K/16];
1158    float scales[QK_K/16];
1159    float sw[QK_K/16];
1160    float weight[16];
1161    uint8_t Ls[QK_K/16], Lm[QK_K/16];
1162
1163    for (int i = 0; i < nb; i++) {
1164        memset(sw, 0, QK_K/16*sizeof(float));
1165        float sumx2 = 0;
1166        for (int j = 0; j < QK_K; ++j) sumx2 += x[j]*x[j];
1167        float sigma2 = sumx2/QK_K;
1168        for (int j = 0; j < QK_K/16; ++j) {
1169            const float * GGML_RESTRICT qw = quant_weights + QK_K * i + 16*j;
1170            for (int l = 0; l < 16; ++l) weight[l] = qw[l] * sqrtf(sigma2 + x[16*j + l]*x[16*j + l]);
1171            for (int l = 0; l < QK_K/16; ++l) sw[j] += weight[l];
1172            scales[j] = make_qkx3_quants(16, 3, x + 16*j, weight, L + 16*j, &mins[j], Laux, -0.9f, 0.05f, 36, false);
1173        }
1174
1175        float dm, mm;
1176        dm  = make_qp_quants(QK_K/16, 15, scales, Ls, sw);
1177        mm  = make_qp_quants(QK_K/16, 15, mins,   Lm, sw);
1178
1179        y[i].d    = GGML_FP32_TO_FP16(dm);
1180        y[i].dmin = GGML_FP32_TO_FP16(mm);
1181        dm        = GGML_FP16_TO_FP32(y[i].d);
1182        mm        = GGML_FP16_TO_FP32(y[i].dmin);
1183
1184        for (int j = 0; j < QK_K/16; ++j) {
1185            y[i].scales[j] = Ls[j] | (Lm[j] << 4);
1186        }
1187
1188        if (requantize) {
1189            for (int j = 0; j < QK_K/16; ++j) {
1190                const float d = dm * (y[i].scales[j] & 0xF);
1191                if (!d) continue;
1192                const float m = mm * (y[i].scales[j] >> 4);
1193                for (int ii = 0; ii < 16; ++ii) {
1194                    int l = nearest_int((x[16*j + ii] + m)/d);
1195                    l = MAX(0, MIN(3, l));
1196                    L[16*j + ii] = l;
1197                }
1198            }
1199        }
1200
1201        for (int j = 0; j < QK_K; j += 128) {
1202            for (int l = 0; l < 32; ++l) {
1203                y[i].qs[j/4 + l] = L[j + l] | (L[j + l + 32] << 2) | (L[j + l + 64] << 4) | (L[j + l + 96] << 6);
1204            }
1205        }
1206
1207        x += QK_K;
1208    }
1209}
1210
1211size_t quantize_q2_K(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
1212    size_t row_size = ggml_row_size(GGML_TYPE_Q2_K, n_per_row);
1213    if (!quant_weights) {
1214        quantize_row_q2_K_ref(src, dst, (int64_t)nrow*n_per_row);
1215    }
1216    else {
1217        char * qrow = (char *)dst;
1218        for (int64_t row = 0; row < nrow; ++row) {
1219            quantize_row_q2_K_impl(src, (block_q2_K*)qrow, n_per_row, quant_weights);
1220            src += n_per_row;
1221            qrow += row_size;
1222        }
1223    }
1224    return nrow * row_size;
1225}
1226
1227//========================= 3-bit (de)-quantization
1228
1229void quantize_row_q3_K_ref(const float * GGML_RESTRICT x, block_q3_K * GGML_RESTRICT y, int64_t k) {
1230    assert(k % QK_K == 0);
1231    const int nb = k / QK_K;
1232
1233    int8_t L[QK_K];
1234    float scales[QK_K / 16];
1235
1236    for (int i = 0; i < nb; i++) {
1237
1238        float max_scale = 0;
1239        float amax = 0;
1240        for (int j = 0; j < QK_K/16; ++j) {
1241            scales[j] = make_q3_quants(16, 4, x + 16*j, L + 16*j, true);
1242            float scale = fabsf(scales[j]);
1243            if (scale > amax) {
1244                amax = scale; max_scale = scales[j];
1245            }
1246        }
1247
1248        memset(y[i].scales, 0, 12);
1249        if (max_scale) {
1250            float iscale = -32.f/max_scale;
1251            for (int j = 0; j < QK_K/16; ++j) {
1252                int8_t l = nearest_int(iscale*scales[j]);
1253                l = MAX(-32, MIN(31, l)) + 32;
1254                if (j < 8) {
1255                    y[i].scales[j] = l & 0xF;
1256                } else {
1257                    y[i].scales[j-8] |= ((l & 0xF) << 4);
1258                }
1259                l >>= 4;
1260                y[i].scales[j%4 + 8] |= (l << (2*(j/4)));
1261            }
1262            y[i].d = GGML_FP32_TO_FP16(1/iscale);
1263        } else {
1264            y[i].d = GGML_FP32_TO_FP16(0.f);
1265        }
1266
1267        int8_t sc;
1268        for (int j = 0; j < QK_K/16; ++j) {
1269            sc = j < 8 ? y[i].scales[j] & 0xF : y[i].scales[j-8] >> 4;
1270            sc = (sc | (((y[i].scales[8 + j%4] >> (2*(j/4))) & 3) << 4)) - 32;
1271            float d = GGML_FP16_TO_FP32(y[i].d) * sc;
1272            if (!d) {
1273                continue;
1274            }
1275            for (int ii = 0; ii < 16; ++ii) {
1276                int l = nearest_int(x[16*j + ii]/d);
1277                l = MAX(-4, MIN(3, l));
1278                L[16*j + ii] = l + 4;
1279            }
1280        }
1281
1282        memset(y[i].hmask, 0, QK_K/8);
1283        // We put the high-bit for the 1st 8 quants into bit 0, the next 8 into bit 1, etc.
1284        int m = 0;
1285        uint8_t hm = 1;
1286        for (int j = 0; j < QK_K; ++j) {
1287            if (L[j] > 3) {
1288                y[i].hmask[m] |= hm;
1289                L[j] -= 4;
1290            }
1291            if (++m == QK_K/8) {
1292                m = 0; hm <<= 1;
1293            }
1294        }
1295        for (int j = 0; j < QK_K; j += 128) {
1296            for (int l = 0; l < 32; ++l) {
1297                y[i].qs[j/4 + l] = L[j + l] | (L[j + l + 32] << 2) | (L[j + l + 64] << 4) | (L[j + l + 96] << 6);
1298            }
1299        }
1300
1301        x += QK_K;
1302    }
1303}
1304
1305void dequantize_row_q3_K(const block_q3_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
1306    assert(k % QK_K == 0);
1307    const int nb = k / QK_K;
1308
1309    const uint32_t kmask1 = 0x03030303;
1310    const uint32_t kmask2 = 0x0f0f0f0f;
1311
1312    uint32_t aux[4];
1313    const int8_t * scales = (const int8_t*)aux;
1314
1315    for (int i = 0; i < nb; i++) {
1316
1317        const float d_all = GGML_FP16_TO_FP32(x[i].d);
1318
1319        const uint8_t * GGML_RESTRICT q = x[i].qs;
1320        const uint8_t * GGML_RESTRICT hm = x[i].hmask;
1321        uint8_t m = 1;
1322
1323        memcpy(aux, x[i].scales, 12);
1324        uint32_t tmp = aux[2];
1325        aux[2] = ((aux[0] >> 4) & kmask2) | (((tmp >> 4) & kmask1) << 4);
1326        aux[3] = ((aux[1] >> 4) & kmask2) | (((tmp >> 6) & kmask1) << 4);
1327        aux[0] = (aux[0] & kmask2) | (((tmp >> 0) & kmask1) << 4);
1328        aux[1] = (aux[1] & kmask2) | (((tmp >> 2) & kmask1) << 4);
1329
1330        int is = 0;
1331        float dl;
1332        for (int n = 0; n < QK_K; n += 128) {
1333            int shift = 0;
1334            for (int j = 0; j < 4; ++j) {
1335
1336                dl = d_all * (scales[is++] - 32);
1337                for (int l = 0; l < 16; ++l) {
1338                    *y++ = dl * ((int8_t)((q[l+ 0] >> shift) & 3) - ((hm[l+ 0] & m) ? 0 : 4));
1339                }
1340
1341                dl = d_all * (scales[is++] - 32);
1342                for (int l = 0; l < 16; ++l) {
1343                    *y++ = dl * ((int8_t)((q[l+16] >> shift) & 3) - ((hm[l+16] & m) ? 0 : 4));
1344                }
1345
1346                shift += 2;
1347                m <<= 1;
1348            }
1349            q += 32;
1350        }
1351
1352    }
1353}
1354
1355static void quantize_row_q3_K_impl(const float * GGML_RESTRICT x, block_q3_K * GGML_RESTRICT y, int64_t n_per_row, const float * GGML_RESTRICT quant_weights) {
1356    assert(n_per_row % QK_K == 0);
1357    const int nb = n_per_row / QK_K;
1358
1359    int8_t L[QK_K];
1360    float scales[QK_K / 16];
1361    float weight[16];
1362    float sw[QK_K / 16];
1363    int8_t Ls[QK_K / 16];
1364
1365    for (int i = 0; i < nb; i++) {
1366
1367        float sumx2 = 0;
1368        for (int j = 0; j < QK_K; ++j) sumx2 += x[j]*x[j];
1369        float sigma2 = 2*sumx2/QK_K;
1370
1371        for (int j = 0; j < QK_K/16; ++j) {
1372            if (quant_weights) {
1373                const float * qw = quant_weights + QK_K * i + 16*j;
1374                for (int l = 0; l < 16; ++l) weight[l] = qw[l] * sqrtf(sigma2 + x[16*j+l]*x[16*j+l]);
1375            } else {
1376                for (int l = 0; l < 16; ++l) weight[l] = x[16*j+l]*x[16*j+l];
1377            }
1378            float sumw = 0;
1379            for (int l = 0; l < 16; ++l) sumw += weight[l];
1380            sw[j] = sumw;
1381
1382            scales[j] = make_qx_quants(16, 4, x + 16*j, L + 16*j, 1, weight);
1383
1384        }
1385
1386        memset(y[i].scales, 0, 12);
1387
1388        float d_block = make_qx_quants(QK_K/16, 32, scales, Ls, 1, sw);
1389        for (int j = 0; j < QK_K/16; ++j) {
1390            int l = Ls[j];
1391            if (j < 8) {
1392                y[i].scales[j] = l & 0xF;
1393            } else {
1394                y[i].scales[j-8] |= ((l & 0xF) << 4);
1395            }
1396            l >>= 4;
1397            y[i].scales[j%4 + 8] |= (l << (2*(j/4)));
1398        }
1399        y[i].d = GGML_FP32_TO_FP16(d_block);
1400
1401        int8_t sc;
1402        for (int j = 0; j < QK_K/16; ++j) {
1403            sc = j < 8 ? y[i].scales[j] & 0xF : y[i].scales[j-8] >> 4;
1404            sc = (sc | (((y[i].scales[8 + j%4] >> (2*(j/4))) & 3) << 4)) - 32;
1405            float d = GGML_FP16_TO_FP32(y[i].d) * sc;
1406            if (!d) {
1407                continue;
1408            }
1409            for (int ii = 0; ii < 16; ++ii) {
1410                int l = nearest_int(x[16*j + ii]/d);
1411                l = MAX(-4, MIN(3, l));
1412                L[16*j + ii] = l + 4;
1413            }
1414        }
1415
1416        memset(y[i].hmask, 0, QK_K/8);
1417        // We put the high-bit for the 1st 8 quants into bit 0, the next 8 into bit 1, etc.
1418        int m = 0;
1419        uint8_t hm = 1;
1420        for (int j = 0; j < QK_K; ++j) {
1421            if (L[j] > 3) {
1422                y[i].hmask[m] |= hm;
1423                L[j] -= 4;
1424            }
1425            if (++m == QK_K/8) {
1426                m = 0; hm <<= 1;
1427            }
1428        }
1429        for (int j = 0; j < QK_K; j += 128) {
1430            for (int l = 0; l < 32; ++l) {
1431                y[i].qs[j/4 + l] = L[j + l] | (L[j + l + 32] << 2) | (L[j + l + 64] << 4) | (L[j + l + 96] << 6);
1432            }
1433        }
1434
1435        x += QK_K;
1436    }
1437}
1438
1439size_t quantize_q3_K(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
1440    size_t row_size = ggml_row_size(GGML_TYPE_Q3_K, n_per_row);
1441    if (!quant_weights) {
1442        quantize_row_q3_K_ref(src, dst, (int64_t)nrow*n_per_row);
1443    }
1444    else {
1445        char * qrow = (char *)dst;
1446        for (int64_t row = 0; row < nrow; ++row) {
1447            quantize_row_q3_K_impl(src, (block_q3_K*)qrow, n_per_row, quant_weights);
1448            src += n_per_row;
1449            qrow += row_size;
1450        }
1451    }
1452    return nrow * row_size;
1453}
1454
1455// ====================== 4-bit (de)-quantization
1456
1457void quantize_row_q4_K_ref(const float * GGML_RESTRICT x, block_q4_K * GGML_RESTRICT y, int64_t k) {
1458    assert(k % QK_K == 0);
1459    const int nb = k / QK_K;
1460
1461    uint8_t L[QK_K];
1462    uint8_t Laux[32];
1463    float   weights[32];
1464    float mins[QK_K/32];
1465    float scales[QK_K/32];
1466
1467    for (int i = 0; i < nb; i++) {
1468        float max_scale = 0; // as we are deducting the min, scales are always positive
1469        float max_min = 0;
1470        for (int j = 0; j < QK_K/32; ++j) {
1471            //scales[j] = make_qkx1_quants(32, 15, x + 32*j, L + 32*j, &mins[j], 9, 0.5f);
1472            float sum_x2 = 0;
1473            for (int l = 0; l < 32; ++l) sum_x2 += x[32*j + l] * x[32*j + l];
1474            float av_x = sqrtf(sum_x2/32);
1475            for (int l = 0; l < 32; ++l) weights[l] = av_x + fabsf(x[32*j + l]);
1476            scales[j] = make_qkx2_quants(32, 15, x + 32*j, weights, L + 32*j, &mins[j], Laux, -1.f, 0.1f, 20, false);
1477            float scale = scales[j];
1478            if (scale > max_scale) {
1479                max_scale = scale;
1480            }
1481            float min = mins[j];
1482            if (min > max_min) {
1483                max_min = min;
1484            }
1485        }
1486
1487        float inv_scale = max_scale > 0 ? 63.f/max_scale : 0.f;
1488        float inv_min   = max_min   > 0 ? 63.f/max_min   : 0.f;
1489        for (int j = 0; j < QK_K/32; ++j) {
1490            uint8_t ls = nearest_int(inv_scale*scales[j]);
1491            uint8_t lm = nearest_int(inv_min*mins[j]);
1492            ls = MIN(63, ls);
1493            lm = MIN(63, lm);
1494            if (j < 4) {
1495                y[i].scales[j] = ls;
1496                y[i].scales[j+4] = lm;
1497            } else {
1498                y[i].scales[j+4] = (ls & 0xF) | ((lm & 0xF) << 4);
1499                y[i].scales[j-4] |= ((ls >> 4) << 6);
1500                y[i].scales[j-0] |= ((lm >> 4) << 6);
1501            }
1502        }
1503        y[i].d = GGML_FP32_TO_FP16(max_scale/63.f);
1504        y[i].dmin = GGML_FP32_TO_FP16(max_min/63.f);
1505
1506        uint8_t sc, m;
1507        for (int j = 0; j < QK_K/32; ++j) {
1508            get_scale_min_k4(j, y[i].scales, &sc, &m);
1509            const float d = GGML_FP16_TO_FP32(y[i].d) * sc;
1510            if (!d) continue;
1511            const float dm = GGML_FP16_TO_FP32(y[i].dmin) * m;
1512            for (int ii = 0; ii < 32; ++ii) {
1513                int l = nearest_int((x[32*j + ii] + dm)/d);
1514                l = MAX(0, MIN(15, l));
1515                L[32*j + ii] = l;
1516            }
1517        }
1518
1519        uint8_t * q = y[i].qs;
1520        for (int j = 0; j < QK_K; j += 64) {
1521            for (int l = 0; l < 32; ++l) q[l] = L[j + l] | (L[j + l + 32] << 4);
1522            q += 32;
1523        }
1524
1525        x += QK_K;
1526    }
1527}
1528
1529void dequantize_row_q4_K(const block_q4_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
1530    assert(k % QK_K == 0);
1531    const int nb = k / QK_K;
1532
1533    for (int i = 0; i < nb; i++) {
1534        const uint8_t * q = x[i].qs;
1535
1536        const float d   = GGML_FP16_TO_FP32(x[i].d);
1537        const float min = GGML_FP16_TO_FP32(x[i].dmin);
1538
1539        int is = 0;
1540        uint8_t sc, m;
1541        for (int j = 0; j < QK_K; j += 64) {
1542            get_scale_min_k4(is + 0, x[i].scales, &sc, &m);
1543            const float d1 = d * sc; const float m1 = min * m;
1544            get_scale_min_k4(is + 1, x[i].scales, &sc, &m);
1545            const float d2 = d * sc; const float m2 = min * m;
1546            for (int l = 0; l < 32; ++l) *y++ = d1 * (q[l] & 0xF) - m1;
1547            for (int l = 0; l < 32; ++l) *y++ = d2 * (q[l]  >> 4) - m2;
1548            q += 32; is += 2;
1549        }
1550    }
1551}
1552
1553static void quantize_row_q4_K_impl(const float * GGML_RESTRICT x, block_q4_K * GGML_RESTRICT y, int64_t n_per_row, const float * quant_weights) {
1554    assert(n_per_row % QK_K == 0);
1555    const int64_t nb = n_per_row / QK_K;
1556
1557    uint8_t L[QK_K];
1558    uint8_t Laux[32];
1559    uint8_t Ls[QK_K/32];
1560    uint8_t Lm[QK_K/32];
1561    float   weights[32];
1562    float   sw[QK_K/32];
1563    float   mins[QK_K/32];
1564    float   scales[QK_K/32];
1565
1566    for (int i = 0; i < nb; i++) {
1567
1568        float sum_x2 = 0;
1569        for (int l = 0; l < QK_K; ++l) sum_x2 += x[l] * x[l];
1570        float sigma2 = 2*sum_x2/QK_K;
1571        float av_x = sqrtf(sigma2);
1572
1573        for (int j = 0; j < QK_K/32; ++j) {
1574            if (quant_weights) {
1575                const float * qw = quant_weights + QK_K*i + 32*j;
1576                for (int l = 0; l < 32; ++l) weights[l] = qw[l] * sqrtf(sigma2 + x[32*j + l]*x[32*j + l]);
1577            } else {
1578                for (int l = 0; l < 32; ++l) weights[l] = av_x + fabsf(x[32*j + l]);
1579            }
1580            float sumw = 0;
1581            for (int l = 0; l < 32; ++l) sumw += weights[l];
1582            sw[j] = sumw;
1583            scales[j] = make_qkx3_quants(32, 15, x + 32*j, weights, L + 32*j, &mins[j], Laux, -0.9f, 0.05f, 36, false);
1584        }
1585
1586        float d_block = make_qp_quants(QK_K/32, 63, scales, Ls, sw);
1587        float m_block = make_qp_quants(QK_K/32, 63, mins,   Lm, sw);
1588        for (int j = 0; j < QK_K/32; ++j) {
1589            uint8_t ls = Ls[j];
1590            uint8_t lm = Lm[j];
1591            if (j < 4) {
1592                y[i].scales[j] = ls;
1593                y[i].scales[j+4] = lm;
1594            } else {
1595                y[i].scales[j+4] = (ls & 0xF) | ((lm & 0xF) << 4);
1596                y[i].scales[j-4] |= ((ls >> 4) << 6);
1597                y[i].scales[j-0] |= ((lm >> 4) << 6);
1598            }
1599        }
1600        y[i].d = GGML_FP32_TO_FP16(d_block);
1601        y[i].dmin = GGML_FP32_TO_FP16(m_block);
1602
1603        uint8_t sc, m;
1604        for (int j = 0; j < QK_K/32; ++j) {
1605            get_scale_min_k4(j, y[i].scales, &sc, &m);
1606            const float d = GGML_FP16_TO_FP32(y[i].d) * sc;
1607            if (!d) continue;
1608            const float dm = GGML_FP16_TO_FP32(y[i].dmin) * m;
1609            for (int ii = 0; ii < 32; ++ii) {
1610                int l = nearest_int((x[32*j + ii] + dm)/d);
1611                l = MAX(0, MIN(15, l));
1612                L[32*j + ii] = l;
1613            }
1614        }
1615        uint8_t * q = y[i].qs;
1616        for (int j = 0; j < QK_K; j += 64) {
1617            for (int l = 0; l < 32; ++l) q[l] = L[j + l] | (L[j + l + 32] << 4);
1618            q += 32;
1619        }
1620
1621        x += QK_K;
1622
1623    }
1624}
1625
1626size_t quantize_q4_K(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
1627    size_t row_size = ggml_row_size(GGML_TYPE_Q4_K, n_per_row);
1628    if (!quant_weights) {
1629        quantize_row_q4_K_ref(src, dst, (int64_t)nrow*n_per_row);
1630    }
1631    else {
1632        char * qrow = (char *)dst;
1633        for (int64_t row = 0; row < nrow; ++row) {
1634            quantize_row_q4_K_impl(src, (block_q4_K*)qrow, n_per_row, quant_weights);
1635            src += n_per_row;
1636            qrow += row_size;
1637        }
1638    }
1639    return nrow * row_size;
1640}
1641
1642// ====================== 5-bit (de)-quantization
1643
1644void quantize_row_q5_K_ref(const float * GGML_RESTRICT x, block_q5_K * GGML_RESTRICT y, int64_t k) {
1645    assert(k % QK_K == 0);
1646    const int64_t nb = k / QK_K;
1647
1648    uint8_t L[QK_K];
1649    float mins[QK_K/32];
1650    float scales[QK_K/32];
1651    float weights[32];
1652    uint8_t Laux[32];
1653
1654    for (int i = 0; i < nb; i++) {
1655        float max_scale = 0; // as we are deducting the min, scales are always positive
1656        float max_min = 0;
1657        for (int j = 0; j < QK_K/32; ++j) {
1658            //scales[j] = make_qkx1_quants(32, 31, x + 32*j, L + 32*j, &mins[j], 9, 0.5f);
1659            float sum_x2 = 0;
1660            for (int l = 0; l < 32; ++l) sum_x2 += x[32*j + l] * x[32*j + l];
1661            float av_x = sqrtf(sum_x2/32);
1662            for (int l = 0; l < 32; ++l) weights[l] = av_x + fabsf(x[32*j + l]);
1663            scales[j] = make_qkx2_quants(32, 31, x + 32*j, weights, L + 32*j, &mins[j], Laux, -0.5f, 0.1f, 15, false);
1664            float scale = scales[j];
1665            if (scale > max_scale) {
1666                max_scale = scale;
1667            }
1668            float min = mins[j];
1669            if (min > max_min) {
1670                max_min = min;
1671            }
1672        }
1673
1674        float inv_scale = max_scale > 0 ? 63.f/max_scale : 0.f;
1675        float inv_min   = max_min   > 0 ? 63.f/max_min   : 0.f;
1676        for (int j = 0; j < QK_K/32; ++j) {
1677            uint8_t ls = nearest_int(inv_scale*scales[j]);
1678            uint8_t lm = nearest_int(inv_min*mins[j]);
1679            ls = MIN(63, ls);
1680            lm = MIN(63, lm);
1681            if (j < 4) {
1682                y[i].scales[j] = ls;
1683                y[i].scales[j+4] = lm;
1684            } else {
1685                y[i].scales[j+4] = (ls & 0xF) | ((lm & 0xF) << 4);
1686                y[i].scales[j-4] |= ((ls >> 4) << 6);
1687                y[i].scales[j-0] |= ((lm >> 4) << 6);
1688            }
1689        }
1690        y[i].d = GGML_FP32_TO_FP16(max_scale/63.f);
1691        y[i].dmin = GGML_FP32_TO_FP16(max_min/63.f);
1692
1693        uint8_t sc, m;
1694        for (int j = 0; j < QK_K/32; ++j) {
1695            get_scale_min_k4(j, y[i].scales, &sc, &m);
1696            const float d = GGML_FP16_TO_FP32(y[i].d) * sc;
1697            if (!d) continue;
1698            const float dm = GGML_FP16_TO_FP32(y[i].dmin) * m;
1699            for (int ii = 0; ii < 32; ++ii) {
1700                int l = nearest_int((x[32*j + ii] + dm)/d);
1701                l = MAX(0, MIN(31, l));
1702                L[32*j + ii] = l;
1703            }
1704        }
1705
1706        uint8_t * GGML_RESTRICT qh = y[i].qh;
1707        uint8_t * GGML_RESTRICT ql = y[i].qs;
1708        memset(qh, 0, QK_K/8);
1709
1710        uint8_t m1 = 1, m2 = 2;
1711        for (int n = 0; n < QK_K; n += 64) {
1712            for (int j = 0; j < 32; ++j) {
1713                int l1 = L[n + j];
1714                if (l1 > 15) {
1715                    l1 -= 16; qh[j] |= m1;
1716                }
1717                int l2 = L[n + j + 32];
1718                if (l2 > 15) {
1719                    l2 -= 16; qh[j] |= m2;
1720                }
1721                ql[j] = l1 | (l2 << 4);
1722            }
1723            m1 <<= 2; m2 <<= 2;
1724            ql += 32;
1725        }
1726
1727        x += QK_K;
1728    }
1729}
1730
1731void dequantize_row_q5_K(const block_q5_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
1732    assert(k % QK_K == 0);
1733    const int64_t nb = k / QK_K;
1734
1735    for (int i = 0; i < nb; i++) {
1736        const uint8_t * ql = x[i].qs;
1737        const uint8_t * qh = x[i].qh;
1738
1739        const float d = GGML_FP16_TO_FP32(x[i].d);
1740        const float min = GGML_FP16_TO_FP32(x[i].dmin);
1741
1742        int is = 0;
1743        uint8_t sc, m;
1744        uint8_t u1 = 1, u2 = 2;
1745        for (int j = 0; j < QK_K; j += 64) {
1746            get_scale_min_k4(is + 0, x[i].scales, &sc, &m);
1747            const float d1 = d * sc; const float m1 = min * m;
1748            get_scale_min_k4(is + 1, x[i].scales, &sc, &m);
1749            const float d2 = d * sc; const float m2 = min * m;
1750            for (int l = 0; l < 32; ++l) *y++ = d1 * ((ql[l] & 0xF) + (qh[l] & u1 ? 16 : 0)) - m1;
1751            for (int l = 0; l < 32; ++l) *y++ = d2 * ((ql[l]  >> 4) + (qh[l] & u2 ? 16 : 0)) - m2;
1752            ql += 32; is += 2;
1753            u1 <<= 2; u2 <<= 2;
1754        }
1755    }
1756}
1757
1758static void quantize_row_q5_K_impl(const float * GGML_RESTRICT x, block_q5_K * GGML_RESTRICT y, int64_t n_per_row, const float * quant_weights) {
1759    assert(n_per_row % QK_K == 0);
1760    const int64_t nb = n_per_row / QK_K;
1761
1762    uint8_t L[QK_K];
1763    uint8_t Laux[32];
1764    uint8_t Ls[QK_K/32];
1765    uint8_t Lm[QK_K/32];
1766    float   mins[QK_K/32];
1767    float   scales[QK_K/32];
1768    float   sw[QK_K/32];
1769    float   weights[32];
1770
1771    for (int i = 0; i < nb; i++) {
1772
1773        float sum_x2 = 0;
1774        for (int l = 0; l < QK_K; ++l) sum_x2 += x[l] * x[l];
1775        float sigma2 = 2*sum_x2/QK_K;
1776        float av_x = sqrtf(sigma2);
1777
1778        for (int j = 0; j < QK_K/32; ++j) {
1779            if (quant_weights) {
1780                const float * qw = quant_weights + QK_K*i + 32*j;
1781                for (int l = 0; l < 32; ++l) weights[l] = qw[l] * sqrtf(sigma2 + x[32*j + l]*x[32*j + l]);
1782            } else {
1783                for (int l = 0; l < 32; ++l) weights[l] = av_x + fabsf(x[32*j + l]);
1784            }
1785            float sumw = 0;
1786            for (int l = 0; l < 32; ++l) sumw += weights[l];
1787            sw[j] = sumw;
1788
1789            scales[j] = make_qkx3_quants(32, 31, x + 32*j, weights, L + 32*j, &mins[j], Laux, -0.9f, 0.05f, 36, false);
1790        }
1791
1792        float d_block = make_qp_quants(QK_K/32, 63, scales, Ls, sw);
1793        float m_block = make_qp_quants(QK_K/32, 63, mins,   Lm, sw);
1794
1795        for (int j = 0; j < QK_K/32; ++j) {
1796            uint8_t ls = Ls[j];
1797            uint8_t lm = Lm[j];
1798            ls = MIN(63, ls);
1799            lm = MIN(63, lm);
1800            if (j < 4) {
1801                y[i].scales[j] = ls;
1802                y[i].scales[j+4] = lm;
1803            } else {
1804                y[i].scales[j+4] = (ls & 0xF) | ((lm & 0xF) << 4);
1805                y[i].scales[j-4] |= ((ls >> 4) << 6);
1806                y[i].scales[j-0] |= ((lm >> 4) << 6);
1807            }
1808        }
1809        y[i].d = GGML_FP32_TO_FP16(d_block);
1810        y[i].dmin = GGML_FP32_TO_FP16(m_block);
1811
1812        uint8_t sc, m;
1813        for (int j = 0; j < QK_K/32; ++j) {
1814            get_scale_min_k4(j, y[i].scales, &sc, &m);
1815            const float d = GGML_FP16_TO_FP32(y[i].d) * sc;
1816            if (!d) continue;
1817            const float dm = GGML_FP16_TO_FP32(y[i].dmin) * m;
1818            for (int ii = 0; ii < 32; ++ii) {
1819                int l = nearest_int((x[32*j + ii] + dm)/d);
1820                l = MAX(0, MIN(31, l));
1821                L[32*j + ii] = l;
1822            }
1823        }
1824
1825        uint8_t * GGML_RESTRICT qh = y[i].qh;
1826        uint8_t * GGML_RESTRICT ql = y[i].qs;
1827        memset(qh, 0, QK_K/8);
1828
1829        uint8_t m1 = 1, m2 = 2;
1830        for (int n = 0; n < QK_K; n += 64) {
1831            for (int j = 0; j < 32; ++j) {
1832                int l1 = L[n + j];
1833                if (l1 > 15) {
1834                    l1 -= 16; qh[j] |= m1;
1835                }
1836                int l2 = L[n + j + 32];
1837                if (l2 > 15) {
1838                    l2 -= 16; qh[j] |= m2;
1839                }
1840                ql[j] = l1 | (l2 << 4);
1841            }
1842            m1 <<= 2; m2 <<= 2;
1843            ql += 32;
1844        }
1845
1846        x += QK_K;
1847
1848    }
1849}
1850
1851size_t quantize_q5_K(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
1852    size_t row_size = ggml_row_size(GGML_TYPE_Q5_K, n_per_row);
1853    if (!quant_weights) {
1854        quantize_row_q5_K_ref(src, dst, (int64_t)nrow*n_per_row);
1855    }
1856    else {
1857        char * qrow = (char *)dst;
1858        for (int64_t row = 0; row < nrow; ++row) {
1859            quantize_row_q5_K_impl(src, (block_q5_K*)qrow, n_per_row, quant_weights);
1860            src += n_per_row;
1861            qrow += row_size;
1862        }
1863    }
1864    return nrow * row_size;
1865}
1866
1867// ====================== 6-bit (de)-quantization
1868
1869void quantize_row_q6_K_ref(const float * GGML_RESTRICT x, block_q6_K * GGML_RESTRICT y, int64_t k) {
1870    assert(k % QK_K == 0);
1871    const int64_t nb = k / QK_K;
1872
1873    int8_t L[QK_K];
1874    float   scales[QK_K/16];
1875
1876    for (int i = 0; i < nb; i++) {
1877
1878        float max_scale = 0;
1879        float max_abs_scale = 0;
1880
1881        for (int ib = 0; ib < QK_K/16; ++ib) {
1882
1883            const float scale = make_qx_quants(16, 32, x + 16*ib, L + 16*ib, 1, NULL);
1884            scales[ib] = scale;
1885
1886            const float abs_scale = fabsf(scale);
1887            if (abs_scale > max_abs_scale) {
1888                max_abs_scale = abs_scale;
1889                max_scale = scale;
1890            }
1891
1892        }
1893
1894        if (max_abs_scale < GROUP_MAX_EPS) {
1895            memset(&y[i], 0, sizeof(block_q6_K));
1896            y[i].d = GGML_FP32_TO_FP16(0.f);
1897            x += QK_K;
1898            continue;
1899        }
1900
1901        float iscale = -128.f/max_scale;
1902        y[i].d = GGML_FP32_TO_FP16(1/iscale);
1903        for (int ib = 0; ib < QK_K/16; ++ib) {
1904            y[i].scales[ib] = MIN(127, nearest_int(iscale*scales[ib]));
1905        }
1906
1907        for (int j = 0; j < QK_K/16; ++j) {
1908            float d = GGML_FP16_TO_FP32(y[i].d) * y[i].scales[j];
1909            if (!d) {
1910                continue;
1911            }
1912            for (int ii = 0; ii < 16; ++ii) {
1913                int l = nearest_int(x[16*j + ii]/d);
1914                l = MAX(-32, MIN(31, l));
1915                L[16*j + ii] = l + 32;
1916            }
1917        }
1918
1919        uint8_t * GGML_RESTRICT ql = y[i].ql;
1920        uint8_t * GGML_RESTRICT qh = y[i].qh;
1921        for (int j = 0; j < QK_K; j += 128) {
1922            for (int l = 0; l < 32; ++l) {
1923                const uint8_t q1 = L[j + l +  0] & 0xF;
1924                const uint8_t q2 = L[j + l + 32] & 0xF;
1925                const uint8_t q3 = L[j + l + 64] & 0xF;
1926                const uint8_t q4 = L[j + l + 96] & 0xF;
1927                ql[l+ 0] = q1 | (q3 << 4);
1928                ql[l+32] = q2 | (q4 << 4);
1929                qh[l] = (L[j + l] >> 4) | ((L[j + l + 32] >> 4) << 2) | ((L[j + l + 64] >> 4) << 4) | ((L[j + l + 96] >> 4) << 6);
1930            }
1931            ql += 64;
1932            qh += 32;
1933        }
1934
1935        x += QK_K;
1936    }
1937}
1938
1939void dequantize_row_q6_K(const block_q6_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
1940    assert(k % QK_K == 0);
1941    const int64_t nb = k / QK_K;
1942
1943    for (int i = 0; i < nb; i++) {
1944        const float d = GGML_FP16_TO_FP32(x[i].d);
1945
1946        const uint8_t * GGML_RESTRICT ql = x[i].ql;
1947        const uint8_t * GGML_RESTRICT qh = x[i].qh;
1948        const int8_t  * GGML_RESTRICT sc = x[i].scales;
1949
1950        for (int n = 0; n < QK_K; n += 128) {
1951            for (int l = 0; l < 32; ++l) {
1952                int is = l/16;
1953                const int8_t q1 = (int8_t)((ql[l +  0] & 0xF) | (((qh[l] >> 0) & 3) << 4)) - 32;
1954                const int8_t q2 = (int8_t)((ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4)) - 32;
1955                const int8_t q3 = (int8_t)((ql[l +  0]  >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32;
1956                const int8_t q4 = (int8_t)((ql[l + 32]  >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32;
1957                y[l +  0] = d * sc[is + 0] * q1;
1958                y[l + 32] = d * sc[is + 2] * q2;
1959                y[l + 64] = d * sc[is + 4] * q3;
1960                y[l + 96] = d * sc[is + 6] * q4;
1961            }
1962            y  += 128;
1963            ql += 64;
1964            qh += 32;
1965            sc += 8;
1966        }
1967    }
1968}
1969
1970static void quantize_row_q6_K_impl(const float * GGML_RESTRICT x, block_q6_K * GGML_RESTRICT y, int64_t n_per_row, const float * quant_weights) {
1971    assert(n_per_row % QK_K == 0);
1972    const int64_t nb = n_per_row / QK_K;
1973
1974    int8_t L[QK_K];
1975    float   scales[QK_K/16];
1976    //float   weights[16];
1977
1978    for (int i = 0; i < nb; i++) {
1979
1980        //float sum_x2 = 0;
1981        //for (int j = 0; j < QK_K; ++j) sum_x2 += x[j]*x[j];
1982        //float sigma2 = sum_x2/QK_K;
1983
1984        float max_scale = 0;
1985        float max_abs_scale = 0;
1986
1987        for (int ib = 0; ib < QK_K/16; ++ib) {
1988
1989            float scale;
1990            if (quant_weights) {
1991                const float * qw = quant_weights + QK_K*i + 16*ib;
1992                //for (int j = 0; j < 16; ++j) weights[j] = qw[j] * sqrtf(sigma2 + x[16*ib + j]*x[16*ib + j]);
1993                //scale = make_qx_quants(16, 32, x + 16*ib, L + 16*ib, 1, weights);
1994                scale = make_qx_quants(16, 32, x + 16*ib, L + 16*ib, 1, qw);
1995            } else {
1996                scale = make_qx_quants(16, 32, x + 16*ib, L + 16*ib, 1, NULL);
1997            }
1998            scales[ib] = scale;
1999
2000            const float abs_scale = fabsf(scale);
2001            if (abs_scale > max_abs_scale) {
2002                max_abs_scale = abs_scale;
2003                max_scale = scale;
2004            }
2005
2006        }
2007
2008        if (max_abs_scale < GROUP_MAX_EPS) {
2009            memset(&y[i], 0, sizeof(block_q6_K));
2010            y[i].d = GGML_FP32_TO_FP16(0.f);
2011            x += QK_K;
2012            continue;
2013        }
2014
2015        float iscale = -128.f/max_scale;
2016        y[i].d = GGML_FP32_TO_FP16(1/iscale);
2017        for (int ib = 0; ib < QK_K/16; ++ib) {
2018            y[i].scales[ib] = MIN(127, nearest_int(iscale*scales[ib]));
2019        }
2020
2021        for (int j = 0; j < QK_K/16; ++j) {
2022            float d = GGML_FP16_TO_FP32(y[i].d) * y[i].scales[j];
2023            if (!d) {
2024                continue;
2025            }
2026            for (int ii = 0; ii < 16; ++ii) {
2027                int l = nearest_int(x[16*j + ii]/d);
2028                l = MAX(-32, MIN(31, l));
2029                L[16*j + ii] = l + 32;
2030            }
2031        }
2032
2033        uint8_t * GGML_RESTRICT ql = y[i].ql;
2034        uint8_t * GGML_RESTRICT qh = y[i].qh;
2035        for (int j = 0; j < QK_K; j += 128) {
2036            for (int l = 0; l < 32; ++l) {
2037                const uint8_t q1 = L[j + l +  0] & 0xF;
2038                const uint8_t q2 = L[j + l + 32] & 0xF;
2039                const uint8_t q3 = L[j + l + 64] & 0xF;
2040                const uint8_t q4 = L[j + l + 96] & 0xF;
2041                ql[l+ 0] = q1 | (q3 << 4);
2042                ql[l+32] = q2 | (q4 << 4);
2043                qh[l] = (L[j + l] >> 4) | ((L[j + l + 32] >> 4) << 2) | ((L[j + l + 64] >> 4) << 4) | ((L[j + l + 96] >> 4) << 6);
2044            }
2045            ql += 64;
2046            qh += 32;
2047        }
2048
2049        x += QK_K;
2050
2051    }
2052}
2053
2054size_t quantize_q6_K(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
2055    size_t row_size = ggml_row_size(GGML_TYPE_Q6_K, n_per_row);
2056    if (!quant_weights) {
2057        quantize_row_q6_K_ref(src, dst, (int64_t)nrow*n_per_row);
2058    }
2059    else {
2060        char * qrow = (char *)dst;
2061        for (int64_t row = 0; row < nrow; ++row) {
2062            quantize_row_q6_K_impl(src, (block_q6_K*)qrow, n_per_row, quant_weights);
2063            src += n_per_row;
2064            qrow += row_size;
2065        }
2066    }
2067    return nrow * row_size;
2068}
2069
2070static void quantize_row_q4_0_impl(const float * GGML_RESTRICT x, block_q4_0 * GGML_RESTRICT y, int64_t n_per_row, const float * quant_weights) {
2071    static_assert(QK4_0 == 32, "QK4_0 must be 32");
2072
2073    if (!quant_weights) {
2074        quantize_row_q4_0_ref(x, y, n_per_row);
2075        return;
2076    }
2077
2078    float weight[QK4_0];
2079    int8_t L[QK4_0];
2080
2081    float sum_x2 = 0;
2082    for (int j = 0; j < n_per_row; ++j) sum_x2 += x[j]*x[j];
2083    float sigma2 = sum_x2/n_per_row;
2084
2085    const int64_t nb = n_per_row/QK4_0;
2086    for (int ib = 0; ib < nb; ++ib) {
2087        const float * xb = x + QK4_0 * ib;
2088        const float * qw = quant_weights + QK4_0 * ib;
2089        for (int j = 0; j < QK4_0; ++j) weight[j] = qw[j] * sqrtf(sigma2 + xb[j]*xb[j]);
2090        float d = make_qx_quants(QK4_0, 8, xb, L, 1, weight);
2091        y[ib].d = GGML_FP32_TO_FP16(d);
2092        for (int j = 0; j < 16; ++j) {
2093            y[ib].qs[j] = L[j] | (L[j+16] << 4);
2094        }
2095    }
2096}
2097
2098size_t quantize_q1_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
2099    if (!quant_weights) {
2100        quantize_row_q1_0_ref(src, dst, (int64_t)nrow*n_per_row);
2101        return nrow * ggml_row_size(GGML_TYPE_Q1_0, n_per_row);
2102    }
2103    size_t row_size = ggml_row_size(GGML_TYPE_Q1_0, n_per_row);
2104    char * qrow = (char *)dst;
2105    for (int64_t row = 0; row < nrow; ++row) {
2106        quantize_row_q1_0_ref(src, (block_q1_0*)qrow, n_per_row);
2107        src += n_per_row;
2108        qrow += row_size;
2109    }
2110    return nrow * row_size;
2111}
2112
2113size_t quantize_q2_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
2114    if (!quant_weights) {
2115        quantize_row_q2_0_ref(src, dst, (int64_t)nrow*n_per_row);
2116        return nrow * ggml_row_size(GGML_TYPE_Q2_0, n_per_row);
2117    }
2118    size_t row_size = ggml_row_size(GGML_TYPE_Q2_0, n_per_row);
2119    char * qrow = (char *)dst;
2120    for (int64_t row = 0; row < nrow; ++row) {
2121        quantize_row_q2_0_ref(src, (block_q2_0*)qrow, n_per_row);
2122        src += n_per_row;
2123        qrow += row_size;
2124    }
2125    return nrow * row_size;
2126}
2127
2128size_t quantize_q4_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
2129    if (!quant_weights) {
2130        quantize_row_q4_0_ref(src, dst, (int64_t)nrow*n_per_row);
2131        return nrow * ggml_row_size(GGML_TYPE_Q4_0, n_per_row);
2132    }
2133    size_t row_size = ggml_row_size(GGML_TYPE_Q4_0, n_per_row);
2134    char * qrow = (char *)dst;
2135    for (int64_t row = 0; row < nrow; ++row) {
2136        quantize_row_q4_0_impl(src, (block_q4_0*)qrow, n_per_row, quant_weights);
2137        src += n_per_row;
2138        qrow += row_size;
2139    }
2140    return nrow * row_size;
2141}
2142
2143static void quantize_row_q4_1_impl(const float * GGML_RESTRICT x, block_q4_1 * GGML_RESTRICT y, int64_t n_per_row, const float * quant_weights) {
2144    static_assert(QK4_1 == 32, "QK4_1 must be 32");
2145
2146    if (!quant_weights) {
2147        quantize_row_q4_1_ref(x, y, n_per_row);
2148        return;
2149    }
2150
2151    float weight[QK4_1];
2152    uint8_t L[QK4_1], Laux[QK4_1];
2153
2154    float sum_x2 = 0;
2155    for (int j = 0; j < n_per_row; ++j) sum_x2 += x[j]*x[j];
2156    float sigma2 = sum_x2/n_per_row;
2157
2158    const int64_t nb = n_per_row/QK4_1;
2159    for (int ib = 0; ib < nb; ++ib) {
2160        const float * xb = x + QK4_1 * ib;
2161        const float * qw = quant_weights + QK4_1 * ib;
2162        for (int j = 0; j < QK4_1; ++j) weight[j] = qw[j] * sqrtf(sigma2 + xb[j]*xb[j]);
2163        float min;
2164        float d = make_qkx3_quants(QK4_1, 15, xb, weight, L, &min, Laux, -0.9f, 0.05f, 36, false);
2165        y[ib].d = GGML_FP32_TO_FP16(d);
2166        y[ib].m = GGML_FP32_TO_FP16(-min);
2167        for (int j = 0; j < 16; ++j) {
2168            y[ib].qs[j] = L[j] | (L[j+16] << 4);
2169        }
2170    }
2171}
2172
2173size_t quantize_q4_1(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
2174    if (!quant_weights) {
2175        quantize_row_q4_1_ref(src, dst, (int64_t)nrow*n_per_row);
2176        return nrow * ggml_row_size(GGML_TYPE_Q4_1, n_per_row);
2177    }
2178    size_t row_size = ggml_row_size(GGML_TYPE_Q4_1, n_per_row);
2179    char * qrow = (char *)dst;
2180    for (int64_t row = 0; row < nrow; ++row) {
2181        quantize_row_q4_1_impl(src, (block_q4_1*)qrow, n_per_row, quant_weights);
2182        src += n_per_row;
2183        qrow += row_size;
2184    }
2185    return nrow * row_size;
2186}
2187
2188static void quantize_row_q5_0_impl(const float * GGML_RESTRICT x, block_q5_0 * GGML_RESTRICT y, int64_t n_per_row, const float * quant_weights) {
2189    static_assert(QK5_0 == 32, "QK5_0 must be 32");
2190
2191    if (!quant_weights) {
2192        quantize_row_q5_0_ref(x, y, n_per_row);
2193        return;
2194    }
2195
2196    float weight[QK5_0];
2197    int8_t L[QK5_0];
2198
2199    float sum_x2 = 0;
2200    for (int j = 0; j < n_per_row; ++j) sum_x2 += x[j]*x[j];
2201    float sigma2 = sum_x2/n_per_row;
2202
2203    const int64_t nb = n_per_row/QK5_0;
2204    for (int ib = 0; ib < nb; ++ib) {
2205        const float * xb = x + QK5_0 * ib;
2206        const float * qw = quant_weights + QK5_0 * ib;
2207        for (int j = 0; j < QK5_0; ++j) weight[j] = qw[j] * sqrtf(sigma2 + xb[j]*xb[j]);
2208        float d = make_qx_quants(QK5_0, 16, xb, L, 1, weight);
2209        y[ib].d = GGML_FP32_TO_FP16(d);
2210
2211        uint32_t qh = 0;
2212
2213        for (int j = 0; j < 16; ++j) {
2214            const uint8_t xi0 = L[j];
2215            const uint8_t xi1 = L[j+16];
2216            y[ib].qs[j] = (xi0 & 0x0F) | ((xi1 & 0x0F) << 4);
2217
2218            // get the 5-th bit and store it in qh at the right position
2219            qh |= ((xi0 & 0x10u) >> 4) << (j + 0);
2220            qh |= ((xi1 & 0x10u) >> 4) << (j + QK5_0/2);
2221        }
2222
2223        memcpy(&y[ib].qh, &qh, sizeof(qh));
2224    }
2225}
2226
2227size_t quantize_q5_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
2228    if (!quant_weights) {
2229        quantize_row_q5_0_ref(src, dst, (int64_t)nrow*n_per_row);
2230        return nrow * ggml_row_size(GGML_TYPE_Q5_0, n_per_row);
2231    }
2232    size_t row_size = ggml_row_size(GGML_TYPE_Q5_0, n_per_row);
2233    char * qrow = (char *)dst;
2234    for (int64_t row = 0; row < nrow; ++row) {
2235        quantize_row_q5_0_impl(src, (block_q5_0*)qrow, n_per_row, quant_weights);
2236        src += n_per_row;
2237        qrow += row_size;
2238    }
2239    return nrow * row_size;
2240}
2241
2242static void quantize_row_q5_1_impl(const float * GGML_RESTRICT x, block_q5_1 * GGML_RESTRICT y, int64_t n_per_row, const float * quant_weights) {
2243    static_assert(QK5_1 == 32, "QK5_1 must be 32");
2244
2245    if (!quant_weights) {
2246        quantize_row_q5_1_ref(x, y, n_per_row);
2247        return;
2248    }
2249
2250    float weight[QK5_1];
2251    uint8_t L[QK5_1], Laux[QK5_1];
2252
2253    float sum_x2 = 0;
2254    for (int j = 0; j < n_per_row; ++j) sum_x2 += x[j]*x[j];
2255    float sigma2 = sum_x2/n_per_row;
2256
2257    const int64_t nb = n_per_row/QK5_1;
2258    for (int ib = 0; ib < nb; ++ib) {
2259        const float * xb = x + QK5_1 * ib;
2260        const float * qw = quant_weights + QK5_1 * ib;
2261        for (int j = 0; j < QK5_1; ++j) weight[j] = qw[j] * sqrtf(sigma2 + xb[j]*xb[j]);
2262        float min;
2263        float d = make_qkx3_quants(QK5_1, 31, xb, weight, L, &min, Laux, -0.9f, 0.05f, 36, false);
2264        y[ib].d = GGML_FP32_TO_FP16(d);
2265        y[ib].m = GGML_FP32_TO_FP16(-min);
2266
2267        uint32_t qh = 0;
2268        for (int j = 0; j < 16; ++j) {
2269            const uint8_t xi0 = L[j];
2270            const uint8_t xi1 = L[j+16];
2271            y[ib].qs[j] = (xi0 & 0x0F) | ((xi1 & 0x0F) << 4);
2272            // get the 5-th bit and store it in qh at the right position
2273            qh |= ((xi0 & 0x10u) >> 4) << (j + 0);
2274            qh |= ((xi1 & 0x10u) >> 4) << (j + QK5_0/2);
2275        }
2276        memcpy(&y[ib].qh, &qh, sizeof(qh));
2277    }
2278}
2279
2280size_t quantize_q5_1(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
2281    if (!quant_weights) {
2282        quantize_row_q5_1_ref(src, dst, (int64_t)nrow*n_per_row);
2283        return nrow * ggml_row_size(GGML_TYPE_Q5_1, n_per_row);
2284    }
2285    size_t row_size = ggml_row_size(GGML_TYPE_Q5_1, n_per_row);
2286    char * qrow = (char *)dst;
2287    for (int64_t row = 0; row < nrow; ++row) {
2288        quantize_row_q5_1_impl(src, (block_q5_1*)qrow, n_per_row, quant_weights);
2289        src += n_per_row;
2290        qrow += row_size;
2291    }
2292    return nrow * row_size;
2293}
2294
2295size_t quantize_q8_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
2296    (void)quant_weights; // not used
2297    const size_t row_size = ggml_row_size(GGML_TYPE_Q8_0, n_per_row);
2298    quantize_row_q8_0_ref(src, dst, (int64_t)nrow*n_per_row);
2299    return nrow * row_size;
2300}
2301
2302size_t quantize_mxfp4(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
2303    GGML_UNUSED(quant_weights);
2304    quantize_row_mxfp4_ref(src, dst, (int64_t)nrow*n_per_row);
2305    return nrow * ggml_row_size(GGML_TYPE_MXFP4, n_per_row);
2306}
2307
2308size_t quantize_nvfp4(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
2309    GGML_UNUSED(quant_weights);
2310    quantize_row_nvfp4_ref(src, dst, (int64_t)nrow*n_per_row);
2311    return nrow * ggml_row_size(GGML_TYPE_NVFP4, n_per_row);
2312}
2313
2314// ====================== Ternary (de)-quantization (BitNet b1.58 and TriLMs)
2315
2316void quantize_row_tq1_0_ref(const float * GGML_RESTRICT x, block_tq1_0 * GGML_RESTRICT y, int64_t k) {
2317    assert(k % QK_K == 0);
2318    const int64_t nb = k / QK_K;
2319
2320    for (int64_t i = 0; i < nb; i++) {
2321        float amax = 0.0f; // absolute max
2322
2323        for (int j = 0; j < QK_K; j++) {
2324            const float v = x[j];
2325            amax = MAX(amax, fabsf(v));
2326        }
2327
2328        const float d = amax;
2329        const float id = d ? 1.0f/d : 0.0f;
2330
2331        y[i].d = GGML_FP32_TO_FP16(d);
2332
2333        // 5 elements per byte, along 32 bytes
2334        for (size_t j = 0; j < sizeof(y->qs) - sizeof(y->qs) % 32; j += 32) {
2335            for (size_t m = 0; m < 32; ++m) {
2336                uint8_t q = 0;
2337                for (size_t n = 0; n < 5; ++n) {
2338                    int xi = lroundf(x[m + n*32] * id) + 1; // -1, 0, 1 -> 0, 1, 2
2339                    q *= 3;
2340                    q += xi;
2341                }
2342                // ceiling division (243 == pow(3, 5))
2343                q = ((uint16_t)q * 256 + (243 - 1)) / 243;
2344                y[i].qs[j + m] = q;
2345            }
2346            x += 5*32;
2347        }
2348        // along 16 bytes
2349        for (size_t j = sizeof(y->qs) - sizeof(y->qs) % 32; j < sizeof(y->qs); j += 16) {
2350            for (size_t m = 0; m < 16; ++m) {
2351                uint8_t q = 0;
2352                for (size_t n = 0; n < 5; ++n) {
2353                    int xi = lroundf(x[m + n*16] * id) + 1; // -1, 0, 1 -> 0, 1, 2
2354                    q *= 3;
2355                    q += xi;
2356                }
2357                // ceiling division (243 == pow(3, 5))
2358                q = ((uint16_t)q * 256 + (243 - 1)) / 243;
2359                y[i].qs[j + m] = q;
2360            }
2361            x += 5*16;
2362        }
2363        // 4 elements per byte
2364        for (size_t j = 0; j < sizeof(y->qh); ++j) {
2365            uint8_t q = 0;
2366            for (size_t m = 0; m < 4; ++m) {
2367                // -1, 0, 1 -> 0, 1, 2
2368                int xi = lroundf(x[j + m*sizeof(y->qh)] * id) + 1;
2369                q *= 3;
2370                q += xi;
2371            }
2372            // shift the first value to the most significant trit
2373            q *= 3;
2374            // ceiling division (243 == pow(3, 5))
2375            q = ((uint16_t)q * 256 + (243 - 1)) / 243;
2376            y[i].qh[j] = q;
2377        }
2378        x += 4*sizeof(y->qh);
2379    }
2380}
2381
2382void quantize_row_tq2_0_ref(const float * GGML_RESTRICT x, block_tq2_0 * GGML_RESTRICT y, int64_t k) {
2383    assert(k % QK_K == 0);
2384    const int64_t nb = k / QK_K;
2385
2386    for (int64_t i = 0; i < nb; i++) {
2387        float amax = 0.0f; // absolute max
2388
2389        for (int j = 0; j < QK_K; j++) {
2390            const float v = x[j];
2391            amax = MAX(amax, fabsf(v));
2392        }
2393
2394        const float d = amax;
2395        const float id = d ? 1.0f/d : 0.0f;
2396
2397        y[i].d = GGML_FP32_TO_FP16(d);
2398
2399        for (size_t j = 0; j < sizeof(y->qs); j += 32) {
2400            for (size_t m = 0; m < 32; ++m) {
2401                uint8_t q = 0;
2402                for (size_t n = 0; n < 4; ++n) {
2403                    // -1, 0, 1 -> 0, 1, 2
2404                    int xi = lroundf(x[m + n*32] * id) + 1;
2405                    q += (xi & 3) << (2*n);
2406                }
2407                y[i].qs[j + m] = q;
2408            }
2409            x += 4*32;
2410        }
2411    }
2412}
2413
2414size_t quantize_tq1_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
2415    (void)quant_weights; // not used
2416    const size_t row_size = ggml_row_size(GGML_TYPE_TQ1_0, n_per_row);
2417    quantize_row_tq1_0_ref(src, dst, (int64_t)nrow*n_per_row);
2418    return nrow * row_size;
2419}
2420
2421size_t quantize_tq2_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
2422    (void)quant_weights; // not used
2423    const size_t row_size = ggml_row_size(GGML_TYPE_TQ2_0, n_per_row);
2424    quantize_row_tq2_0_ref(src, dst, (int64_t)nrow*n_per_row);
2425    return nrow * row_size;
2426}
2427
2428void dequantize_row_tq1_0(const block_tq1_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
2429    assert(k % QK_K == 0);
2430    const int64_t nb = k / QK_K;
2431
2432    const uint8_t pow3[6] = {1, 3, 9, 27, 81, 243};
2433
2434    for (int64_t i = 0; i < nb; ++i) {
2435
2436        const float d = GGML_FP16_TO_FP32(x[i].d);
2437
2438        for (size_t j = 0; j < sizeof(x->qs) - sizeof(x->qs) % 32; j += 32) {
2439            for (size_t n = 0; n < 5; ++n) {
2440                for (size_t m = 0; m < 32; ++m) {
2441                    uint8_t q = x[i].qs[j + m] * pow3[n];
2442                    int16_t xi = ((uint16_t) q * 3) >> 8;
2443                    *y++ = (float) (xi - 1) * d;
2444                }
2445            }
2446        }
2447        for (size_t j = sizeof(x->qs) - sizeof(x->qs) % 32; j < sizeof(x->qs); j += 16) {
2448            for (size_t n = 0; n < 5; ++n) {
2449                for (size_t m = 0; m < 16; ++m) {
2450                    uint8_t q = x[i].qs[j + m] * pow3[n];
2451                    int16_t xi = ((uint16_t) q * 3) >> 8;
2452                    *y++ = (float) (xi - 1) * d;
2453                }
2454            }
2455        }
2456
2457        for (size_t n = 0; n < 4; ++n) {
2458            for (size_t j = 0; j < sizeof(x->qh); ++j) {
2459                uint8_t q = x[i].qh[j] * pow3[n];
2460                int16_t xi = ((uint16_t) q * 3) >> 8;
2461                *y++ = (float) (xi - 1) * d;
2462            }
2463        }
2464    }
2465}
2466
2467void dequantize_row_tq2_0(const block_tq2_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
2468    assert(k % QK_K == 0);
2469    const int64_t nb = k / QK_K;
2470
2471    for (int64_t i = 0; i < nb; ++i) {
2472
2473        const float d = GGML_FP16_TO_FP32(x[i].d);
2474
2475        for (size_t j = 0; j < sizeof(x->qs); j += 32) {
2476            for (size_t l = 0; l < 4; ++l) {
2477                for (size_t m = 0; m < 32; ++m) {
2478                    int8_t q = (x[i].qs[j + m] >> (l*2)) & 3;
2479                    *y++ = (float) (q - 1) * d;
2480                }
2481            }
2482        }
2483    }
2484}
2485
2486// ====================== "True" 2-bit (de)-quantization
2487
2488void dequantize_row_iq2_xxs(const block_iq2_xxs * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
2489    assert(k % QK_K == 0);
2490    const int64_t nb = k / QK_K;
2491
2492    uint32_t aux32[2];
2493    const uint8_t * aux8 = (const uint8_t *)aux32;
2494
2495    for (int i = 0; i < nb; i++) {
2496
2497        const float d = GGML_FP16_TO_FP32(x[i].d);
2498
2499        for (int ib32 = 0; ib32 < QK_K/32; ++ib32) {
2500            memcpy(aux32, x[i].qs + 4*ib32, 2*sizeof(uint32_t));
2501            const float db = d * (0.5f + (aux32[1] >> 28)) * 0.25f;
2502            for (int l = 0; l < 4; ++l) {
2503                const uint8_t * grid = (const uint8_t *)(iq2xxs_grid + aux8[l]);
2504                const uint8_t  signs = ksigns_iq2xs[(aux32[1] >> 7*l) & 127];
2505                for (int j = 0; j < 8; ++j) {
2506                    y[j] = db * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f);
2507                }
2508                y += 8;
2509            }
2510        }
2511    }
2512}
2513
2514// ====================== 2.3125 bpw (de)-quantization
2515
2516void dequantize_row_iq2_xs(const block_iq2_xs * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
2517    assert(k % QK_K == 0);
2518    const int64_t nb = k / QK_K;
2519
2520    float db[2];
2521
2522    for (int i = 0; i < nb; i++) {
2523
2524        const float d = GGML_FP16_TO_FP32(x[i].d);
2525
2526        for (int ib32 = 0; ib32 < QK_K/32; ++ib32) {
2527            db[0] = d * (0.5f + (x[i].scales[ib32] & 0xf)) * 0.25f;
2528            db[1] = d * (0.5f + (x[i].scales[ib32] >>  4)) * 0.25f;
2529            for (int l = 0; l < 4; ++l) {
2530                const uint8_t * grid = (const uint8_t *)(iq2xs_grid + (x[i].qs[4*ib32 + l] & 511));
2531                const uint8_t  signs = ksigns_iq2xs[x[i].qs[4*ib32 + l] >> 9];
2532                for (int j = 0; j < 8; ++j) {
2533                    y[j] = db[l/2] * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f);
2534                }
2535                y += 8;
2536            }
2537        }
2538    }
2539}
2540
2541// ====================== 2.5625 bpw (de)-quantization
2542
2543void dequantize_row_iq2_s(const block_iq2_s * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
2544    assert(k % QK_K == 0);
2545    const int64_t nb = k / QK_K;
2546
2547    float db[2];
2548
2549    for (int i = 0; i < nb; i++) {
2550
2551        const float d = GGML_FP16_TO_FP32(x[i].d);
2552        const uint8_t * qs = x[i].qs;
2553        const uint8_t * qh = x[i].qh;
2554        const uint8_t * signs = qs + QK_K/8;
2555
2556        for (int ib32 = 0; ib32 < QK_K/32; ++ib32) {
2557            db[0] = d * (0.5f + (x[i].scales[ib32] & 0xf)) * 0.25f;
2558            db[1] = d * (0.5f + (x[i].scales[ib32] >>  4)) * 0.25f;
2559            for (int l = 0; l < 4; ++l) {
2560                const float dl = db[l/2];
2561                const uint8_t * grid = (const uint8_t *)(iq2s_grid + (qs[l] | (qh[ib32] << (8-2*l) & 0x300)));
2562                for (int j = 0; j < 8; ++j) {
2563                    y[j] = dl * grid[j] * (signs[l] & kmask_iq2xs[j] ? -1.f : 1.f);
2564                }
2565                y += 8;
2566            }
2567            qs += 4;
2568            signs += 4;
2569        }
2570    }
2571}
2572
2573// ====================== 3.0625 bpw (de)-quantization
2574
2575void dequantize_row_iq3_xxs(const block_iq3_xxs * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
2576    assert(k % QK_K == 0);
2577    const int64_t nb = k / QK_K;
2578
2579    uint32_t aux32;
2580
2581    for (int i = 0; i < nb; i++) {
2582
2583        const float d = GGML_FP16_TO_FP32(x[i].d);
2584        const uint8_t * qs = x[i].qs;
2585        const uint8_t * scales_and_signs = qs + QK_K/4;
2586
2587        for (int ib32 = 0; ib32 < QK_K/32; ++ib32) {
2588            memcpy(&aux32, scales_and_signs + 4*ib32, sizeof(uint32_t));
2589            const float db = d * (0.5f + (aux32 >> 28)) * 0.5f;
2590            for (int l = 0; l < 4; ++l) {
2591                const uint8_t  signs = ksigns_iq2xs[(aux32 >> 7*l) & 127];
2592                const uint8_t * grid1 = (const uint8_t *)(iq3xxs_grid + qs[2*l+0]);
2593                const uint8_t * grid2 = (const uint8_t *)(iq3xxs_grid + qs[2*l+1]);
2594                for (int j = 0; j < 4; ++j) {
2595                    y[j+0] = db * grid1[j] * (signs & kmask_iq2xs[j+0] ? -1.f : 1.f);
2596                    y[j+4] = db * grid2[j] * (signs & kmask_iq2xs[j+4] ? -1.f : 1.f);
2597                }
2598                y += 8;
2599            }
2600            qs += 8;
2601        }
2602    }
2603}
2604
2605// ====================== 3.3125 bpw (de)-quantization
2606
2607void dequantize_row_iq3_s(const block_iq3_s * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
2608    assert(k % QK_K == 0);
2609    const int64_t nb = k / QK_K;
2610
2611    for (int i = 0; i < nb; i++) {
2612
2613        const float d = GGML_FP16_TO_FP32(x[i].d);
2614        const uint8_t * qs = x[i].qs;
2615        const uint8_t * qh = x[i].qh;
2616        const uint8_t * signs = x[i].signs;
2617
2618        for (int ib32 = 0; ib32 < QK_K/32; ib32 += 2) {
2619            const float db1 = d * (1 + 2*(x[i].scales[ib32/2] & 0xf));
2620            const float db2 = d * (1 + 2*(x[i].scales[ib32/2] >>  4));
2621            for (int l = 0; l < 4; ++l) {
2622                const uint8_t * grid1 = (const uint8_t *)(iq3s_grid + (qs[2*l+0] | ((qh[0] << (8-2*l)) & 256)));
2623                const uint8_t * grid2 = (const uint8_t *)(iq3s_grid + (qs[2*l+1] | ((qh[0] << (7-2*l)) & 256)));
2624                for (int j = 0; j < 4; ++j) {
2625                    y[j+0] = db1 * grid1[j] * (signs[l] & kmask_iq2xs[j+0] ? -1.f : 1.f);
2626                    y[j+4] = db1 * grid2[j] * (signs[l] & kmask_iq2xs[j+4] ? -1.f : 1.f);
2627                }
2628                y += 8;
2629            }
2630            qs += 8;
2631            signs += 4;
2632            for (int l = 0; l < 4; ++l) {
2633                const uint8_t * grid1 = (const uint8_t *)(iq3s_grid + (qs[2*l+0] | ((qh[1] << (8-2*l)) & 256)));
2634                const uint8_t * grid2 = (const uint8_t *)(iq3s_grid + (qs[2*l+1] | ((qh[1] << (7-2*l)) & 256)));
2635                for (int j = 0; j < 4; ++j) {
2636                    y[j+0] = db2 * grid1[j] * (signs[l] & kmask_iq2xs[j+0] ? -1.f : 1.f);
2637                    y[j+4] = db2 * grid2[j] * (signs[l] & kmask_iq2xs[j+4] ? -1.f : 1.f);
2638                }
2639                y += 8;
2640            }
2641            qh += 2;
2642            qs += 8;
2643            signs += 4;
2644        }
2645    }
2646}
2647
2648// ====================== 1.5625 bpw (de)-quantization
2649
2650void dequantize_row_iq1_s(const block_iq1_s * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
2651    assert(k % QK_K == 0);
2652    const int64_t nb = k / QK_K;
2653
2654    for (int i = 0; i < nb; i++) {
2655
2656        const float d = GGML_FP16_TO_FP32(x[i].d);
2657        const uint8_t  * qs = x[i].qs;
2658        const uint16_t * qh = x[i].qh;
2659
2660        for (int ib = 0; ib < QK_K/32; ++ib) {
2661            const float dl = d * (2*((qh[ib] >> 12) & 7) + 1);
2662            const float delta = qh[ib] & 0x8000 ? -IQ1S_DELTA : IQ1S_DELTA;
2663            for (int l = 0; l < 4; ++l) {
2664                const int8_t * grid = (const int8_t *)(iq1s_grid + (qs[l] | (((qh[ib] >> 3*l) & 7) << 8)));
2665                for (int j = 0; j < 8; ++j) {
2666                    y[j] = dl * (grid[j] + delta);
2667                }
2668                y += 8;
2669            }
2670            qs += 4;
2671        }
2672    }
2673}
2674
2675void dequantize_row_iq1_m(const block_iq1_m * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
2676    assert(k % QK_K == 0);
2677    const int64_t nb = k / QK_K;
2678
2679    float delta[4];
2680    uint16_t idx[4];
2681
2682    iq1m_scale_t scale;
2683
2684    for (int i = 0; i < nb; i++) {
2685
2686        const uint16_t * sc = (const uint16_t *)x[i].scales;
2687        scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000);
2688        const float d = GGML_FP16_TO_FP32(scale.f16);
2689
2690        const uint8_t * qs = x[i].qs;
2691        const uint8_t * qh = x[i].qh;
2692
2693        for (int ib = 0; ib < QK_K/32; ++ib) {
2694            const float dl1 = d * (2*((sc[ib/2] >> (6*(ib%2)+0)) & 0x7) + 1);
2695            const float dl2 = d * (2*((sc[ib/2] >> (6*(ib%2)+3)) & 0x7) + 1);
2696
2697            idx[0] = qs[0] | ((qh[0] << 8) & 0x700);
2698            idx[1] = qs[1] | ((qh[0] << 4) & 0x700);
2699            idx[2] = qs[2] | ((qh[1] << 8) & 0x700);
2700            idx[3] = qs[3] | ((qh[1] << 4) & 0x700);
2701            delta[0] = qh[0] & 0x08 ? -IQ1S_DELTA : IQ1S_DELTA;
2702            delta[1] = qh[0] & 0x80 ? -IQ1S_DELTA : IQ1S_DELTA;
2703            delta[2] = qh[1] & 0x08 ? -IQ1S_DELTA : IQ1S_DELTA;
2704            delta[3] = qh[1] & 0x80 ? -IQ1S_DELTA : IQ1S_DELTA;
2705            for (int l = 0; l < 2; ++l) {
2706                const int8_t * grid = (const int8_t *)(iq1s_grid + idx[l]);
2707                for (int j = 0; j < 8; ++j) {
2708                    y[j] = dl1 * (grid[j] + delta[l]);
2709                }
2710                y += 8;
2711            }
2712            for (int l = 2; l < 4; ++l) {
2713                const int8_t * grid = (const int8_t *)(iq1s_grid + idx[l]);
2714                for (int j = 0; j < 8; ++j) {
2715                    y[j] = dl2 * (grid[j] + delta[l]);
2716                }
2717                y += 8;
2718            }
2719            qs += 4;
2720            qh += 2;
2721        }
2722    }
2723}
2724
2725void dequantize_row_iq4_nl(const block_iq4_nl * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
2726    assert(k % QK4_NL == 0);
2727    const int64_t nb = k / QK4_NL;
2728
2729    for (int i = 0; i < nb; i++) {
2730
2731        const uint8_t * qs = x[i].qs;
2732
2733        const float d = GGML_FP16_TO_FP32(x[i].d);
2734        for (int j = 0; j < QK4_NL/2; ++j) {
2735            y[j+       0] = d * kvalues_iq4nl[qs[j] & 0xf];
2736            y[j+QK4_NL/2] = d * kvalues_iq4nl[qs[j] >>  4];
2737        }
2738        y  += QK4_NL;
2739        qs += QK4_NL/2;
2740    }
2741}
2742
2743void dequantize_row_iq4_xs(const block_iq4_xs * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
2744    assert(k % QK_K == 0);
2745    const int64_t nb = k / QK_K;
2746
2747    for (int i = 0; i < nb; i++) {
2748
2749        const uint8_t * qs = x[i].qs;
2750
2751        const float d = GGML_FP16_TO_FP32(x[i].d);
2752
2753        for (int ib = 0; ib < QK_K/32; ++ib) {
2754            const int ls = ((x[i].scales_l[ib/2] >> 4*(ib%2)) & 0xf) | (((x[i].scales_h >> 2*ib) & 3) << 4);
2755            const float dl = d * (ls - 32);
2756            for (int j = 0; j < 16; ++j) {
2757                y[j+ 0] = dl * kvalues_iq4nl[qs[j] & 0xf];
2758                y[j+16] = dl * kvalues_iq4nl[qs[j] >>  4];
2759            }
2760            y  += 32;
2761            qs += 16;
2762        }
2763    }
2764}
2765
2766//===================================== Q8_K ==============================================
2767
2768void quantize_row_q8_K_ref(const float * GGML_RESTRICT x, block_q8_K * GGML_RESTRICT y, int64_t k) {
2769    assert(k % QK_K == 0);
2770    const int64_t nb = k / QK_K;
2771
2772    for (int i = 0; i < nb; i++) {
2773
2774        float max = 0;
2775        float amax = 0;
2776        for (int j = 0; j < QK_K; ++j) {
2777            float ax = fabsf(x[j]);
2778            if (ax > amax) {
2779                amax = ax; max = x[j];
2780            }
2781        }
2782        if (!amax) {
2783            y[i].d = 0;
2784            memset(y[i].qs, 0, QK_K);
2785            x += QK_K;
2786            continue;
2787        }
2788        //const float iscale = -128.f/max;
2789        // We need this change for IQ2_XXS, else the AVX implementation becomes very awkward
2790        const float iscale = -127.f/max;
2791        for (int j = 0; j < QK_K; ++j) {
2792            int v = nearest_int(iscale*x[j]);
2793            y[i].qs[j] = MIN(127, v);
2794        }
2795        for (int j = 0; j < QK_K/16; ++j) {
2796            int sum = 0;
2797            for (int ii = 0; ii < 16; ++ii) {
2798                sum += y[i].qs[j*16 + ii];
2799            }
2800            y[i].bsums[j] = sum;
2801        }
2802        y[i].d = 1/iscale;
2803        x += QK_K;
2804    }
2805}
2806
2807void dequantize_row_q8_K(const block_q8_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) {
2808    assert(k % QK_K == 0);
2809    const int64_t nb = k / QK_K;
2810
2811    for (int i = 0; i < nb; i++) {
2812        for (int j = 0; j < QK_K; ++j) {
2813            *y++ = x[i].d * x[i].qs[j];
2814        }
2815    }
2816}
2817
2818// ================================ IQ2 quantization =============================================
2819
2820typedef struct {
2821    uint64_t * grid;
2822    int      * map;
2823    uint16_t * neighbours;
2824} iq2_entry_t;
2825
2826static iq2_entry_t iq2_data[4] = {
2827    {NULL, NULL, NULL},
2828    {NULL, NULL, NULL},
2829    {NULL, NULL, NULL},
2830    {NULL, NULL, NULL},
2831};
2832
2833static inline int iq2_data_index(enum ggml_type type) {
2834    GGML_ASSERT(type == GGML_TYPE_IQ2_XXS || type == GGML_TYPE_IQ2_XS || type == GGML_TYPE_IQ1_S || type == GGML_TYPE_IQ1_M || type == GGML_TYPE_IQ2_S);
2835    return type == GGML_TYPE_IQ2_XXS ? 0 :
2836           type == GGML_TYPE_IQ2_XS  ? 1 :
2837           type == GGML_TYPE_IQ1_S || type == GGML_TYPE_IQ1_M ? 2 : 3;
2838}
2839
2840static inline int iq2_grid_size(enum ggml_type type) {
2841    GGML_ASSERT(type == GGML_TYPE_IQ2_XXS || type == GGML_TYPE_IQ2_XS || type == GGML_TYPE_IQ1_S || type == GGML_TYPE_IQ1_M || type == GGML_TYPE_IQ2_S);
2842    return type == GGML_TYPE_IQ2_XXS ? 256 :
2843           type == GGML_TYPE_IQ2_XS  ? 512 :
2844           type == GGML_TYPE_IQ1_S || type == GGML_TYPE_IQ1_M ? NGRID_IQ1S : 1024;
2845}
2846
2847static int iq2_compare_func(const void * left, const void * right) {
2848    const int * l = (const int *)left;
2849    const int * r = (const int *)right;
2850    return l[0] < r[0] ? -1 : l[0] > r[0] ? 1 : l[1] < r[1] ? -1 : l[1] > r[1] ? 1 : 0;
2851}
2852
2853void iq2xs_init_impl(enum ggml_type type) {
2854    const int gindex = iq2_data_index(type);
2855    const int grid_size = iq2_grid_size(type);
2856    if (iq2_data[gindex].grid) {
2857        return;
2858    }
2859    static const uint16_t kgrid_2bit_256[256] = {
2860            0,     2,     5,     8,    10,    17,    20,    32,    34,    40,    42,    65,    68,    80,    88,    97,
2861          100,   128,   130,   138,   162,   257,   260,   272,   277,   320,   388,   408,   512,   514,   546,   642,
2862         1025,  1028,  1040,  1057,  1060,  1088,  1090,  1096,  1120,  1153,  1156,  1168,  1188,  1280,  1282,  1288,
2863         1312,  1350,  1385,  1408,  1425,  1545,  1552,  1600,  1668,  1700,  2048,  2053,  2056,  2068,  2088,  2113,
2864         2116,  2128,  2130,  2184,  2308,  2368,  2562,  2580,  4097,  4100,  4112,  4129,  4160,  4192,  4228,  4240,
2865         4245,  4352,  4360,  4384,  4432,  4442,  4480,  4644,  4677,  5120,  5128,  5152,  5157,  5193,  5248,  5400,
2866         5474,  5632,  5654,  6145,  6148,  6160,  6208,  6273,  6400,  6405,  6560,  6737,  8192,  8194,  8202,  8260,
2867         8289,  8320,  8322,  8489,  8520,  8704,  8706,  9217,  9220,  9232,  9280,  9302,  9472,  9537,  9572,  9872,
2868        10248, 10272, 10388, 10820, 16385, 16388, 16400, 16408, 16417, 16420, 16448, 16456, 16470, 16480, 16513, 16516,
2869        16528, 16640, 16672, 16737, 16768, 16773, 16897, 16912, 16968, 16982, 17000, 17408, 17416, 17440, 17536, 17561,
2870        17682, 17700, 17920, 18433, 18436, 18448, 18496, 18501, 18688, 18776, 18785, 18818, 19013, 19088, 20480, 20488,
2871        20497, 20505, 20512, 20608, 20616, 20740, 20802, 20900, 21137, 21648, 21650, 21770, 22017, 22100, 22528, 22545,
2872        22553, 22628, 22848, 23048, 24580, 24592, 24640, 24680, 24832, 24917, 25112, 25184, 25600, 25605, 25872, 25874,
2873        25988, 26690, 32768, 32770, 32778, 32833, 32898, 33028, 33048, 33088, 33297, 33793, 33796, 33808, 33813, 33856,
2874        33888, 34048, 34118, 34196, 34313, 34368, 34400, 34818, 35076, 35345, 36868, 36880, 36900, 36928, 37025, 37142,
2875        37248, 37445, 37888, 37922, 37956, 38225, 39041, 39200, 40962, 41040, 41093, 41225, 41472, 42008, 43088, 43268,
2876    };
2877    static const uint16_t kgrid_2bit_512[512] = {
2878            0,     2,     5,     8,    10,    17,    20,    22,    25,    32,    34,    37,    40,    65,    68,    70,
2879           73,    80,    82,    85,    88,    97,   100,   128,   130,   133,   136,   145,   148,   153,   160,   257,
2880          260,   262,   265,   272,   274,   277,   280,   282,   289,   292,   320,   322,   325,   328,   337,   340,
2881          352,   360,   385,   388,   400,   512,   514,   517,   520,   529,   532,   544,   577,   580,   592,   597,
2882          640,   650,  1025,  1028,  1030,  1033,  1040,  1042,  1045,  1048,  1057,  1060,  1088,  1090,  1093,  1096,
2883         1105,  1108,  1110,  1120,  1153,  1156,  1168,  1280,  1282,  1285,  1288,  1297,  1300,  1312,  1345,  1348,
2884         1360,  1377,  1408,  1537,  1540,  1552,  1574,  1600,  1602,  1668,  2048,  2050,  2053,  2056,  2058,  2065,
2885         2068,  2080,  2085,  2113,  2116,  2128,  2136,  2176,  2208,  2218,  2305,  2308,  2320,  2368,  2433,  2441,
2886         2560,  2592,  2600,  2710,  2720,  4097,  4100,  4102,  4105,  4112,  4114,  4117,  4120,  4129,  4132,  4160,
2887         4162,  4165,  4168,  4177,  4180,  4192,  4202,  4225,  4228,  4240,  4352,  4354,  4357,  4360,  4369,  4372,
2888         4384,  4417,  4420,  4432,  4480,  4500,  4502,  4609,  4612,  4614,  4624,  4672,  4704,  5120,  5122,  5125,
2889         5128,  5137,  5140,  5152,  5185,  5188,  5193,  5200,  5220,  5248,  5377,  5380,  5392,  5440,  5632,  5652,
2890         5705,  6145,  6148,  6160,  6162,  6208,  6228,  6278,  6400,  6405,  6502,  6737,  6825,  8192,  8194,  8197,
2891         8200,  8202,  8209,  8212,  8224,  8257,  8260,  8272,  8320,  8352,  8449,  8452,  8464,  8512,  8520,  8549,
2892         8704,  8738,  8832,  8872,  9217,  9220,  9232,  9257,  9280,  9472,  9537,  9554,  9625,  9729,  9754,  9894,
2893        10240, 10248, 10250, 10272, 10325, 10376, 10402, 10600, 10640, 10760, 10784, 10882, 10888, 10890, 16385, 16388,
2894        16390, 16393, 16400, 16402, 16405, 16408, 16417, 16420, 16448, 16450, 16453, 16456, 16458, 16465, 16468, 16480,
2895        16485, 16513, 16516, 16528, 16640, 16642, 16645, 16648, 16657, 16660, 16672, 16705, 16708, 16720, 16768, 16773,
2896        16802, 16897, 16900, 16912, 16914, 16937, 16960, 17408, 17410, 17413, 17416, 17425, 17428, 17433, 17440, 17473,
2897        17476, 17488, 17536, 17556, 17665, 17668, 17680, 17700, 17728, 17818, 17920, 17930, 17988, 18000, 18433, 18436,
2898        18448, 18496, 18501, 18516, 18530, 18688, 18705, 18756, 18768, 18793, 18948, 20480, 20482, 20485, 20488, 20497,
2899        20500, 20512, 20520, 20545, 20548, 20560, 20608, 20737, 20740, 20752, 20757, 20800, 20802, 20992, 21060, 21162,
2900        21505, 21508, 21520, 21537, 21568, 21600, 21633, 21665, 21760, 21768, 21888, 21896, 22049, 22120, 22177, 22528,
2901        22548, 22593, 22608, 22681, 22810, 22848, 22850, 23173, 24577, 24580, 24592, 24640, 24660, 24674, 24710, 24745,
2902        24832, 25124, 25162, 25234, 25600, 25622, 25872, 25920, 25925, 26020, 26625, 26730, 26917, 27142, 27220, 27234,
2903        32768, 32770, 32773, 32776, 32785, 32788, 32800, 32810, 32833, 32836, 32848, 32896, 32898, 32936, 32938, 33025,
2904        33028, 33030, 33040, 33088, 33105, 33113, 33280, 33312, 33408, 33410, 33440, 33448, 33793, 33796, 33808, 33810,
2905        33813, 33856, 33888, 33929, 34048, 34116, 34213, 34328, 34410, 34816, 34824, 34853, 34906, 34944, 34946, 34984,
2906        35078, 35362, 35456, 35464, 35478, 35496, 36865, 36868, 36880, 36928, 36950, 36996, 37120, 37154, 37220, 37462,
2907        37513, 37888, 37893, 37956, 37968, 37976, 38185, 38288, 38290, 38465, 38993, 39078, 39241, 39445, 39520, 40960,
2908        40962, 40968, 40970, 40992, 41002, 41120, 41297, 41305, 41382, 41472, 41474, 41480, 41514, 41600, 41632, 42048,
2909        42133, 42597, 42648, 43018, 43040, 43042, 43048, 43168, 43176, 43268, 43396, 43398, 43560, 43562, 43665, 43690,
2910    };
2911    static const uint16_t kgrid_1bit_2048[NGRID_IQ1S] = {
2912            0,     2,     5,     8,    10,    17,    21,    32,    34,    40,    42,    69,    81,    84,    86,   101,
2913          128,   130,   136,   138,   149,   160,   162,   168,   170,   260,   261,   273,   276,   278,   281,   282,
2914          293,   321,   326,   329,   338,   341,   346,   353,   356,   358,   360,   389,   401,   404,   406,   421,
2915          512,   514,   520,   522,   533,   544,   546,   552,   554,   581,   593,   601,   612,   617,   640,   642,
2916          648,   650,   657,   661,   665,   672,   674,   680,   682,  1041,  1044,  1046,  1061,  1089,  1097,  1109,
2917         1114,  1124,  1125,  1169,  1177,  1189,  1281,  1284,  1285,  1286,  1301,  1304,  1306,  1321,  1344,  1349,
2918         1354,  1360,  1361,  1364,  1365,  1366,  1369,  1376,  1378,  1381,  1384,  1386,  1409,  1425,  1429,  1432,
2919         1434,  1441,  1444,  1445,  1446,  1449,  1556,  1561,  1601,  1604,  1616,  1618,  1621,  1624,  1632,  1633,
2920         1638,  1641,  1669,  1681,  1684,  1689,  2048,  2050,  2056,  2058,  2069,  2080,  2082,  2088,  2090,  2117,
2921         2129,  2134,  2149,  2176,  2178,  2184,  2186,  2197,  2208,  2210,  2216,  2218,  2309,  2321,  2324,  2329,
2922         2340,  2341,  2369,  2384,  2385,  2389,  2401,  2404,  2409,  2449,  2452,  2454,  2457,  2469,  2560,  2562,
2923         2568,  2570,  2581,  2592,  2594,  2600,  2602,  2629,  2641,  2649,  2657,  2661,  2688,  2690,  2693,  2696,
2924         2698,  2709,  2720,  2722,  2728,  2730,  4112,  4113,  4116,  4121,  4132,  4133,  4161,  4164,  4176,  4181,
2925         4184,  4193,  4196,  4197,  4201,  4241,  4244,  4246,  4257,  4261,  4353,  4356,  4358,  4361,  4368,  4370,
2926         4373,  4376,  4385,  4388,  4393,  4421,  4426,  4432,  4433,  4434,  4436,  4437,  4438,  4441,  4448,  4453,
2927         4484,  4498,  4501,  4513,  4516,  4625,  4628,  4630,  4645,  4672,  4678,  4681,  4690,  4693,  4696,  4698,
2928         4708,  4710,  4741,  4753,  4756,  4758,  4773,  5121,  5126,  5129,  5140,  5141,  5144,  5145,  5153,  5158,
2929         5185,  5189,  5190,  5192,  5194,  5201,  5204,  5205,  5206,  5209,  5218,  5221,  5224,  5252,  5257,  5264,
2930         5268,  5269,  5272,  5273,  5274,  5281,  5284,  5285,  5289,  5378,  5381,  5386,  5393,  5396,  5397,  5398,
2931         5401,  5408,  5410,  5413,  5416,  5418,  5441,  5444,  5445,  5446,  5457,  5458,  5460,  5461,  5462,  5465,
2932         5466,  5473,  5476,  5477,  5478,  5481,  5504,  5506,  5508,  5509,  5512,  5514,  5520,  5521,  5524,  5525,
2933         5526,  5529,  5530,  5536,  5538,  5541,  5633,  5636,  5637,  5638,  5653,  5654,  5656,  5658,  5665,  5670,
2934         5696,  5698,  5700,  5701,  5704,  5706,  5713,  5717,  5718,  5720,  5721,  5729,  5732,  5733,  5736,  5737,
2935         5738,  5766,  5770,  5778,  5781,  5796,  5801,  6161,  6166,  6181,  6209,  6212,  6214,  6217,  6224,  6229,
2936         6232,  6234,  6240,  6241,  6244,  6246,  6249,  6277,  6289,  6292,  6309,  6416,  6418,  6421,  6426,  6433,
2937         6437,  6466,  6468,  6469,  6472,  6481,  6484,  6485,  6486,  6489,  6490,  6496,  6501,  6506,  6537,  6545,
2938         6546,  6549,  6552,  6561,  6566,  6569,  6665,  6678,  6692,  6694,  6724,  6726,  6729,  6736,  6738,  6741,
2939         6744,  6753,  6758,  6761,  6789,  6801,  6806,  6810,  8192,  8194,  8200,  8202,  8213,  8224,  8226,  8229,
2940         8232,  8234,  8261,  8273,  8281,  8289,  8293,  8320,  8322,  8328,  8330,  8341,  8352,  8354,  8357,  8360,
2941         8362,  8453,  8465,  8468,  8473,  8485,  8514,  8516,  8521,  8533,  8536,  8538,  8545,  8548,  8549,  8550,
2942         8581,  8592,  8598,  8601,  8613,  8705,  8712,  8714,  8721,  8725,  8736,  8738,  8744,  8746,  8773,  8785,
2943         8790,  8793,  8805,  8833,  8840,  8842,  8849,  8853,  8864,  8866,  8872,  8874,  9221,  9236,  9238,  9241,
2944         9253,  9284,  9285,  9286,  9289,  9298,  9301,  9304,  9306,  9318,  9349,  9361,  9364,  9369,  9377,  9381,
2945         9481,  9493,  9505,  9513,  9536,  9541,  9544,  9553,  9556,  9557,  9561,  9570,  9573,  9576,  9609,  9616,
2946         9620,  9621,  9624,  9626,  9633,  9636,  9638,  9641,  9733,  9744,  9746,  9753,  9765,  9793,  9801,  9813,
2947         9824,  9825,  9833,  9860,  9862,  9872,  9882, 10240, 10242, 10248, 10250, 10261, 10272, 10274, 10280, 10282,
2948        10309, 10321, 10324, 10341, 10368, 10370, 10376, 10378, 10400, 10402, 10408, 10410, 10505, 10513, 10516, 10521,
2949        10533, 10566, 10569, 10578, 10581, 10593, 10596, 10598, 10601, 10629, 10640, 10646, 10649, 10660, 10661, 10752,
2950        10754, 10760, 10762, 10784, 10786, 10792, 10794, 10821, 10833, 10838, 10841, 10853, 10880, 10882, 10888, 10890,
2951        10901, 10912, 10914, 10920, 10922, 16389, 16401, 16406, 16421, 16457, 16466, 16469, 16472, 16474, 16481, 16484,
2952        16486, 16532, 16537, 16545, 16550, 16640, 16641, 16644, 16646, 16649, 16658, 16661, 16662, 16664, 16666, 16673,
2953        16678, 16681, 16709, 16712, 16714, 16721, 16724, 16725, 16726, 16729, 16730, 16741, 16744, 16746, 16769, 16772,
2954        16774, 16784, 16786, 16789, 16800, 16801, 16802, 16901, 16913, 16916, 16918, 16933, 16961, 16978, 16981, 16986,
2955        16996, 17001, 17033, 17044, 17061, 17409, 17429, 17433, 17449, 17477, 17480, 17482, 17489, 17492, 17493, 17494,
2956        17505, 17506, 17509, 17512, 17514, 17537, 17542, 17545, 17552, 17554, 17557, 17568, 17569, 17577, 17665, 17666,
2957        17669, 17674, 17681, 17684, 17685, 17686, 17689, 17696, 17701, 17706, 17729, 17732, 17733, 17734, 17737, 17744,
2958        17745, 17748, 17749, 17750, 17752, 17753, 17761, 17764, 17765, 17766, 17769, 17794, 17796, 17797, 17800, 17809,
2959        17812, 17813, 17814, 17817, 17818, 17829, 17832, 17834, 17921, 17925, 17929, 17940, 17941, 17944, 17946, 17953,
2960        17956, 17961, 17984, 17986, 17989, 17992, 18000, 18001, 18002, 18005, 18006, 18009, 18018, 18021, 18024, 18049,
2961        18053, 18058, 18068, 18069, 18081, 18084, 18086, 18437, 18449, 18453, 18458, 18469, 18498, 18505, 18512, 18517,
2962        18520, 18529, 18532, 18534, 18537, 18565, 18577, 18580, 18582, 18585, 18597, 18689, 18693, 18694, 18698, 18704,
2963        18708, 18709, 18712, 18721, 18724, 18726, 18752, 18757, 18762, 18769, 18770, 18772, 18773, 18774, 18777, 18784,
2964        18786, 18789, 18790, 18794, 18822, 18825, 18834, 18837, 18838, 18840, 18849, 18852, 18854, 18857, 18966, 19012,
2965        19014, 19017, 19029, 19032, 19034, 19044, 19049, 19092, 19109, 20481, 20484, 20485, 20486, 20489, 20498, 20501,
2966        20506, 20513, 20516, 20521, 20544, 20549, 20552, 20561, 20564, 20565, 20566, 20569, 20581, 20584, 20614, 20617,
2967        20629, 20632, 20640, 20641, 20646, 20649, 20741, 20744, 20745, 20746, 20753, 20756, 20757, 20758, 20760, 20761,
2968        20768, 20773, 20774, 20776, 20778, 20801, 20804, 20805, 20806, 20809, 20816, 20817, 20818, 20820, 20821, 20822,
2969        20824, 20825, 20826, 20833, 20836, 20837, 20838, 20841, 20866, 20869, 20881, 20884, 20885, 20886, 20889, 20896,
2970        20901, 20906, 20993, 20998, 21010, 21013, 21018, 21025, 21028, 21058, 21061, 21066, 21073, 21076, 21077, 21078,
2971        21081, 21090, 21093, 21125, 21136, 21138, 21141, 21145, 21146, 21156, 21508, 21509, 21521, 21524, 21525, 21526,
2972        21528, 21529, 21537, 21541, 21544, 21546, 21569, 21572, 21573, 21574, 21577, 21578, 21584, 21585, 21588, 21589,
2973        21590, 21592, 21593, 21594, 21601, 21602, 21604, 21605, 21606, 21609, 21632, 21640, 21642, 21649, 21652, 21653,
2974        21654, 21657, 21665, 21668, 21669, 21674, 21761, 21762, 21764, 21765, 21766, 21769, 21776, 21777, 21778, 21780,
2975        21781, 21782, 21785, 21786, 21793, 21796, 21797, 21798, 21801, 21824, 21825, 21826, 21828, 21829, 21830, 21832,
2976        21833, 21840, 21841, 21842, 21844, 21845, 21846, 21848, 21849, 21850, 21856, 21857, 21860, 21861, 21862, 21864,
2977        21865, 21866, 21889, 21892, 21893, 21897, 21898, 21904, 21905, 21908, 21909, 21910, 21912, 21913, 21921, 21924,
2978        21925, 21926, 21929, 22016, 22017, 22018, 22020, 22022, 22024, 22025, 22033, 22036, 22037, 22040, 22041, 22048,
2979        22049, 22050, 22052, 22053, 22054, 22056, 22057, 22081, 22085, 22086, 22088, 22089, 22090, 22096, 22097, 22098,
2980        22100, 22101, 22102, 22104, 22105, 22106, 22113, 22116, 22117, 22121, 22146, 22149, 22150, 22152, 22153, 22154,
2981        22161, 22165, 22170, 22178, 22181, 22182, 22184, 22185, 22532, 22533, 22534, 22537, 22544, 22549, 22552, 22561,
2982        22570, 22597, 22600, 22602, 22609, 22612, 22613, 22614, 22616, 22617, 22624, 22626, 22628, 22629, 22658, 22665,
2983        22672, 22674, 22677, 22680, 22689, 22697, 22785, 22786, 22789, 22794, 22801, 22804, 22805, 22806, 22809, 22821,
2984        22849, 22852, 22853, 22854, 22857, 22864, 22865, 22866, 22868, 22869, 22870, 22872, 22873, 22874, 22881, 22884,
2985        22885, 22886, 22889, 22913, 22917, 22921, 22929, 22932, 22933, 22934, 22936, 22937, 22949, 23044, 23048, 23061,
2986        23066, 23072, 23077, 23078, 23081, 23109, 23112, 23113, 23121, 23125, 23126, 23128, 23129, 23138, 23141, 23144,
2987        23146, 23169, 23178, 23186, 23189, 23190, 23192, 23194, 23201, 24581, 24596, 24598, 24601, 24613, 24644, 24656,
2988        24661, 24662, 24664, 24666, 24673, 24676, 24678, 24681, 24705, 24726, 24741, 24833, 24836, 24838, 24841, 24850,
2989        24853, 24865, 24866, 24870, 24873, 24901, 24905, 24913, 24917, 24918, 24921, 24933, 24934, 24938, 24964, 24970,
2990        24978, 24981, 24993, 24998, 25001, 25105, 25110, 25113, 25152, 25153, 25158, 25173, 25174, 25176, 25184, 25221,
2991        25233, 25238, 25253, 25617, 25618, 25621, 25622, 25626, 25633, 25638, 25641, 25664, 25666, 25669, 25672, 25674,
2992        25681, 25684, 25685, 25686, 25689, 25690, 25696, 25698, 25701, 25732, 25733, 25737, 25744, 25746, 25748, 25749,
2993        25750, 25752, 25754, 25761, 25764, 25769, 25861, 25864, 25866, 25873, 25877, 25878, 25881, 25924, 25925, 25926,
2994        25929, 25936, 25937, 25940, 25941, 25942, 25945, 25953, 25956, 25957, 25958, 25961, 25990, 25993, 25994, 26001,
2995        26005, 26006, 26009, 26010, 26018, 26021, 26022, 26024, 26114, 26121, 26133, 26144, 26150, 26152, 26153, 26176,
2996        26181, 26184, 26186, 26193, 26196, 26197, 26198, 26200, 26202, 26208, 26213, 26216, 26240, 26242, 26245, 26250,
2997        26260, 26262, 26264, 26265, 26272, 26276, 26278, 26282, 26646, 26649, 26661, 26689, 26706, 26709, 26714, 26721,
2998        26729, 26757, 26769, 26776, 26790, 26881, 26884, 26896, 26901, 26913, 26916, 26918, 26921, 26944, 26945, 26949,
2999        26950, 26952, 26961, 26964, 26965, 26966, 26969, 26976, 26981, 26986, 27010, 27012, 27018, 27029, 27041, 27044,
3000        27045, 27049, 27153, 27158, 27160, 27201, 27204, 27209, 27216, 27221, 27224, 27226, 27236, 27237, 27241, 27270,
3001        27284, 27288, 27290, 27302, 32768, 32770, 32776, 32778, 32800, 32802, 32808, 32810, 32837, 32848, 32849, 32852,
3002        32854, 32857, 32869, 32896, 32898, 32904, 32906, 32917, 32928, 32930, 32936, 32938, 33029, 33041, 33044, 33046,
3003        33049, 33061, 33089, 33092, 33097, 33104, 33106, 33109, 33110, 33112, 33113, 33124, 33126, 33129, 33157, 33161,
3004        33172, 33174, 33177, 33189, 33280, 33282, 33288, 33290, 33301, 33312, 33314, 33320, 33322, 33361, 33364, 33369,
3005        33381, 33408, 33410, 33416, 33418, 33429, 33440, 33442, 33448, 33450, 33812, 33817, 33857, 33860, 33873, 33877,
3006        33882, 33889, 33892, 33897, 33940, 33945, 34049, 34057, 34066, 34069, 34074, 34086, 34089, 34112, 34113, 34117,
3007        34120, 34129, 34132, 34133, 34134, 34137, 34138, 34149, 34150, 34152, 34154, 34177, 34180, 34182, 34185, 34192,
3008        34194, 34197, 34200, 34214, 34321, 34326, 34329, 34341, 34369, 34372, 34377, 34378, 34384, 34389, 34393, 34394,
3009        34401, 34406, 34410, 34437, 34449, 34458, 34468, 34816, 34818, 34824, 34826, 34837, 34848, 34850, 34856, 34858,
3010        34881, 34885, 34897, 34900, 34905, 34917, 34921, 34944, 34946, 34952, 34954, 34965, 34976, 34978, 34984, 34986,
3011        35077, 35078, 35089, 35092, 35094, 35109, 35137, 35140, 35142, 35145, 35152, 35154, 35157, 35162, 35169, 35172,
3012        35205, 35222, 35225, 35237, 35328, 35330, 35336, 35338, 35349, 35360, 35362, 35368, 35370, 35397, 35409, 35412,
3013        35414, 35456, 35458, 35464, 35466, 35477, 35488, 35490, 35496, 35498, 36869, 36881, 36886, 36888, 36889, 36901,
3014        36929, 36934, 36937, 36949, 36952, 36954, 36969, 36970, 36997, 37009, 37012, 37014, 37017, 37029, 37121, 37124,
3015        37126, 37129, 37136, 37141, 37144, 37146, 37153, 37156, 37158, 37161, 37184, 37189, 37200, 37201, 37204, 37205,
3016        37206, 37209, 37218, 37221, 37252, 37254, 37266, 37269, 37272, 37281, 37284, 37286, 37289, 37381, 37393, 37396,
3017        37401, 37413, 37444, 37446, 37449, 37456, 37458, 37461, 37464, 37478, 37481, 37509, 37524, 37526, 37545, 37889,
3018        37892, 37894, 37904, 37909, 37912, 37926, 37952, 37962, 37969, 37972, 37973, 37974, 37976, 37977, 37984, 37985,
3019        37986, 37989, 38020, 38022, 38034, 38036, 38037, 38040, 38049, 38057, 38144, 38149, 38152, 38154, 38160, 38161,
3020        38164, 38165, 38166, 38169, 38177, 38181, 38185, 38186, 38209, 38212, 38213, 38214, 38217, 38224, 38225, 38226,
3021        38228, 38229, 38230, 38232, 38233, 38234, 38241, 38244, 38245, 38246, 38249, 38273, 38277, 38280, 38289, 38290,
3022        38292, 38293, 38294, 38297, 38298, 38304, 38306, 38309, 38312, 38314, 38401, 38404, 38416, 38421, 38425, 38432,
3023        38438, 38441, 38469, 38472, 38473, 38481, 38482, 38485, 38486, 38489, 38501, 38504, 38530, 38532, 38537, 38538,
3024        38546, 38548, 38549, 38564, 38566, 38569, 38917, 38934, 38937, 38949, 38977, 38982, 38992, 38994, 38997, 38998,
3025        39002, 39012, 39013, 39045, 39057, 39062, 39065, 39077, 39172, 39174, 39177, 39184, 39186, 39189, 39192, 39194,
3026        39200, 39201, 39204, 39206, 39232, 39234, 39237, 39240, 39242, 39249, 39252, 39253, 39254, 39257, 39266, 39269,
3027        39270, 39274, 39297, 39300, 39312, 39314, 39317, 39322, 39329, 39334, 39429, 39445, 39461, 39492, 39494, 39497,
3028        39504, 39509, 39512, 39521, 39557, 39569, 39572, 39573, 39574, 40960, 40962, 40968, 40970, 40981, 40992, 40994,
3029        41000, 41002, 41029, 41041, 41044, 41046, 41049, 41088, 41090, 41096, 41098, 41109, 41120, 41122, 41128, 41130,
3030        41221, 41225, 41233, 41236, 41238, 41241, 41242, 41286, 41289, 41297, 41301, 41304, 41306, 41313, 41316, 41349,
3031        41360, 41362, 41366, 41369, 41474, 41480, 41482, 41488, 41497, 41506, 41512, 41514, 41541, 41553, 41558, 41561,
3032        41573, 41600, 41602, 41608, 41610, 41621, 41632, 41634, 41640, 41642, 42009, 42021, 42049, 42052, 42064, 42068,
3033        42069, 42072, 42074, 42081, 42085, 42086, 42088, 42089, 42117, 42246, 42249, 42256, 42258, 42261, 42264, 42278,
3034        42281, 42306, 42309, 42321, 42324, 42325, 42326, 42329, 42341, 42346, 42369, 42372, 42373, 42374, 42377, 42386,
3035        42389, 42392, 42501, 42513, 42518, 42522, 42529, 42533, 42564, 42566, 42570, 42578, 42581, 42582, 42584, 42592,
3036        42594, 42630, 42640, 42645, 42646, 42649, 42657, 42660, 42662, 43008, 43010, 43016, 43018, 43040, 43042, 43048,
3037        43050, 43089, 43092, 43094, 43097, 43136, 43138, 43144, 43146, 43157, 43168, 43170, 43176, 43178, 43269, 43284,
3038        43289, 43297, 43301, 43329, 43344, 43349, 43354, 43361, 43366, 43369, 43408, 43414, 43520, 43522, 43528, 43530,
3039        43552, 43554, 43560, 43562, 43601, 43604, 43606, 43648, 43650, 43656, 43658, 43669, 43680, 43682, 43688, 43690,
3040    };
3041    static const uint16_t kgrid_2bit_1024[1024] = {
3042            0,     2,     5,     8,    10,    17,    20,    22,    25,    32,    34,    37,    40,    65,    68,    70,
3043           73,    80,    82,    85,    88,    97,   100,   102,   105,   128,   130,   133,   136,   145,   148,   160,
3044          165,   170,   257,   260,   262,   265,   272,   274,   277,   280,   289,   292,   320,   322,   325,   328,
3045          337,   340,   342,   345,   352,   357,   360,   385,   388,   400,   402,   405,   417,   420,   512,   514,
3046          517,   520,   529,   532,   544,   554,   577,   580,   582,   585,   592,   597,   640,   645,   650,   660,
3047          674,  1025,  1028,  1030,  1033,  1040,  1042,  1045,  1048,  1057,  1060,  1062,  1065,  1088,  1090,  1093,
3048         1096,  1098,  1105,  1108,  1110,  1113,  1120,  1122,  1125,  1153,  1156,  1158,  1161,  1168,  1173,  1176,
3049         1185,  1188,  1280,  1282,  1285,  1288,  1290,  1297,  1300,  1302,  1305,  1312,  1317,  1320,  1345,  1348,
3050         1350,  1353,  1360,  1362,  1365,  1368,  1377,  1380,  1408,  1410,  1413,  1416,  1425,  1428,  1440,  1537,
3051         1540,  1542,  1545,  1552,  1557,  1600,  1605,  1608,  1617,  1620,  1632,  1665,  1668,  1680,  2048,  2050,
3052         2053,  2056,  2065,  2068,  2070,  2073,  2080,  2085,  2090,  2113,  2116,  2118,  2121,  2128,  2130,  2133,
3053         2136,  2145,  2148,  2176,  2181,  2196,  2218,  2305,  2308,  2320,  2322,  2325,  2328,  2337,  2368,  2373,
3054         2376,  2385,  2388,  2400,  2433,  2448,  2560,  2577,  2580,  2594,  2600,  2602,  2640,  2713,  4097,  4100,
3055         4102,  4105,  4112,  4114,  4117,  4120,  4129,  4132,  4134,  4160,  4162,  4165,  4168,  4177,  4180,  4182,
3056         4185,  4192,  4194,  4197,  4200,  4225,  4228,  4230,  4240,  4245,  4248,  4257,  4260,  4352,  4354,  4357,
3057         4360,  4362,  4369,  4372,  4374,  4377,  4384,  4386,  4389,  4392,  4417,  4420,  4422,  4425,  4432,  4434,
3058         4437,  4440,  4449,  4452,  4480,  4482,  4485,  4488,  4497,  4500,  4609,  4612,  4617,  4624,  4629,  4641,
3059         4644,  4672,  4677,  4689,  4692,  4737,  4740,  4752,  5120,  5122,  5125,  5128,  5137,  5140,  5142,  5145,
3060         5152,  5157,  5160,  5185,  5188,  5190,  5193,  5200,  5202,  5205,  5208,  5217,  5220,  5248,  5250,  5253,
3061         5256,  5265,  5268,  5280,  5377,  5380,  5382,  5385,  5392,  5394,  5397,  5400,  5409,  5412,  5440,  5442,
3062         5445,  5448,  5457,  5460,  5472,  5505,  5508,  5520,  5632,  5637,  5640,  5649,  5652,  5664,  5697,  5700,
3063         5712,  5760,  5802,  6145,  6148,  6150,  6153,  6160,  6165,  6168,  6177,  6208,  6210,  6213,  6216,  6225,
3064         6228,  6240,  6273,  6276,  6400,  6402,  6405,  6408,  6417,  6420,  6432,  6465,  6468,  6480,  6505,  6562,
3065         6660,  6672,  6720,  6742,  8192,  8194,  8197,  8200,  8209,  8212,  8214,  8217,  8224,  8229,  8234,  8257,
3066         8260,  8272,  8274,  8277,  8292,  8320,  8330,  8340,  8362,  8449,  8452,  8464,  8466,  8469,  8481,  8512,
3067         8514,  8517,  8529,  8532,  8544,  8577,  8580,  8592,  8704,  8714,  8738,  8744,  8746,  8772,  8784,  8840,
3068         8842,  8872,  9217,  9220,  9222,  9225,  9232,  9237,  9240,  9249,  9252,  9280,  9282,  9285,  9288,  9297,
3069         9300,  9312,  9345,  9348,  9360,  9472,  9477,  9480,  9489,  9492,  9504,  9537,  9540,  9552,  9574,  9600,
3070         9729,  9732,  9744,  9792,  9817, 10240, 10245, 10257, 10260, 10305, 10308, 10320, 10378, 10410, 10497, 10500,
3071        10512, 10645, 10762, 10786, 10852, 10888, 10890, 16385, 16388, 16390, 16393, 16400, 16402, 16405, 16408, 16410,
3072        16417, 16420, 16422, 16448, 16450, 16453, 16456, 16458, 16465, 16468, 16470, 16473, 16480, 16482, 16485, 16513,
3073        16516, 16528, 16533, 16536, 16545, 16548, 16640, 16642, 16645, 16648, 16657, 16660, 16662, 16665, 16672, 16674,
3074        16677, 16705, 16708, 16710, 16713, 16720, 16722, 16725, 16728, 16737, 16740, 16768, 16770, 16773, 16776, 16785,
3075        16788, 16800, 16897, 16900, 16912, 16914, 16917, 16920, 16932, 16960, 16965, 16968, 16977, 16980, 16992, 17025,
3076        17028, 17408, 17410, 17413, 17416, 17418, 17425, 17428, 17430, 17433, 17440, 17442, 17445, 17448, 17473, 17476,
3077        17478, 17481, 17488, 17490, 17493, 17496, 17505, 17508, 17536, 17538, 17541, 17544, 17553, 17556, 17568, 17665,
3078        17668, 17670, 17673, 17680, 17682, 17685, 17688, 17697, 17700, 17728, 17730, 17733, 17736, 17745, 17748, 17760,
3079        17770, 17793, 17796, 17808, 17920, 17922, 17925, 17928, 17937, 17940, 17952, 17985, 17988, 18000, 18048, 18085,
3080        18433, 18436, 18441, 18448, 18450, 18453, 18456, 18465, 18468, 18496, 18498, 18501, 18504, 18513, 18516, 18528,
3081        18564, 18576, 18688, 18690, 18693, 18696, 18705, 18708, 18720, 18753, 18756, 18768, 18816, 18838, 18945, 18948,
3082        18960, 19008, 20480, 20482, 20485, 20488, 20497, 20500, 20502, 20505, 20512, 20514, 20517, 20520, 20545, 20548,
3083        20550, 20553, 20560, 20562, 20565, 20568, 20577, 20580, 20608, 20610, 20613, 20616, 20625, 20628, 20737, 20740,
3084        20742, 20745, 20752, 20754, 20757, 20760, 20769, 20772, 20800, 20802, 20805, 20808, 20817, 20820, 20832, 20865,
3085        20868, 20880, 20992, 20997, 21000, 21009, 21012, 21024, 21057, 21060, 21072, 21097, 21120, 21505, 21508, 21510,
3086        21513, 21520, 21522, 21525, 21528, 21537, 21540, 21568, 21570, 21573, 21576, 21585, 21588, 21600, 21633, 21636,
3087        21648, 21760, 21762, 21765, 21768, 21777, 21780, 21792, 21825, 21828, 21840, 21888, 22017, 22020, 22032, 22054,
3088        22080, 22528, 22530, 22533, 22536, 22545, 22548, 22560, 22593, 22596, 22608, 22618, 22656, 22785, 22788, 22800,
3089        22848, 23040, 23065, 23173, 23208, 24577, 24580, 24582, 24592, 24594, 24597, 24600, 24609, 24612, 24640, 24645,
3090        24648, 24657, 24660, 24672, 24708, 24720, 24832, 24834, 24837, 24840, 24849, 24852, 24864, 24897, 24900, 24912,
3091        24960, 24985, 25092, 25104, 25152, 25174, 25249, 25600, 25605, 25608, 25617, 25620, 25632, 25665, 25668, 25680,
3092        25728, 25857, 25860, 25872, 25920, 25930, 25960, 26002, 26112, 26260, 26625, 26628, 26640, 26725, 26776, 26880,
3093        26922, 27202, 27297, 32768, 32770, 32773, 32776, 32785, 32788, 32793, 32800, 32805, 32833, 32836, 32848, 32850,
3094        32853, 32856, 32865, 32896, 32901, 32913, 32916, 33025, 33028, 33033, 33040, 33042, 33045, 33048, 33057, 33060,
3095        33088, 33090, 33093, 33096, 33105, 33108, 33153, 33156, 33168, 33193, 33280, 33285, 33290, 33297, 33300, 33345,
3096        33348, 33360, 33793, 33796, 33798, 33801, 33808, 33810, 33813, 33816, 33825, 33856, 33858, 33861, 33864, 33873,
3097        33876, 33888, 33921, 33924, 33936, 34048, 34050, 34053, 34056, 34065, 34068, 34080, 34113, 34116, 34128, 34176,
3098        34186, 34305, 34308, 34320, 34345, 34368, 34816, 34821, 34833, 34836, 34881, 34884, 34896, 34978, 35073, 35076,
3099        35136, 35173, 35362, 35416, 35418, 35458, 35490, 36865, 36868, 36873, 36880, 36882, 36885, 36888, 36900, 36928,
3100        36930, 36933, 36936, 36945, 36948, 36960, 36993, 36996, 37008, 37120, 37125, 37137, 37140, 37185, 37188, 37200,
3101        37210, 37377, 37380, 37392, 37440, 37542, 37888, 37890, 37893, 37896, 37905, 37908, 37920, 37953, 37956, 37968,
3102        38016, 38038, 38145, 38148, 38160, 38208, 38296, 38305, 38400, 38470, 38500, 38913, 38916, 38928, 38950, 38976,
3103        39081, 39168, 39241, 39250, 39568, 40960, 40965, 40970, 40980, 40994, 41002, 41025, 41028, 41040, 41122, 41130,
3104        41280, 41317, 41474, 41482, 41506, 41512, 41514, 41602, 41608, 41610, 41640, 41985, 41988, 42000, 42048, 42121,
3105        42148, 42240, 42265, 42577, 43018, 43048, 43170, 43348, 43398, 43528, 43530, 43552, 43554, 43560, 43656, 43690,
3106    };
3107
3108    const int kmap_size = 43692;
3109    //const int nwant = type == GGML_TYPE_IQ1_S ? 3 : 2;
3110    const int nwant = type == GGML_TYPE_IQ1_S || type == GGML_TYPE_IQ1_M ? 3 : type == GGML_TYPE_IQ2_S ? 1 : 2;
3111    const uint16_t * kgrid = type == GGML_TYPE_IQ2_XXS ? kgrid_2bit_256 :
3112                             type == GGML_TYPE_IQ2_XS  ? kgrid_2bit_512 :
3113                             type == GGML_TYPE_IQ1_S || type == GGML_TYPE_IQ1_M ? kgrid_1bit_2048 : kgrid_2bit_1024;
3114    uint64_t * kgrid_q2xs;
3115    int      * kmap_q2xs;
3116    uint16_t * kneighbors_q2xs;
3117
3118    //printf("================================================================= %s(grid_size = %d)\n", __func__, grid_size);
3119    uint64_t * the_grid = (uint64_t *)malloc(grid_size*sizeof(uint64_t));
3120    for (int k = 0; k < grid_size; ++k) {
3121        int8_t * pos = (int8_t *)(the_grid + k);
3122        for (int i = 0; i < 8; ++i) {
3123            int l = (kgrid[k] >> 2*i) & 0x3;
3124            pos[i] = 2*l + 1;
3125        }
3126    }
3127    kgrid_q2xs = the_grid;
3128    iq2_data[gindex].grid = the_grid;
3129    kmap_q2xs = (int *)malloc(kmap_size*sizeof(int));
3130    iq2_data[gindex].map = kmap_q2xs;
3131    for (int i = 0; i < kmap_size; ++i) kmap_q2xs[i] = -1;
3132    uint64_t aux64;
3133    uint8_t * aux8 = (uint8_t *)&aux64;
3134    for (int i = 0; i < grid_size; ++i) {
3135        aux64 = kgrid_q2xs[i];
3136        uint16_t index = 0;
3137        for (int k=0; k<8; ++k) {
3138            uint16_t q = (aux8[k] - 1)/2;
3139            index |= (q << 2*k);
3140        }
3141        kmap_q2xs[index] = i;
3142    }
3143    // The neighbour search runs in three passes:
3144    //   1. Parallel: for each i, qsort and count its neighbours into n_per_i,
3145    //      and reduce the totals (num_neighbors, num_not_in_map).
3146    //   2. Serial: prefix-sum n_per_i into offsets[], so each i has a
3147    //      pre-assigned slice of kneighbors_q2xs to write into.
3148    //   3. Parallel: redo the qsort and write each i's neighbour list at
3149    //      offsets[i].
3150    int * n_per_i = (int *)malloc(kmap_size*sizeof(int));
3151    GGML_ASSERT(n_per_i);
3152    int num_neighbors = 0, num_not_in_map = 0;
3153#ifdef GGML_USE_OPENMP
3154    #pragma omp parallel reduction(+:num_neighbors,num_not_in_map)
3155#endif
3156    {
3157        int * dist2 = (int *)malloc(2*grid_size*sizeof(int));
3158        GGML_ASSERT(dist2);
3159        int8_t pos[8];
3160        int i;
3161#ifdef GGML_USE_OPENMP
3162        #pragma omp for schedule(dynamic, 64)
3163#endif
3164        for (i = 0; i < kmap_size; ++i) {
3165            if (kmap_q2xs[i] >= 0) {
3166                n_per_i[i] = 0;
3167                continue;
3168            }
3169            ++num_not_in_map;
3170            for (int k = 0; k < 8; ++k) {
3171                int l = (i >> 2*k) & 0x3;
3172                pos[k] = 2*l + 1;
3173            }
3174            for (int j = 0; j < grid_size; ++j) {
3175                const int8_t * pg = (const int8_t *)(kgrid_q2xs + j);
3176                int d2 = 0;
3177                for (int k = 0; k < 8; ++k) d2 += (pg[k] - pos[k])*(pg[k] - pos[k]);
3178                dist2[2*j+0] = d2;
3179                dist2[2*j+1] = j;
3180            }
3181            qsort(dist2, grid_size, 2*sizeof(int), iq2_compare_func);
3182            int n = 0; int d2 = dist2[0];
3183            int nhave = 1;
3184            for (int j = 0; j < grid_size; ++j) {
3185                if (dist2[2*j] > d2) {
3186                    if (nhave == nwant) break;
3187                    d2 = dist2[2*j];
3188                    ++nhave;
3189                }
3190                ++n;
3191            }
3192            n_per_i[i] = n;
3193            num_neighbors += n;
3194        }
3195        free(dist2);
3196    }
3197    //printf("%s: %d neighbours in total\n", __func__, num_neighbors);
3198    kneighbors_q2xs = (uint16_t *)malloc((num_neighbors + num_not_in_map)*sizeof(uint16_t));
3199    iq2_data[gindex].neighbours = kneighbors_q2xs;
3200
3201    int * offsets = (int *)malloc(kmap_size*sizeof(int));
3202    GGML_ASSERT(offsets);
3203    int counter = 0;
3204    for (int i = 0; i < kmap_size; ++i) {
3205        if (kmap_q2xs[i] >= 0) {
3206            offsets[i] = -1;
3207            continue;
3208        }
3209        offsets[i] = counter;
3210        counter += 1 + n_per_i[i];
3211    }
3212
3213#ifdef GGML_USE_OPENMP
3214    #pragma omp parallel
3215#endif
3216    {
3217        int * dist2 = (int *)malloc(2*grid_size*sizeof(int));
3218        GGML_ASSERT(dist2);
3219        int8_t pos[8];
3220        int i;
3221#ifdef GGML_USE_OPENMP
3222        #pragma omp for schedule(dynamic, 64)
3223#endif
3224        for (i = 0; i < kmap_size; ++i) {
3225            if (kmap_q2xs[i] >= 0) continue;
3226            for (int k = 0; k < 8; ++k) {
3227                int l = (i >> 2*k) & 0x3;
3228                pos[k] = 2*l + 1;
3229            }
3230            for (int j = 0; j < grid_size; ++j) {
3231                const int8_t * pg = (const int8_t *)(kgrid_q2xs + j);
3232                int d2 = 0;
3233                for (int k = 0; k < 8; ++k) d2 += (pg[k] - pos[k])*(pg[k] - pos[k]);
3234                dist2[2*j+0] = d2;
3235                dist2[2*j+1] = j;
3236            }
3237            qsort(dist2, grid_size, 2*sizeof(int), iq2_compare_func);
3238            int local_counter = offsets[i];
3239            kmap_q2xs[i] = -(local_counter + 1);
3240            int d2 = dist2[0];
3241            uint16_t * start = &kneighbors_q2xs[local_counter++];
3242            int n = 0, nhave = 1;
3243            for (int j = 0; j < grid_size; ++j) {
3244                if (dist2[2*j] > d2) {
3245                    if (nhave == nwant) break;
3246                    d2 = dist2[2*j];
3247                    ++nhave;
3248                }
3249                kneighbors_q2xs[local_counter++] = dist2[2*j+1];
3250                ++n;
3251            }
3252            *start = n;
3253        }
3254        free(dist2);
3255    }
3256    free(offsets);
3257    free(n_per_i);
3258}
3259
3260void iq2xs_free_impl(enum ggml_type type) {
3261    GGML_ASSERT(type == GGML_TYPE_IQ2_XXS || type == GGML_TYPE_IQ2_XS || type == GGML_TYPE_IQ1_S || type == GGML_TYPE_IQ1_M || type == GGML_TYPE_IQ2_S);
3262    const int gindex = iq2_data_index(type);
3263    if (iq2_data[gindex].grid) {
3264        free(iq2_data[gindex].grid);       iq2_data[gindex].grid = NULL;
3265        free(iq2_data[gindex].map);        iq2_data[gindex].map  = NULL;
3266        free(iq2_data[gindex].neighbours); iq2_data[gindex].neighbours = NULL;
3267    }
3268}
3269
3270static int iq2_find_best_neighbour(const uint16_t * GGML_RESTRICT neighbours, const uint64_t * GGML_RESTRICT grid,
3271        const float * GGML_RESTRICT xval, const float * GGML_RESTRICT weight, float scale, int8_t * GGML_RESTRICT L) {
3272    int num_neighbors = neighbours[0];
3273    GGML_ASSERT(num_neighbors > 0);
3274    float best_d2 = FLT_MAX;
3275    int grid_index = -1;
3276    for (int j = 1; j <= num_neighbors; ++j) {
3277        const int8_t * pg = (const int8_t *)(grid + neighbours[j]);
3278        float d2 = 0;
3279        for (int i = 0; i < 8; ++i) {
3280            float q = pg[i];
3281            float diff = scale*q - xval[i];
3282            d2 += weight[i]*diff*diff;
3283        }
3284        if (d2 < best_d2) {
3285            best_d2 = d2; grid_index = neighbours[j];
3286        }
3287    }
3288    GGML_ASSERT(grid_index >= 0);
3289    const int8_t * pg = (const int8_t *)(grid + grid_index);
3290    for (int i = 0; i < 8; ++i) L[i] = (pg[i] - 1)/2;
3291    return grid_index;
3292}
3293
3294static void quantize_row_iq2_xxs_impl(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t n, const float * GGML_RESTRICT quant_weights) {
3295
3296    const int gindex = iq2_data_index(GGML_TYPE_IQ2_XXS);
3297
3298    const uint64_t * kgrid_q2xs      = iq2_data[gindex].grid;
3299    const int      * kmap_q2xs       = iq2_data[gindex].map;
3300    const uint16_t * kneighbors_q2xs = iq2_data[gindex].neighbours;
3301
3302    GGML_ASSERT(quant_weights   && "missing quantization weights");
3303    GGML_ASSERT(kgrid_q2xs      && "forgot to call ggml_quantize_init()?");
3304    GGML_ASSERT(kmap_q2xs       && "forgot to call ggml_quantize_init()?");
3305    GGML_ASSERT(kneighbors_q2xs && "forgot to call ggml_quantize_init()?");
3306    GGML_ASSERT(n%QK_K == 0);
3307
3308    const int kMaxQ = 3;
3309
3310    const int64_t nbl = n/QK_K;
3311
3312    block_iq2_xxs * y = vy;
3313
3314    float scales[QK_K/32];
3315    float weight[32];
3316    float xval[32];
3317    int8_t L[32];
3318    int8_t Laux[32];
3319    float  waux[32];
3320    uint8_t block_signs[4];
3321    uint32_t q2[2*(QK_K/32)];
3322
3323    for (int ibl = 0; ibl < nbl; ++ibl) {
3324
3325        y[ibl].d = GGML_FP32_TO_FP16(0.f);
3326        memset(q2, 0, QK_K/4);
3327
3328        float max_scale = 0;
3329
3330        const float * xbl = x + QK_K*ibl;
3331        float sumx2 = 0;
3332        for (int i = 0; i < QK_K; ++i) sumx2 += xbl[i]*xbl[i];
3333        float sigma2 = sumx2/QK_K;
3334
3335        for (int ib = 0; ib < QK_K/32; ++ib) {
3336            const float * xb = xbl + 32*ib;
3337            const float * qw = quant_weights + QK_K*ibl + 32*ib;
3338            for (int i = 0; i < 32; ++i) weight[i] = qw[i] * sqrtf(sigma2 + xb[i]*xb[i]);
3339            for (int i = 0; i < 32; ++i) waux[i] = sqrtf(weight[i]);
3340            for (int k = 0; k < 4; ++k) {
3341                int nflip = 0;
3342                uint8_t s = 0;
3343                for (int i = 0; i < 8; ++i) {
3344                    if (xb[8*k + i] >= 0) xval[8*k + i] = xb[8*k + i];
3345                    else {
3346                        xval[8*k + i] = -xb[8*k + i]; ++nflip; s |= (1 << i);
3347                    }
3348                }
3349                if (nflip%2) {
3350                    int imin = 0; float min = weight[8*k+imin]*xb[8*k+imin]*xb[8*k+imin];
3351                    for (int i = 1; i < 8; ++i) {
3352                        float ax = weight[8*k+i]*xb[8*k+i]*xb[8*k+i];
3353                        if (ax < min) {
3354                            min = ax; imin = i;
3355                        }
3356                    }
3357                    xval[8*k+imin] = -xval[8*k+imin];
3358                    s ^= (1 << imin);
3359                }
3360                block_signs[k] = s & 127;
3361            }
3362            float max = xval[0];
3363            for (int i = 1; i < 32; ++i) max = MAX(max, xval[i]);
3364            if (max < GROUP_MAX_EPS) {
3365                scales[ib] = 0;
3366                memset(L, 0, 32);
3367                continue;
3368            }
3369            float scale = make_qp_quants(32, kMaxQ+1, xval, (uint8_t*)L, weight);
3370            float eff_max = scale*kMaxQ;
3371            if (eff_max <= 0) {
3372                scales[ib] = 0;
3373                memset(L, 0, 32);
3374                continue;
3375            }
3376            float best = 0;
3377            for (int is = -6; is <= 6; ++is) {
3378                float id = (2*kMaxQ-1+is*0.1f)/eff_max;
3379                float this_scale = 1/id;
3380                for (int k = 0; k < 4; ++k) {
3381                    for (int i = 0; i < 8; ++i) {
3382                        int l = nearest_int(0.5f*(id*xval[8*k+i]-1));
3383                        Laux[8*k+i] = MAX(0, MIN(kMaxQ-1, l));
3384                    }
3385                    uint16_t u = 0;
3386                    for (int i = 0; i < 8; ++i) u |= (Laux[8*k+i] << 2*i);
3387                    int grid_index = kmap_q2xs[u];
3388                    if (grid_index < 0) {
3389                        const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1;
3390                        grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, this_scale, Laux + 8*k);
3391                    }
3392                }
3393                float sumqx = 0, sumq2 = 0;
3394                for (int i = 0; i < 32; ++i) {
3395                    float w = weight[i];
3396                    float q = 2*Laux[i] + 1;
3397                    sumqx += w*xval[i]*q;
3398                    sumq2 += w*q*q;
3399                }
3400                if (sumq2 > 0 && sumqx*sumqx > best*sumq2) {
3401                    scale = sumqx/sumq2; best = scale*sumqx;
3402                    memcpy(L, Laux, 32);
3403                }
3404            }
3405            if (scale > 0) {
3406                float id = 1/scale;
3407                for (int k = 0; k < 4; ++k) {
3408                    uint16_t u = 0;
3409                    for (int i = 0; i < 8; ++i) {
3410                        int l = nearest_int(0.5f*(id*xval[8*k+i]-1));
3411                        l = MAX(0, MIN(kMaxQ-1, l));
3412                        u |= (l << 2*i);
3413                    }
3414                    int grid_index = kmap_q2xs[u];
3415                    if (grid_index < 0) {
3416                        const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1;
3417                        grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, scale, L + 8*k);
3418                    }
3419                    const int8_t * pg = (const int8_t *)(kgrid_q2xs + grid_index);
3420                    for (int i = 0; i < 8; ++i) L[8*k+i] = (pg[i] - 1)/2;
3421                }
3422                float sumqx = 0, sumq2 = 0;
3423                for (int i = 0; i < 32; ++i) {
3424                    float w = weight[i];
3425                    float q = 2*L[i] + 1;
3426                    sumqx += w*xval[i]*q;
3427                    sumq2 += w*q*q;
3428                }
3429                if (sumq2 > 0) scale = sumqx/sumq2;
3430            }
3431            if (scale < 0) {
3432                // This should never happen, but just in case, flip scale so that it is positive (we use uint's to encode the scale)
3433                // and correspondingly flip quant signs.
3434                scale = -scale;
3435                for (int k = 0; k < 4; ++k) block_signs[k] = (~block_signs[k]) & 127;
3436            }
3437            for (int k = 0; k < 4; ++k) {
3438                uint16_t u = 0;
3439                for (int i = 0; i < 8; ++i) u |= (L[8*k+i] << 2*i);
3440                int grid_index = kmap_q2xs[u];
3441                if (grid_index < 0) {
3442                    printf("Oops: found point %u not on grid:", u);
3443                    for (int i = 0; i < 8; ++i) printf(" %d", L[8*k+i]);
3444                    printf("\n");
3445                    GGML_ABORT("fatal error");
3446                }
3447                q2[2*ib+0] |= ((uint32_t) grid_index << 8*k);
3448                q2[2*ib+1] |= (block_signs[k] << 7*k);
3449            }
3450            GGML_ASSERT(scale >= 0);
3451            scales[ib] = scale;
3452            max_scale = MAX(max_scale, scale);
3453        }
3454
3455        if (!max_scale) {
3456            memset(y[ibl].qs, 0, QK_K/4);
3457            continue;
3458        }
3459
3460        float d = max_scale/31;
3461        y[ibl].d = GGML_FP32_TO_FP16(d);
3462        float id = 1/d;
3463        for (int ib = 0; ib < QK_K/32; ++ib) {
3464            int l = nearest_int(0.5f*(id*scales[ib]-1));
3465            l = MAX(0, MIN(15, l));
3466            q2[2*ib+1] |= ((uint32_t)l << 28);
3467        }
3468        memcpy(y[ibl].qs, q2, QK_K/4);
3469    }
3470}
3471
3472static void quantize_row_iq2_xs_impl(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t n, const float * GGML_RESTRICT quant_weights) {
3473
3474    const int gindex = iq2_data_index(GGML_TYPE_IQ2_XS);
3475
3476    const uint64_t * kgrid_q2xs      = iq2_data[gindex].grid;
3477    const int      * kmap_q2xs       = iq2_data[gindex].map;
3478    const uint16_t * kneighbors_q2xs = iq2_data[gindex].neighbours;
3479
3480    GGML_ASSERT(quant_weights   && "missing quantization weights");
3481    GGML_ASSERT(kmap_q2xs       && "forgot to call ggml_quantize_init()?");
3482    GGML_ASSERT(kgrid_q2xs      && "forgot to call ggml_quantize_init()?");
3483    GGML_ASSERT(kneighbors_q2xs && "forgot to call ggml_quantize_init()?");
3484    GGML_ASSERT(n%QK_K == 0);
3485
3486    const int kMaxQ = 3;
3487
3488    const int64_t nbl = n/QK_K;
3489
3490    block_iq2_xs * y = vy;
3491
3492    float scales[QK_K/16];
3493    float weight[16];
3494    float xval[16];
3495    int8_t L[16];
3496    int8_t Laux[16];
3497    float  waux[16];
3498    bool   is_on_grid[2];
3499    bool   is_on_grid_aux[2];
3500    uint8_t block_signs[2];
3501    uint16_t q2[2*(QK_K/16)];
3502
3503    for (int ibl = 0; ibl < nbl; ++ibl) {
3504
3505        y[ibl].d = GGML_FP32_TO_FP16(0.f);
3506        memset(q2, 0, QK_K/4);
3507        memset(y[ibl].scales, 0, QK_K/32);
3508
3509        float max_scale = 0;
3510
3511        const float * xbl = x + QK_K*ibl;
3512        float sumx2 = 0;
3513        for (int i = 0; i < QK_K; ++i) sumx2 += xbl[i]*xbl[i];
3514        float sigma2 = sumx2/QK_K;
3515
3516        for (int ib = 0; ib < QK_K/16; ++ib) {
3517            const float * xb = xbl + 16*ib;
3518            const float * qw = quant_weights + QK_K*ibl + 16*ib;
3519            for (int i = 0; i < 16; ++i) weight[i] = qw[i] * sqrtf(sigma2 + xb[i]*xb[i]);
3520            for (int i = 0; i < 16; ++i) waux[i] = sqrtf(weight[i]);
3521            for (int k = 0; k < 2; ++k) {
3522                int nflip = 0;
3523                uint8_t s = 0;
3524                for (int i = 0; i < 8; ++i) {
3525                    if (xb[8*k + i] >= 0) xval[8*k + i] = xb[8*k + i];
3526                    else {
3527                        xval[8*k + i] = -xb[8*k + i]; ++nflip; s |= (1 << i);
3528                    }
3529                }
3530                if (nflip%2) {
3531                    int imin = 0; float min = weight[8*k+imin]*xb[8*k+imin]*xb[8*k+imin];
3532                    for (int i = 1; i < 8; ++i) {
3533                        float ax = weight[8*k+i]*xb[8*k+i]*xb[8*k+i];
3534                        if (ax < min) {
3535                            min = ax; imin = i;
3536                        }
3537                    }
3538                    xval[8*k+imin] = -xval[8*k+imin];
3539                    s ^= (1 << imin);
3540                }
3541                block_signs[k] = s & 127;
3542            }
3543            float max = xval[0];
3544            for (int i = 1; i < 16; ++i) max = MAX(max, xval[i]);
3545            memset(L, 0, 16);
3546            if (max < GROUP_MAX_EPS) {
3547                scales[ib] = 0;
3548                continue;
3549            }
3550            float best = 0;
3551            float scale = max/(2*kMaxQ-1);
3552            is_on_grid[0] = is_on_grid[1] = true;
3553            for (int is = -9; is <= 9; ++is) {
3554                float id = (2*kMaxQ-1+is*0.1f)/max;
3555                float this_scale = 1/id;
3556                for (int k = 0; k < 2; ++k) {
3557                    for (int i = 0; i < 8; ++i) {
3558                        int l = nearest_int(0.5f*(id*xval[8*k+i]-1));
3559                        Laux[8*k+i] = MAX(0, MIN(kMaxQ-1, l));
3560                    }
3561                    uint16_t u = 0;
3562                    for (int i = 0; i < 8; ++i) u |= (Laux[8*k+i] << 2*i);
3563                    int grid_index = kmap_q2xs[u];
3564                    is_on_grid_aux[k] = true;
3565                    if (grid_index < 0) {
3566                        is_on_grid_aux[k] = false;
3567                        const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1;
3568                        grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, this_scale, Laux + 8*k);
3569                    }
3570                }
3571                float sumqx = 0, sumq2 = 0;
3572                for (int i = 0; i < 16; ++i) {
3573                    float w = weight[i];
3574                    float q = 2*Laux[i] + 1;
3575                    sumqx += w*xval[i]*q;
3576                    sumq2 += w*q*q;
3577                }
3578                if (sumq2 > 0 && sumqx*sumqx > best*sumq2) {
3579                    scale = sumqx/sumq2; best = scale*sumqx;
3580                    for (int i = 0; i < 16; ++i) L[i] = Laux[i];
3581                    for (int k = 0; k <  2; ++k) is_on_grid[k] = is_on_grid_aux[k];
3582                }
3583            }
3584            int n_not_ongrid = 0;
3585            for (int k = 0; k < 2; ++k) if (!is_on_grid[k]) ++n_not_ongrid;
3586            if (n_not_ongrid > 0 && scale > 0) {
3587                float id = 1/scale;
3588                for (int k = 0; k < 2; ++k) {
3589                    if (is_on_grid[k]) continue;
3590                    uint16_t u = 0;
3591                    for (int i = 0; i < 8; ++i) {
3592                        int l = nearest_int(0.5f*(id*xval[8*k+i]-1));
3593                        l = MAX(0, MIN(kMaxQ-1, l));
3594                        u |= (l << 2*i);
3595                        L[8*k + i] = l;
3596                    }
3597                    int grid_index = kmap_q2xs[u];
3598                    if (grid_index < 0) {
3599                        const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1;
3600                        grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, scale, L + 8*k);
3601                    }
3602                }
3603                float sumqx = 0, sumq2 = 0;
3604                for (int i = 0; i < 16; ++i) {
3605                    float w = weight[i];
3606                    float q = 2*L[i] + 1;
3607                    sumqx += w*xval[i]*q;
3608                    sumq2 += w*q*q;
3609                }
3610                if (sumq2 > 0) scale = sumqx/sumq2;
3611            }
3612            if (scale < 0) {
3613                scale = -scale;
3614                for (int k = 0; k < 2; ++k) block_signs[k] = (~block_signs[k]) & 127;
3615            }
3616            for (int k = 0; k < 2; ++k) {
3617                uint16_t u = 0;
3618                for (int i = 0; i < 8; ++i) u |= (L[8*k+i] << 2*i);
3619                int grid_index = kmap_q2xs[u];
3620                if (grid_index < 0) {
3621                    printf("Oops: found point %u not on grid:", u);
3622                    for (int i = 0; i < 8; ++i) printf(" %d", L[8*k+i]);
3623                    printf("\n");
3624                    GGML_ABORT("fatal error");
3625                }
3626                q2[2*ib+k] = grid_index | (block_signs[k] << 9);
3627            }
3628            GGML_ASSERT(scale >= 0);
3629            scales[ib] = scale;
3630            max_scale = MAX(max_scale, scale);
3631        }
3632
3633        if (!max_scale) {
3634            memset(y[ibl].qs, 0, QK_K/4);
3635            continue;
3636        }
3637
3638        float d = max_scale/31;
3639        y[ibl].d = GGML_FP32_TO_FP16(d);
3640        float id = 1/d;
3641        for (int ib = 0; ib < QK_K/16; ++ib) {
3642            int l = nearest_int(0.5f*(id*scales[ib]-1));
3643            l = MAX(0, MIN(15, l));
3644            if (ib%2 == 0) y[ibl].scales[ib/2] = l;
3645            else y[ibl].scales[ib/2] |= (l << 4);
3646        }
3647        memcpy(y[ibl].qs, q2, QK_K/4);
3648
3649    }
3650}
3651
3652size_t quantize_iq2_xxs(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
3653    GGML_ASSERT(n_per_row%QK_K == 0);
3654    int64_t nblock = n_per_row/QK_K;
3655    char * qrow = (char *)dst;
3656    for (int64_t row = 0; row < nrow; ++row) {
3657        quantize_row_iq2_xxs_impl(src, qrow, n_per_row, quant_weights);
3658        src += n_per_row;
3659        qrow += nblock*sizeof(block_iq2_xxs);
3660    }
3661    return nrow * nblock * sizeof(block_iq2_xxs);
3662}
3663
3664size_t quantize_iq2_xs(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
3665    GGML_ASSERT(n_per_row%QK_K == 0);
3666    int64_t nblock = n_per_row/QK_K;
3667    char * qrow = (char *)dst;
3668    for (int64_t row = 0; row < nrow; ++row) {
3669        quantize_row_iq2_xs_impl(src, qrow, n_per_row, quant_weights);
3670        src += n_per_row;
3671        qrow += nblock*sizeof(block_iq2_xs);
3672    }
3673    return nrow * nblock * sizeof(block_iq2_xs);
3674}
3675
3676//
3677// ============================================= 3-bit using D4 lattice
3678//
3679
3680typedef struct {
3681    uint32_t * grid;
3682    int      * map;
3683    uint16_t * neighbours;
3684} iq3_entry_t;
3685
3686static iq3_entry_t iq3_data[2] = {
3687    {NULL, NULL, NULL},
3688    {NULL, NULL, NULL},
3689};
3690
3691static inline int iq3_data_index(int grid_size) {
3692    (void)grid_size;
3693    GGML_ASSERT(grid_size == 256 || grid_size == 512);
3694    return grid_size == 256 ? 0 : 1;
3695}
3696
3697static int iq3_compare_func(const void * left, const void * right) {
3698    const int * l = (const int *)left;
3699    const int * r = (const int *)right;
3700    return l[0] < r[0] ? -1 : l[0] > r[0] ? 1 : l[1] < r[1] ? -1 : l[1] > r[1] ? 1 : 0;
3701}
3702
3703void iq3xs_init_impl(int grid_size) {
3704    const int gindex = iq3_data_index(grid_size);
3705    if (iq3_data[gindex].grid) {
3706        return;
3707    }
3708    static const uint16_t kgrid_256[256] = {
3709            0,     2,     4,     9,    11,    15,    16,    18,    25,    34,    59,    61,    65,    67,    72,    74,
3710           81,    85,    88,    90,    97,   108,   120,   128,   130,   132,   137,   144,   146,   153,   155,   159,
3711          169,   175,   189,   193,   199,   200,   202,   213,   248,   267,   287,   292,   303,   315,   317,   321,
3712          327,   346,   362,   413,   436,   456,   460,   462,   483,   497,   513,   515,   520,   522,   529,   531,
3713          536,   538,   540,   551,   552,   576,   578,   585,   592,   594,   641,   643,   648,   650,   657,   664,
3714          698,   704,   706,   720,   729,   742,   758,   769,   773,   808,   848,   852,   870,   889,   901,   978,
3715          992,  1024,  1026,  1033,  1035,  1040,  1042,  1046,  1049,  1058,  1089,  1091,  1093,  1096,  1098,  1105,
3716         1112,  1139,  1143,  1144,  1152,  1154,  1161,  1167,  1168,  1170,  1183,  1184,  1197,  1217,  1224,  1228,
3717         1272,  1276,  1309,  1323,  1347,  1367,  1377,  1404,  1473,  1475,  1486,  1509,  1537,  1544,  1546,  1553,
3718         1555,  1576,  1589,  1594,  1600,  1602,  1616,  1625,  1636,  1638,  1665,  1667,  1672,  1685,  1706,  1722,
3719         1737,  1755,  1816,  1831,  1850,  1856,  1862,  1874,  1901,  1932,  1950,  1971,  2011,  2032,  2052,  2063,
3720         2077,  2079,  2091,  2095,  2172,  2192,  2207,  2208,  2224,  2230,  2247,  2277,  2308,  2345,  2356,  2389,
3721         2403,  2424,  2501,  2504,  2506,  2520,  2570,  2593,  2616,  2624,  2630,  2646,  2669,  2700,  2714,  2746,
3722         2754,  2795,  2824,  2835,  2839,  2874,  2882,  2905,  2984,  3028,  3042,  3092,  3108,  3110,  3124,  3153,
3723         3185,  3215,  3252,  3288,  3294,  3364,  3397,  3434,  3483,  3523,  3537,  3587,  3589,  3591,  3592,  3610,
3724         3626,  3670,  3680,  3722,  3749,  3754,  3776,  3789,  3803,  3824,  3857,  3873,  3904,  3906,  3924,  3992,
3725    };
3726    static const uint16_t kgrid_512[512] = {
3727            0,     1,     2,     5,     7,     8,     9,    10,    12,    14,    16,    17,    21,    27,    32,    34,
3728           37,    39,    41,    43,    48,    50,    57,    60,    63,    64,    65,    66,    68,    72,    73,    77,
3729           80,    83,    87,    89,    93,   100,   113,   117,   122,   128,   129,   133,   135,   136,   139,   142,
3730          145,   149,   152,   156,   162,   165,   167,   169,   171,   184,   187,   195,   201,   205,   208,   210,
3731          217,   219,   222,   228,   232,   234,   247,   249,   253,   256,   267,   271,   273,   276,   282,   288,
3732          291,   297,   312,   322,   324,   336,   338,   342,   347,   353,   357,   359,   374,   379,   390,   393,
3733          395,   409,   426,   441,   448,   450,   452,   464,   466,   470,   475,   488,   492,   512,   513,   514,
3734          516,   520,   521,   523,   525,   527,   528,   530,   537,   540,   542,   556,   558,   561,   570,   576,
3735          577,   579,   582,   584,   588,   593,   600,   603,   609,   616,   618,   632,   638,   640,   650,   653,
3736          655,   656,   660,   666,   672,   675,   685,   688,   698,   705,   708,   711,   712,   715,   721,   727,
3737          728,   732,   737,   754,   760,   771,   773,   778,   780,   793,   795,   802,   806,   808,   812,   833,
3738          840,   843,   849,   856,   858,   873,   912,   916,   919,   932,   934,   961,   963,   968,   970,   977,
3739          989,   993,  1010,  1016,  1024,  1025,  1027,  1029,  1031,  1032,  1034,  1036,  1038,  1041,  1043,  1047,
3740         1048,  1050,  1057,  1059,  1061,  1064,  1066,  1079,  1080,  1083,  1085,  1088,  1090,  1096,  1099,  1103,
3741         1106,  1109,  1113,  1116,  1122,  1129,  1153,  1156,  1159,  1169,  1171,  1176,  1183,  1185,  1195,  1199,
3742         1209,  1212,  1216,  1218,  1221,  1225,  1234,  1236,  1241,  1243,  1250,  1256,  1270,  1281,  1287,  1296,
3743         1299,  1306,  1309,  1313,  1338,  1341,  1348,  1353,  1362,  1375,  1376,  1387,  1400,  1408,  1410,  1415,
3744         1425,  1453,  1457,  1477,  1481,  1494,  1496,  1507,  1512,  1538,  1545,  1547,  1549,  1551,  1554,  1561,
3745         1563,  1565,  1570,  1572,  1575,  1577,  1587,  1593,  1601,  1603,  1605,  1612,  1617,  1619,  1632,  1648,
3746         1658,  1662,  1664,  1674,  1680,  1690,  1692,  1704,  1729,  1736,  1740,  1745,  1747,  1751,  1752,  1761,
3747         1763,  1767,  1773,  1787,  1795,  1801,  1806,  1810,  1817,  1834,  1840,  1844,  1857,  1864,  1866,  1877,
3748         1882,  1892,  1902,  1915,  1934,  1953,  1985,  1987,  2000,  2002,  2013,  2048,  2052,  2058,  2064,  2068,
3749         2071,  2074,  2081,  2088,  2104,  2114,  2119,  2121,  2123,  2130,  2136,  2141,  2147,  2153,  2157,  2177,
3750         2179,  2184,  2189,  2193,  2203,  2208,  2223,  2226,  2232,  2244,  2249,  2251,  2256,  2258,  2265,  2269,
3751         2304,  2306,  2324,  2335,  2336,  2361,  2373,  2375,  2385,  2418,  2443,  2460,  2480,  2504,  2509,  2520,
3752         2531,  2537,  2562,  2568,  2572,  2578,  2592,  2596,  2599,  2602,  2614,  2620,  2625,  2627,  2629,  2634,
3753         2641,  2650,  2682,  2688,  2697,  2707,  2712,  2718,  2731,  2754,  2759,  2760,  2775,  2788,  2793,  2805,
3754         2811,  2817,  2820,  2832,  2842,  2854,  2890,  2902,  2921,  2923,  2978,  3010,  3012,  3026,  3081,  3083,
3755         3085,  3097,  3099,  3120,  3136,  3152,  3159,  3188,  3210,  3228,  3234,  3245,  3250,  3256,  3264,  3276,
3756         3281,  3296,  3349,  3363,  3378,  3392,  3395,  3420,  3440,  3461,  3488,  3529,  3531,  3584,  3588,  3591,
3757         3600,  3602,  3614,  3616,  3628,  3634,  3650,  3657,  3668,  3683,  3685,  3713,  3716,  3720,  3726,  3729,
3758         3736,  3753,  3778,  3802,  3805,  3819,  3841,  3845,  3851,  3856,  3880,  3922,  3938,  3970,  3993,  4032,
3759    };
3760
3761    const int kmap_size = 4096;
3762    const int nwant = grid_size == 256 ? 2 : 3;
3763    const uint16_t * kgrid = grid_size == 256 ? kgrid_256 : kgrid_512;
3764    uint32_t * kgrid_q3xs;
3765    int      * kmap_q3xs;
3766    uint16_t * kneighbors_q3xs;
3767
3768    //printf("================================================================= %s(grid_size = %d)\n", __func__, grid_size);
3769    uint32_t * the_grid = (uint32_t *)malloc(grid_size*sizeof(uint32_t));
3770    for (int k = 0; k < grid_size; ++k) {
3771        int8_t * pos = (int8_t *)(the_grid + k);
3772        for (int i = 0; i < 4; ++i) {
3773            int l = (kgrid[k] >> 3*i) & 0x7;
3774            pos[i] = 2*l + 1;
3775        }
3776    }
3777    kgrid_q3xs = the_grid;
3778    iq3_data[gindex].grid = the_grid;
3779    kmap_q3xs = (int *)malloc(kmap_size*sizeof(int));
3780    iq3_data[gindex].map = kmap_q3xs;
3781    for (int i = 0; i < kmap_size; ++i) kmap_q3xs[i] = -1;
3782    uint32_t aux32;
3783    uint8_t * aux8 = (uint8_t *)&aux32;
3784    for (int i = 0; i < grid_size; ++i) {
3785        aux32 = kgrid_q3xs[i];
3786        uint16_t index = 0;
3787        for (int k=0; k<4; ++k) {
3788            uint16_t q = (aux8[k] - 1)/2;
3789            index |= (q << 3*k);
3790        }
3791        kmap_q3xs[index] = i;
3792    }
3793    // See explanation of parallelism in iq2xs_init_impl
3794    int * n_per_i = (int *)malloc(kmap_size*sizeof(int));
3795    GGML_ASSERT(n_per_i);
3796    int num_neighbors = 0, num_not_in_map = 0;
3797#ifdef GGML_USE_OPENMP
3798    #pragma omp parallel reduction(+:num_neighbors,num_not_in_map)
3799#endif
3800    {
3801        int * dist2 = (int *)malloc(2*grid_size*sizeof(int));
3802        GGML_ASSERT(dist2);
3803        int8_t pos[4];
3804        int i;
3805#ifdef GGML_USE_OPENMP
3806        #pragma omp for schedule(dynamic, 64)
3807#endif
3808        for (i = 0; i < kmap_size; ++i) {
3809            if (kmap_q3xs[i] >= 0) {
3810                n_per_i[i] = 0;
3811                continue;
3812            }
3813            ++num_not_in_map;
3814            for (int k = 0; k < 4; ++k) {
3815                int l = (i >> 3*k) & 0x7;
3816                pos[k] = 2*l + 1;
3817            }
3818            for (int j = 0; j < grid_size; ++j) {
3819                const int8_t * pg = (const int8_t *)(kgrid_q3xs + j);
3820                int d2 = 0;
3821                for (int k = 0; k < 4; ++k) d2 += (pg[k] - pos[k])*(pg[k] - pos[k]);
3822                dist2[2*j+0] = d2;
3823                dist2[2*j+1] = j;
3824            }
3825            qsort(dist2, grid_size, 2*sizeof(int), iq3_compare_func);
3826            int n = 0; int d2 = dist2[0];
3827            int nhave = 1;
3828            for (int j = 0; j < grid_size; ++j) {
3829                if (dist2[2*j] > d2) {
3830                    if (nhave == nwant) break;
3831                    d2 = dist2[2*j];
3832                    ++nhave;
3833                }
3834                ++n;
3835            }
3836            n_per_i[i] = n;
3837            num_neighbors += n;
3838        }
3839        free(dist2);
3840    }
3841    //printf("%s: %d neighbours in total\n", __func__, num_neighbors);
3842    kneighbors_q3xs = (uint16_t *)malloc((num_neighbors + num_not_in_map)*sizeof(uint16_t));
3843    iq3_data[gindex].neighbours = kneighbors_q3xs;
3844
3845    int * offsets = (int *)malloc(kmap_size*sizeof(int));
3846    GGML_ASSERT(offsets);
3847    int counter = 0;
3848    for (int i = 0; i < kmap_size; ++i) {
3849        if (kmap_q3xs[i] >= 0) {
3850            offsets[i] = -1;
3851            continue;
3852        }
3853        offsets[i] = counter;
3854        counter += 1 + n_per_i[i];
3855    }
3856
3857#ifdef GGML_USE_OPENMP
3858    #pragma omp parallel
3859#endif
3860    {
3861        int * dist2 = (int *)malloc(2*grid_size*sizeof(int));
3862        GGML_ASSERT(dist2);
3863        int8_t pos[4];
3864        int i;
3865#ifdef GGML_USE_OPENMP
3866        #pragma omp for schedule(dynamic, 64)
3867#endif
3868        for (i = 0; i < kmap_size; ++i) {
3869            if (kmap_q3xs[i] >= 0) continue;
3870            for (int k = 0; k < 4; ++k) {
3871                int l = (i >> 3*k) & 0x7;
3872                pos[k] = 2*l + 1;
3873            }
3874            for (int j = 0; j < grid_size; ++j) {
3875                const int8_t * pg = (const int8_t *)(kgrid_q3xs + j);
3876                int d2 = 0;
3877                for (int k = 0; k < 4; ++k) d2 += (pg[k] - pos[k])*(pg[k] - pos[k]);
3878                dist2[2*j+0] = d2;
3879                dist2[2*j+1] = j;
3880            }
3881            qsort(dist2, grid_size, 2*sizeof(int), iq3_compare_func);
3882            int local_counter = offsets[i];
3883            kmap_q3xs[i] = -(local_counter + 1);
3884            int d2 = dist2[0];
3885            uint16_t * start = &kneighbors_q3xs[local_counter++];
3886            int n = 0, nhave = 1;
3887            for (int j = 0; j < grid_size; ++j) {
3888                if (dist2[2*j] > d2) {
3889                    if (nhave == nwant) break;
3890                    d2 = dist2[2*j];
3891                    ++nhave;
3892                }
3893                kneighbors_q3xs[local_counter++] = dist2[2*j+1];
3894                ++n;
3895            }
3896            *start = n;
3897        }
3898        free(dist2);
3899    }
3900    free(offsets);
3901    free(n_per_i);
3902}
3903
3904void iq3xs_free_impl(int grid_size) {
3905    GGML_ASSERT(grid_size == 256 || grid_size == 512);
3906    const int gindex = iq3_data_index(grid_size);
3907    if (iq3_data[gindex].grid) {
3908        free(iq3_data[gindex].grid);       iq3_data[gindex].grid = NULL;
3909        free(iq3_data[gindex].map);        iq3_data[gindex].map  = NULL;
3910        free(iq3_data[gindex].neighbours); iq3_data[gindex].neighbours = NULL;
3911    }
3912}
3913
3914static int iq3_find_best_neighbour(const uint16_t * GGML_RESTRICT neighbours, const uint32_t * GGML_RESTRICT grid,
3915        const float * GGML_RESTRICT xval, const float * GGML_RESTRICT weight, float scale, int8_t * GGML_RESTRICT L) {
3916    int num_neighbors = neighbours[0];
3917    GGML_ASSERT(num_neighbors > 0);
3918    float best_d2 = FLT_MAX;
3919    int grid_index = -1;
3920    for (int j = 1; j <= num_neighbors; ++j) {
3921        const int8_t * pg = (const int8_t *)(grid + neighbours[j]);
3922        float d2 = 0;
3923        for (int i = 0; i < 4; ++i) {
3924            float q = pg[i];
3925            float diff = scale*q - xval[i];
3926            d2 += weight[i]*diff*diff;
3927        }
3928        if (d2 < best_d2) {
3929            best_d2 = d2; grid_index = neighbours[j];
3930        }
3931    }
3932    GGML_ASSERT(grid_index >= 0);
3933    const int8_t * pg = (const int8_t *)(grid + grid_index);
3934    for (int i = 0; i < 4; ++i) L[i] = (pg[i] - 1)/2;
3935    return grid_index;
3936}
3937
3938static void quantize_row_iq3_xxs_impl(int grid_size, const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t n,
3939        const float * GGML_RESTRICT quant_weights) {
3940
3941    const int gindex = iq3_data_index(grid_size);
3942
3943    const uint32_t * kgrid_q3xs      = iq3_data[gindex].grid;
3944    const int      * kmap_q3xs       = iq3_data[gindex].map;
3945    const uint16_t * kneighbors_q3xs = iq3_data[gindex].neighbours;
3946
3947    //GGML_ASSERT(quant_weights   && "missing quantization weights");
3948    GGML_ASSERT(kgrid_q3xs      && "forgot to call ggml_quantize_init()?");
3949    GGML_ASSERT(kmap_q3xs       && "forgot to call ggml_quantize_init()?");
3950    GGML_ASSERT(kneighbors_q3xs && "forgot to call ggml_quantize_init()?");
3951    GGML_ASSERT(n%QK_K == 0);
3952
3953    const int kMaxQ = 8;
3954
3955    const int64_t nbl = n/QK_K;
3956
3957    ggml_fp16_t * dh;
3958    uint8_t * qs;
3959    int block_size;
3960    if (grid_size == 256) {
3961        block_iq3_xxs * y = vy;
3962        dh = &y->d;
3963        qs = y->qs;
3964        block_size = sizeof(block_iq3_xxs);
3965    } else {
3966        block_iq3_s * y = vy;
3967        dh = &y->d;
3968        qs = y->qs;
3969        block_size = sizeof(block_iq3_s);
3970    }
3971    int quant_size = block_size - sizeof(ggml_fp16_t);
3972
3973    float scales[QK_K/32];
3974    float weight[32];
3975    float xval[32];
3976    int8_t L[32];
3977    int8_t Laux[32];
3978    float  waux[32];
3979    bool   is_on_grid[8];
3980    bool   is_on_grid_aux[8];
3981    uint8_t block_signs[8];
3982    uint8_t q3[3*(QK_K/8)+QK_K/32];
3983    uint32_t * scales_and_signs = (uint32_t *)(q3 + QK_K/4);
3984    uint8_t  * qh = q3 + 3*(QK_K/8);
3985
3986    for (int ibl = 0; ibl < nbl; ++ibl) {
3987
3988        dh[0] = GGML_FP32_TO_FP16(0.f);
3989        memset(q3, 0, 3*QK_K/8+QK_K/32);
3990
3991        float max_scale = 0;
3992
3993        const float * xbl = x + QK_K*ibl;
3994        float sumx2 = 0;
3995        for (int i = 0; i < QK_K; ++i) sumx2 += xbl[i]*xbl[i];
3996        float sigma2 = 2*sumx2/QK_K;
3997
3998        for (int ib = 0; ib < QK_K/32; ++ib) {
3999            const float * xb = xbl + 32*ib;
4000            if (quant_weights) {
4001                const float * qw = quant_weights + QK_K*ibl + 32*ib;
4002                for (int i = 0; i < 32; ++i) weight[i] = qw[i] * sqrtf(sigma2 + xb[i]*xb[i]);
4003            } else {
4004                for (int i = 0; i < 32; ++i) weight[i] = xb[i]*xb[i];
4005            }
4006            for (int i = 0; i < 32; ++i) waux[i] = sqrtf(weight[i]);
4007            for (int k = 0; k < 4; ++k) {
4008                int nflip = 0;
4009                uint8_t s = 0;
4010                for (int i = 0; i < 8; ++i) {
4011                    if (xb[8*k + i] >= 0) xval[8*k + i] = xb[8*k + i];
4012                    else {
4013                        xval[8*k + i] = -xb[8*k + i]; ++nflip; s |= (1 << i);
4014                    }
4015                }
4016                if (nflip%2) {
4017                    int imin = 0; float min = weight[8*k+imin]*xb[8*k+imin]*xb[8*k+imin];
4018                    for (int i = 1; i < 8; ++i) {
4019                        float ax = weight[8*k+i]*xb[8*k+i]*xb[8*k+i];
4020                        if (ax < min) {
4021                            min = ax; imin = i;
4022                        }
4023                    }
4024                    xval[8*k+imin] = -xval[8*k+imin];
4025                    s ^= (1 << imin);
4026                }
4027                block_signs[k] = s & 127;
4028            }
4029            float max = xval[0];
4030            for (int i = 1; i < 32; ++i) max = MAX(max, xval[i]);
4031            memset(L, 0, 32);
4032            if (max < GROUP_MAX_EPS_IQ3_XXS) {
4033                scales[ib] = 0;
4034                continue;
4035            }
4036            float best = 0;
4037            float scale = max/(2*kMaxQ-1);
4038            for (int k = 0; k < 8; ++k) is_on_grid[k] = true;
4039            for (int is = -15; is <= 15; ++is) {
4040                float id = (2*kMaxQ-1+is*0.2f)/max;
4041                float this_scale = 1/id;
4042                for (int k = 0; k < 8; ++k) {
4043                    for (int i = 0; i < 4; ++i) {
4044                        int l = nearest_int(0.5f*(id*xval[4*k+i]-1));
4045                        Laux[4*k+i] = MAX(0, MIN(kMaxQ-1, l));
4046                    }
4047                    uint16_t u = 0;
4048                    for (int i = 0; i < 4; ++i) u |= (Laux[4*k+i] << 3*i);
4049                    int grid_index = kmap_q3xs[u];
4050                    is_on_grid_aux[k] = true;
4051                    if (grid_index < 0) {
4052                        is_on_grid_aux[k] = false;
4053                        const uint16_t * neighbours = kneighbors_q3xs - kmap_q3xs[u] - 1;
4054                        grid_index = iq3_find_best_neighbour(neighbours, kgrid_q3xs, xval + 4*k, waux + 4*k, this_scale, Laux + 4*k);
4055                    }
4056                }
4057                float sumqx = 0, sumq2 = 0;
4058                for (int i = 0; i < 32; ++i) {
4059                    float w = weight[i];
4060                    float q = 2*Laux[i] + 1;
4061                    sumqx += w*xval[i]*q;
4062                    sumq2 += w*q*q;
4063                }
4064                if (sumq2 > 0 && sumqx*sumqx > best*sumq2) {
4065                    scale = sumqx/sumq2; best = scale*sumqx;
4066                    for (int i = 0; i < 32; ++i) L[i] = Laux[i];
4067                    for (int k = 0; k <  8; ++k) is_on_grid[k] = is_on_grid_aux[k];
4068                }
4069            }
4070            int n_not_ongrid = 0;
4071            for (int k = 0; k < 8; ++k) if (!is_on_grid[k]) ++n_not_ongrid;
4072            if (n_not_ongrid > 0 && scale > 0) {
4073                float id = 1/scale;
4074                for (int k = 0; k < 8; ++k) {
4075                    if (is_on_grid[k]) continue;
4076                    uint16_t u = 0;
4077                    for (int i = 0; i < 4; ++i) {
4078                        int l = nearest_int(0.5f*(id*xval[4*k+i]-1));
4079                        l = MAX(0, MIN(kMaxQ-1, l));
4080                        u |= (l << 3*i);
4081                    }
4082                    int grid_index = kmap_q3xs[u];
4083                    if (grid_index < 0) {
4084                        const uint16_t * neighbours = kneighbors_q3xs - kmap_q3xs[u] - 1;
4085                        grid_index = iq3_find_best_neighbour(neighbours, kgrid_q3xs, xval + 4*k, waux + 4*k, scale, L + 4*k);
4086                    }
4087                    const int8_t * pg = (const int8_t *)(kgrid_q3xs + grid_index);
4088                    for (int i = 0; i < 4; ++i) L[4*k+i] = (pg[i] - 1)/2;
4089                }
4090                float sumqx = 0, sumq2 = 0;
4091                for (int i = 0; i < 32; ++i) {
4092                    float w = weight[i];
4093                    float q = 2*L[i] + 1;
4094                    sumqx += w*xval[i]*q;
4095                    sumq2 += w*q*q;
4096                }
4097                if (sumq2 > 0) scale = sumqx/sumq2;
4098            }
4099            if (scale < 0) {
4100                // This should never happen, but just in case, flip scale so that it is positive (we use uint's to encode the scale)
4101                // and correspondingly flip quant signs.
4102                scale = -scale;
4103                for (int k = 0; k < 4; ++k) block_signs[k] = (~block_signs[k]) & 127;
4104            }
4105            for (int k = 0; k < 8; ++k) {
4106                uint16_t u = 0;
4107                for (int i = 0; i < 4; ++i) u |= (L[4*k+i] << 3*i);
4108                int grid_index = kmap_q3xs[u];
4109                if (grid_index < 0) {
4110                    printf("Oops: found point %u not on grid:", u);
4111                    for (int i = 0; i < 4; ++i) printf(" %d", L[4*k+i]);
4112                    printf("\n");
4113                    GGML_ABORT("fatal error");
4114                }
4115                if (grid_size == 256) {
4116                    q3[8*ib+k] = grid_index;
4117                } else {
4118                    q3[8*ib+k] = grid_index & 255;
4119                    qh[ib] |= ((grid_index >> 8) << k);
4120                }
4121
4122            }
4123            scales_and_signs[ib] = block_signs[0] | (block_signs[1] << 7) | (block_signs[2] << 14) | (block_signs[3] << 21);
4124            GGML_ASSERT(scale >= 0);
4125            scales[ib] = scale;
4126            max_scale = MAX(max_scale, scale);
4127        }
4128
4129        if (!max_scale) {
4130            memset(qs, 0, quant_size);
4131            dh += block_size/sizeof(ggml_fp16_t);
4132            qs += block_size;
4133            continue;
4134        }
4135
4136        float d = max_scale/31;
4137        dh[0] = GGML_FP32_TO_FP16(d * 1.0125f);  // small improvement via this fudge factor
4138        float id = 1/d;
4139        for (int ib = 0; ib < QK_K/32; ++ib) {
4140            int l = nearest_int(0.5f*(id*scales[ib]-1));
4141            l = MAX(0, MIN(15, l));
4142            scales_and_signs[ib] |= ((uint32_t)l << 28);
4143        }
4144        memcpy(qs, q3, quant_size);
4145
4146        dh += block_size/sizeof(ggml_fp16_t);
4147        qs += block_size;
4148
4149    }
4150}
4151
4152size_t quantize_iq3_xxs(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
4153    GGML_ASSERT(n_per_row%QK_K == 0);
4154    int64_t nblock = n_per_row/QK_K;
4155    char * qrow = (char *)dst;
4156    for (int64_t row = 0; row < nrow; ++row) {
4157        quantize_row_iq3_xxs_impl(256, src, qrow, n_per_row, quant_weights);
4158        src += n_per_row;
4159        qrow += nblock*sizeof(block_iq3_xxs);
4160    }
4161    return nrow * nblock * sizeof(block_iq3_xxs);
4162}
4163
4164void quantize_row_iq3_xxs_ref(const float * GGML_RESTRICT x, block_iq3_xxs * GGML_RESTRICT y, int64_t k) {
4165    assert(k % QK_K == 0);
4166    quantize_row_iq3_xxs_impl(256, x, y, k, NULL);
4167}
4168
4169static void quantize_row_iq3_s_impl(int block_size, const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int n,
4170        const float * GGML_RESTRICT quant_weights,
4171        float   * scales,
4172        float   * weight,
4173        float   * xval,
4174        int8_t  * L,
4175        int8_t  * Laux,
4176        float   * waux,
4177        bool    * is_on_grid,
4178        bool    * is_on_grid_aux,
4179        uint8_t * block_signs) {
4180
4181    const int gindex = iq3_data_index(512);
4182
4183    const uint32_t * kgrid_q3xs      = iq3_data[gindex].grid;
4184    const int      * kmap_q3xs       = iq3_data[gindex].map;
4185    const uint16_t * kneighbors_q3xs = iq3_data[gindex].neighbours;
4186
4187    //GGML_ASSERT(quant_weights   && "missing quantization weights");
4188    GGML_ASSERT(kgrid_q3xs      && "forgot to call ggml_quantize_init()?");
4189    GGML_ASSERT(kmap_q3xs       && "forgot to call ggml_quantize_init()?");
4190    GGML_ASSERT(kneighbors_q3xs && "forgot to call ggml_quantize_init()?");
4191    GGML_ASSERT(n%QK_K == 0);
4192
4193    const int kMaxQ = 8;
4194
4195    const int64_t nbl = n/QK_K;
4196
4197    block_iq3_s * y = vy;
4198
4199    const int bs4 = block_size/4;
4200    const int bs8 = block_size/8;
4201
4202    for (int ibl = 0; ibl < nbl; ++ibl) {
4203
4204        memset(&y[ibl], 0, sizeof(block_iq3_s));
4205        y[ibl].d = GGML_FP32_TO_FP16(0.f);
4206
4207        uint8_t * qs = y[ibl].qs;
4208        uint8_t * qh = y[ibl].qh;
4209        uint8_t * signs = y[ibl].signs;
4210
4211        float max_scale = 0;
4212
4213        const float * xbl = x + QK_K*ibl;
4214        float sumx2 = 0;
4215        for (int i = 0; i < QK_K; ++i) sumx2 += xbl[i]*xbl[i];
4216        float sigma2 = 2*sumx2/QK_K;
4217
4218        for (int ib = 0; ib < QK_K/block_size; ++ib) {
4219            const float * xb = xbl + block_size*ib;
4220            if (quant_weights) {
4221                const float * qw = quant_weights + QK_K*ibl + block_size*ib;
4222                for (int i = 0; i < block_size; ++i) weight[i] = qw[i] * sqrtf(sigma2 + xb[i]*xb[i]);
4223            } else {
4224                for (int i = 0; i < block_size; ++i) weight[i] = xb[i]*xb[i];
4225            }
4226            for (int i = 0; i < block_size; ++i) waux[i] = sqrtf(weight[i]);
4227            for (int k = 0; k < bs8; ++k) {
4228                uint8_t s = 0;
4229                for (int i = 0; i < 8; ++i) {
4230                    if (xb[8*k + i] >= 0) xval[8*k + i] = xb[8*k + i];
4231                    else {
4232                        xval[8*k + i] = -xb[8*k + i]; s |= (1 << i);
4233                    }
4234                }
4235                block_signs[k] = s;
4236            }
4237            float max = xval[0];
4238            for (int i = 1; i < block_size; ++i) max = MAX(max, xval[i]);
4239            memset(L, 0, block_size);
4240            if (!max) {
4241                scales[ib] = 0;
4242                continue;
4243            }
4244            float best = 0;
4245            float scale = max/(2*kMaxQ-1);
4246            for (int k = 0; k < bs4; ++k) is_on_grid[k] = false;
4247            for (int is = -9; is <= 9; ++is) {
4248                float id = (2*kMaxQ-1+is*0.2f)/max;
4249                float this_scale = 1/id;
4250                for (int k = 0; k < bs4; ++k) {
4251                    for (int i = 0; i < 4; ++i) {
4252                        int l = nearest_int(0.5f*(id*xval[4*k+i]-1));
4253                        Laux[4*k+i] = MAX(0, MIN(kMaxQ-1, l));
4254                    }
4255                    uint16_t u = 0;
4256                    for (int i = 0; i < 4; ++i) u |= (Laux[4*k+i] << 3*i);
4257                    int grid_index = kmap_q3xs[u];
4258                    is_on_grid_aux[k] = true;
4259                    if (grid_index < 0) {
4260                        is_on_grid_aux[k] = false;
4261                        const uint16_t * neighbours = kneighbors_q3xs - kmap_q3xs[u] - 1;
4262                        grid_index = iq3_find_best_neighbour(neighbours, kgrid_q3xs, xval + 4*k, waux + 4*k, this_scale, Laux + 4*k);
4263                    }
4264                }
4265                float sumqx = 0, sumq2 = 0;
4266                for (int i = 0; i < block_size; ++i) {
4267                    float w = weight[i];
4268                    float q = 2*Laux[i] + 1;
4269                    sumqx += w*xval[i]*q;
4270                    sumq2 += w*q*q;
4271                }
4272                if (sumq2 > 0 && sumqx*sumqx > best*sumq2) {
4273                    scale = sumqx/sumq2; best = scale*sumqx;
4274                    for (int i = 0; i < block_size; ++i) L[i] = Laux[i];
4275                    for (int k = 0; k < bs4; ++k) is_on_grid[k] = is_on_grid_aux[k];
4276                }
4277            }
4278            int n_not_ongrid = 0;
4279            for (int k = 0; k < bs4; ++k) if (!is_on_grid[k]) ++n_not_ongrid;
4280            if (n_not_ongrid > 0 && scale > 0) {
4281                float id = 1/scale;
4282                for (int k = 0; k < bs4; ++k) {
4283                    //if (is_on_grid[k]) continue;
4284                    uint16_t u = 0;
4285                    for (int i = 0; i < 4; ++i) {
4286                        int l = nearest_int(0.5f*(id*xval[4*k+i]-1));
4287                        l = MAX(0, MIN(kMaxQ-1, l));
4288                        u |= (l << 3*i);
4289                    }
4290                    int grid_index = kmap_q3xs[u];
4291                    if (grid_index < 0) {
4292                        const uint16_t * neighbours = kneighbors_q3xs - kmap_q3xs[u] - 1;
4293                        grid_index = iq3_find_best_neighbour(neighbours, kgrid_q3xs, xval + 4*k, waux + 4*k, scale, L + 4*k);
4294                    }
4295                    const int8_t * pg = (const int8_t *)(kgrid_q3xs + grid_index);
4296                    for (int i = 0; i < 4; ++i) L[4*k+i] = (pg[i] - 1)/2;
4297                }
4298                float sumqx = 0, sumq2 = 0;
4299                for (int i = 0; i < block_size; ++i) {
4300                    float w = weight[i];
4301                    float q = 2*L[i] + 1;
4302                    sumqx += w*xval[i]*q;
4303                    sumq2 += w*q*q;
4304                }
4305                if (sumq2 > 0) scale = sumqx/sumq2;
4306            }
4307            if (scale < 0) {
4308                // This should never happen, but just in case, flip scale so that it is positive (we use uint's to encode the scale)
4309                // and correspondingly flip quant signs.
4310                scale = -scale;
4311                for (int k = 0; k < bs8; ++k) block_signs[k] = ~block_signs[k];
4312            }
4313            for (int k = 0; k < bs4; ++k) {
4314                uint16_t u = 0;
4315                for (int i = 0; i < 4; ++i) u |= (L[4*k+i] << 3*i);
4316                int grid_index = kmap_q3xs[u];
4317                if (grid_index < 0) {
4318                    printf("Oops: found point %u not on grid:", u);
4319                    for (int i = 0; i < 4; ++i) printf(" %d", L[4*k+i]);
4320                    printf("\n");
4321                    GGML_ABORT("fatal error");
4322                }
4323                qs[k] = grid_index & 255;
4324                qh[(ib*bs4+k)/8] |= ((grid_index >> 8) << ((ib*bs4+k)%8));
4325            }
4326            qs += bs4;
4327            for (int k = 0; k < bs8; ++k) signs[k] = block_signs[k];
4328            signs += bs8;
4329            GGML_ASSERT(scale >= 0);
4330            scales[ib] = scale;
4331            max_scale = MAX(max_scale, scale);
4332        }
4333
4334        if (!max_scale) {
4335            continue;
4336        }
4337
4338        float d = max_scale/31;
4339        y[ibl].d = GGML_FP32_TO_FP16(d * 1.033f);
4340        float id = 1/d;
4341        for (int ib = 0; ib < QK_K/block_size; ib += 2) {
4342            int l1 = nearest_int(0.5f*(id*scales[ib+0]-1));
4343            l1 = MAX(0, MIN(15, l1));
4344            int l2 = nearest_int(0.5f*(id*scales[ib+1]-1));
4345            l2 = MAX(0, MIN(15, l2));
4346            y[ibl].scales[ib/2] = l1 | (l2 << 4);
4347        }
4348
4349    }
4350}
4351
4352#define IQ3S_BLOCK_SIZE 32
4353size_t quantize_iq3_s(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
4354    GGML_ASSERT(n_per_row%QK_K == 0);
4355    int64_t nblock = n_per_row/QK_K;
4356    float scales[QK_K/IQ3S_BLOCK_SIZE];
4357    float weight[IQ3S_BLOCK_SIZE];
4358    float xval[IQ3S_BLOCK_SIZE];
4359    int8_t L[IQ3S_BLOCK_SIZE];
4360    int8_t Laux[IQ3S_BLOCK_SIZE];
4361    float  waux[IQ3S_BLOCK_SIZE];
4362    bool   is_on_grid[IQ3S_BLOCK_SIZE/4];
4363    bool   is_on_grid_aux[IQ3S_BLOCK_SIZE/4];
4364    uint8_t block_signs[IQ3S_BLOCK_SIZE/8];
4365    char * qrow = (char *)dst;
4366    for (int64_t row = 0; row < nrow; ++row) {
4367        quantize_row_iq3_s_impl(IQ3S_BLOCK_SIZE, src, qrow, n_per_row, quant_weights,
4368                scales, weight, xval, L, Laux, waux, is_on_grid, is_on_grid_aux, block_signs);
4369        src += n_per_row;
4370        qrow += nblock*sizeof(block_iq3_s);
4371    }
4372    return nrow * nblock * sizeof(block_iq3_s);
4373}
4374
4375void quantize_row_iq3_s_ref(const float * GGML_RESTRICT x, block_iq3_s * GGML_RESTRICT y, int64_t k) {
4376    assert(k % QK_K == 0);
4377    quantize_iq3_s(x, y, 1, k, NULL);
4378}
4379
4380
4381// =================================== 1.5 bpw ===================================================
4382
4383static int iq1_find_best_neighbour(const uint16_t * GGML_RESTRICT neighbours, const uint64_t * GGML_RESTRICT grid,
4384        const float * GGML_RESTRICT xval, const float * GGML_RESTRICT weight, float * scale, int8_t * GGML_RESTRICT L, int ngrid) {
4385    int num_neighbors = neighbours[0];
4386    GGML_ASSERT(num_neighbors > 0);
4387    float best_score = -FLT_MAX;
4388    int grid_index = -1;
4389    for (int j = 1; j <= num_neighbors; ++j) {
4390        const int8_t * pg = (const int8_t *)(grid + neighbours[j]);
4391        float sumqx = 0, sumq2 = 0;
4392        for (int i = 0; i < 8; ++i) {
4393            float q = (pg[i] - 3)/2;
4394            float w = weight[i];
4395            sumqx += w*q*xval[i];
4396            sumq2 += w*q*q;
4397        }
4398        if (sumqx > 0 && sumq2 > 0 && sumqx*sumqx > best_score*sumq2) {
4399            *scale = sumqx/sumq2; best_score = *scale * sumqx;
4400            grid_index = neighbours[j];
4401        }
4402    }
4403    if (grid_index < 0) {
4404        for (int i = 0; i < ngrid; ++i) {
4405            const int8_t * grid_i = (const int8_t *)(grid + i);
4406            float sumqx = 0, sumq2 = 0;
4407            for (int j = 0; j < 8; ++j) {
4408                float w = weight[j];
4409                float q = (grid_i[j] - 3)/2;
4410                sumqx += w*q*xval[j];
4411                sumq2 += w*q*q;
4412            }
4413            if (sumqx > 0 && sumq2 > 0 && sumqx*sumqx > best_score*sumq2) {
4414                *scale = sumqx/sumq2; best_score = *scale*sumqx;
4415                grid_index = i;
4416            }
4417        }
4418    }
4419    if (grid_index < 0) {
4420        printf("Oops, did not find grid point\n");
4421        printf("Have %d neighbours\n", num_neighbors);
4422        for (int j = 1; j <= num_neighbors; ++j) {
4423            const int8_t * pg = (const int8_t *)(grid + neighbours[j]);
4424            float sumqx = 0, sumq2 = 0;
4425            for (int i = 0; i < 8; ++i) {
4426                float q = (pg[i] - 3)/2;
4427                float w = weight[i];
4428                sumqx += w*q*xval[i];
4429                sumq2 += w*q*q;
4430            }
4431            printf("    neighbour %d: sumqx = %g sumq2 = %g\n", j, (double)sumqx, (double)sumq2);
4432        }
4433    }
4434    GGML_ASSERT(grid_index >= 0);
4435    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
4436    *scale *= 1.05f;  // This is a fudge factor. Don't ask me why it improves the result.
4437    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
4438    const int8_t * pg = (const int8_t *)(grid + grid_index);
4439    for (int i = 0; i < 8; ++i) L[i] = (pg[i] - 1)/2;
4440    return grid_index;
4441}
4442
4443static int iq1_find_best_neighbour2(const uint16_t * GGML_RESTRICT neighbours, const uint64_t * GGML_RESTRICT grid,
4444        const float * GGML_RESTRICT xval, const float * GGML_RESTRICT weight, float scale, const float * GGML_RESTRICT xg, int8_t * GGML_RESTRICT L, int ngrid) {
4445    int num_neighbors = neighbours[0];
4446    GGML_ASSERT(num_neighbors > 0);
4447    float best_score = FLT_MAX;
4448    int grid_index = -1;
4449    for (int j = 1; j <= num_neighbors; ++j) {
4450        const int8_t * pg = (const int8_t *)(grid + neighbours[j]);
4451        float d2 = 0;
4452        for (int i = 0; i < 8; ++i) {
4453            float q = xg[(pg[i] - 1)/2];
4454            float w = weight[i];
4455            float diff = scale*q - xval[i];
4456            d2 += w*diff*diff;
4457        }
4458        if (d2 < best_score) {
4459            best_score = d2;
4460            grid_index = neighbours[j];
4461        }
4462    }
4463    if (grid_index < 0) {
4464        for (int i = 0; i < ngrid; ++i) {
4465            const int8_t * grid_i = (const int8_t *)(grid + i);
4466            float d2 = 0;
4467            for (int j = 0; j < 8; ++j) {
4468                float w = weight[j];
4469                float q = xg[(grid_i[j] - 1)/2];
4470                float diff = scale*q - xval[i];
4471                d2 += w*diff*diff;
4472            }
4473            if (d2 < best_score) {
4474                best_score = d2;
4475                grid_index = i;
4476            }
4477        }
4478    }
4479    if (grid_index < 0) {
4480        printf("Oops, did not find grid point\n");
4481        printf("Have %d neighbours\n", num_neighbors);
4482        for (int j = 1; j <= num_neighbors; ++j) {
4483            const int8_t * pg = (const int8_t *)(grid + neighbours[j]);
4484            float sumqx = 0, sumq2 = 0;
4485            for (int i = 0; i < 8; ++i) {
4486                float q = xg[(pg[i] - 1)/2];
4487                float w = weight[i];
4488                sumqx += w*q*xval[i];
4489                sumq2 += w*q*q;
4490            }
4491            printf("    neighbour %d: sumqx = %g sumq2 = %g\n", j, (double)sumqx, (double)sumq2);
4492        }
4493    }
4494    GGML_ASSERT(grid_index >= 0);
4495    const int8_t * pg = (const int8_t *)(grid + grid_index);
4496    for (int i = 0; i < 8; ++i) L[i] = (pg[i] - 1)/2;
4497    return grid_index;
4498}
4499
4500static int iq1_sort_helper(const void * left, const void * right) {
4501    const float * l = left;
4502    const float * r = right;
4503    return *l < *r ? -1 : *l > *r ? 1 : 0;
4504}
4505
4506#define IQ1S_BLOCK_SIZE 32
4507#define IQ1M_BLOCK_SIZE 16
4508static void quantize_row_iq1_s_impl(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t n, const float * GGML_RESTRICT quant_weights,
4509        float    * scales,
4510        float    * weight,
4511        float    * sumx,
4512        float    * sumw,
4513        float    * pairs,
4514        int8_t   * L,
4515        uint16_t * index,
4516        int8_t   * shifts) {
4517
4518    const int gindex = iq2_data_index(GGML_TYPE_IQ1_S);
4519
4520    const uint64_t * kgrid_q2xs      = iq2_data[gindex].grid;
4521    const int      * kmap_q2xs       = iq2_data[gindex].map;
4522    const uint16_t * kneighbors_q2xs = iq2_data[gindex].neighbours;
4523
4524    GGML_ASSERT(quant_weights   && "missing quantization weights");
4525    GGML_ASSERT(kgrid_q2xs      && "forgot to call ggml_quantize_init()?");
4526    GGML_ASSERT(kmap_q2xs       && "forgot to call ggml_quantize_init()?");
4527    GGML_ASSERT(kneighbors_q2xs && "forgot to call ggml_quantize_init()?");
4528    GGML_ASSERT(n%QK_K == 0);
4529
4530    block_iq1_s * y = vy;
4531
4532    const int64_t nbl = n/QK_K;
4533
4534    const int block_size = IQ1S_BLOCK_SIZE;
4535
4536    const float x_p[3] = {-1 + IQ1S_DELTA,  IQ1S_DELTA, 1 + IQ1S_DELTA};
4537    const float x_m[3] = {-1 - IQ1S_DELTA, -IQ1S_DELTA, 1 - IQ1S_DELTA};
4538
4539
4540    int * idx = (int *)(pairs + 1);
4541
4542    for (int ibl = 0; ibl < nbl; ++ibl) {
4543
4544        y[ibl].d = GGML_FP32_TO_FP16(0.f);
4545        memset(y[ibl].qs, 0, QK_K/8);
4546        memset(y[ibl].qh, 0, QK_K/16);
4547
4548        float max_scale = 0;
4549
4550        const float * xbl = x + QK_K*ibl;
4551        float sumx2 = 0;
4552        for (int i = 0; i < QK_K; ++i) sumx2 += xbl[i]*xbl[i];
4553        float sigma2 = 2*sumx2/QK_K;
4554
4555        for (int ib = 0; ib < QK_K/block_size; ++ib) {
4556            const float * xb = xbl + block_size*ib;
4557            const float * qw = quant_weights + QK_K*ibl + block_size*ib;
4558            for (int i = 0; i < block_size; ++i) weight[i] = qw[i] * sqrtf(sigma2 + xb[i]*xb[i]);
4559            float max = fabsf(xb[0]);
4560            for (int i = 1; i < block_size; ++i) max = MAX(max, fabsf(xb[i]));
4561            if (max < GROUP_MAX_EPS_IQ1_S) {
4562                scales[ib] = 0;
4563                shifts[ib] = 1;
4564                memset(L, 1, block_size);
4565                continue;
4566            }
4567            // Here we solve exactly the sum of squared difference (SSD) weighted minimization problem.
4568            // With just 3 allowed quant values (-1, 0, 1), we can search exhaustively for the two
4569            // boundaries that split the weights xb[i] into 3 groups. To do so, we sort the weights
4570            // in ascending order, compute Si = sum[weight[j] xb[j], j = 0...i] and
4571            // Wi = sum[weight[j], j = 0...i], and use these to quckly get get the optimum scale
4572            // for each possible and score for each split.
4573            for (int j = 0; j < block_size; ++j) {
4574                pairs[2*j] = xb[j];
4575                idx[2*j] = j;
4576            }
4577            qsort(pairs, block_size, 2*sizeof(float), iq1_sort_helper);
4578            {
4579                sumx[0] = sumw[0] = 0;
4580                for (int j = 0; j < block_size; ++j) {
4581                    int i = idx[2*j];
4582                    sumx[j+1] = sumx[j] + weight[i]*xb[i];
4583                    sumw[j+1] = sumw[j] + weight[i];
4584                }
4585            }
4586            float best_score = -FLT_MAX, scale = max;
4587            int besti1 = -1, besti2 = -1, best_shift = 0;
4588            for (int i1 = 0; i1 <= block_size; ++i1) {
4589                for (int i2 = i1; i2 <= block_size; ++i2) {
4590                    float sumqx = (sumx[i1] - sumx[0])*x_p[0] + (sumx[i2] - sumx[i1])*x_p[1] + (sumx[block_size] - sumx[i2])*x_p[2];
4591                    float sumq2 = (sumw[i1] - sumw[0])*x_p[0]*x_p[0] + (sumw[i2] - sumw[i1])*x_p[1]*x_p[1] + (sumw[block_size] - sumw[i2])*x_p[2]*x_p[2];
4592                    if (sumq2 > 0 && sumqx*sumqx > best_score*sumq2) {
4593                        scale = sumqx/sumq2; best_score = scale*sumqx;
4594                        besti1 = i1; besti2 = i2; best_shift = 1;
4595                    }
4596                    sumqx = (sumx[i1] - sumx[0])*x_m[0] + (sumx[i2] - sumx[i1])*x_m[1] + (sumx[block_size] - sumx[i2])*x_m[2];
4597                    sumq2 = (sumw[i1] - sumw[0])*x_m[0]*x_m[0] + (sumw[i2] - sumw[i1])*x_m[1]*x_m[1] + (sumw[block_size] - sumw[i2])*x_m[2]*x_m[2];
4598                    if (sumq2 > 0 && sumqx*sumqx > best_score*sumq2) {
4599                        scale = sumqx/sumq2; best_score = scale*sumqx;
4600                        besti1 = i1; besti2 = i2; best_shift = -1;
4601                    }
4602                }
4603            }
4604            if (besti1 < 0 || besti2 < 0 || best_shift == 0) {
4605                scales[ib] = 0;
4606                shifts[ib] = 1;
4607                memset(L, 1, block_size);
4608                continue;
4609            }
4610            for (int j =      0; j < besti1; ++j) L[idx[2*j]] = 0;
4611            for (int j = besti1; j < besti2; ++j) L[idx[2*j]] = 1;
4612            for (int j = besti2; j < block_size; ++j) L[idx[2*j]] = 2;
4613            if (scale < 0) {
4614                for (int j = 0; j < block_size; ++j) L[j] = 2 - L[j];
4615                scale = -scale; best_shift = -best_shift;
4616            }
4617            bool all_on_grid = true;
4618            const float * xx = best_shift == 1 ? x_p : x_m;
4619            for (int k = 0; k < block_size/8; ++k) {
4620                uint16_t u = 0;
4621                for (int j = 0; j < 8; ++j) u |= (L[8*k+j] << 2*j);
4622                int grid_index = kmap_q2xs[u];
4623                if (grid_index < 0) {
4624                    all_on_grid = false;
4625                    const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1;
4626                    grid_index = iq1_find_best_neighbour2(neighbours, kgrid_q2xs, xb + 8*k, weight + 8*k, scale, xx, L + 8*k, NGRID_IQ1S);
4627                    GGML_ASSERT(grid_index >= 0);
4628                }
4629                index[k] = grid_index;
4630            }
4631            if (!all_on_grid) {
4632                float sumqx = 0, sumq2 = 0;
4633                for (int k = 0; k < block_size/8; ++k) {
4634                    const int8_t * pg = (const int8_t *)(kgrid_q2xs + index[k]);
4635                    for (int j = 0; j < 8; ++j) {
4636                        float w = weight[8*k + j];
4637                        float q = xx[(pg[j] - 1)/2];
4638                        sumqx += w*q*xb[8*k+j];
4639                        sumq2 += w*q*q;
4640                    }
4641                }
4642                if (sumqx > 0 && sumq2 > 0) scale = sumqx/sumq2;
4643            }
4644            uint16_t h = 0;
4645            for (int k = 0; k < block_size/8; ++k) {
4646                y[ibl].qs[(block_size/8)*ib + k] = index[k] & 255;
4647                h |= (index[k] >> 8) << 3*k;
4648            }
4649            y[ibl].qh[ib] = h;
4650            GGML_ASSERT(scale >= 0);
4651            scales[ib] = scale;
4652            shifts[ib] = best_shift;
4653            max_scale = MAX(max_scale, scale);
4654        }
4655
4656        if (!max_scale) {
4657            continue;
4658        }
4659
4660        float d = max_scale/15;
4661        y[ibl].d = GGML_FP32_TO_FP16(d*1.125f); // 1.125f is another fudge factor. Don't ask me why it is needed.
4662        float id = 1/d;
4663        for (int ib = 0; ib < QK_K/block_size; ++ib) {
4664            int l = nearest_int(0.5f*(id*scales[ib]-1));
4665            l = MAX(0, MIN(7, l));
4666            if (shifts[ib] == -1) l |= 8;
4667            y[ibl].qh[ib] |= (l << 12);
4668        }
4669    }
4670}
4671
4672size_t quantize_iq1_s(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
4673    GGML_ASSERT(n_per_row%QK_K == 0);
4674    float  scales[QK_K/IQ1S_BLOCK_SIZE];
4675    float  weight[IQ1S_BLOCK_SIZE];
4676    int8_t L[IQ1S_BLOCK_SIZE];
4677    float  sumx[IQ1S_BLOCK_SIZE+1];
4678    float  sumw[IQ1S_BLOCK_SIZE+1];
4679    float  pairs[2*IQ1S_BLOCK_SIZE];
4680    uint16_t index[IQ1S_BLOCK_SIZE/8];
4681    int8_t shifts[QK_K/IQ1S_BLOCK_SIZE];
4682    int64_t nblock = n_per_row/QK_K;
4683    char * qrow = (char *)dst;
4684    for (int64_t row = 0; row < nrow; ++row) {
4685        quantize_row_iq1_s_impl(src, qrow, n_per_row, quant_weights, scales, weight, sumx, sumw, pairs, L, index, shifts);
4686        src += n_per_row;
4687        qrow += nblock*sizeof(block_iq1_s);
4688    }
4689    return nrow * nblock * sizeof(block_iq1_s);
4690}
4691
4692static void quantize_row_iq1_m_impl(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t n, const float * GGML_RESTRICT quant_weights,
4693        float    * scales,
4694        float    * weight,
4695        float    * pairs,
4696        int8_t   * L,
4697        uint16_t * index,
4698        int8_t   * shifts) {
4699
4700    const int gindex = iq2_data_index(GGML_TYPE_IQ1_M);
4701
4702    const uint64_t * kgrid_q2xs      = iq2_data[gindex].grid;
4703    const int      * kmap_q2xs       = iq2_data[gindex].map;
4704    const uint16_t * kneighbors_q2xs = iq2_data[gindex].neighbours;
4705
4706    //GGML_ASSERT(quant_weights   && "missing quantization weights");
4707    GGML_ASSERT(kgrid_q2xs      && "forgot to call ggml_quantize_init()?");
4708    GGML_ASSERT(kmap_q2xs       && "forgot to call ggml_quantize_init()?");
4709    GGML_ASSERT(kneighbors_q2xs && "forgot to call ggml_quantize_init()?");
4710    GGML_ASSERT(n%QK_K == 0);
4711
4712    block_iq1_m * y = vy;
4713
4714    const int64_t nbl = n/QK_K;
4715
4716    const int block_size = IQ1M_BLOCK_SIZE;
4717
4718    const float x_p[3] = {-1 + IQ1M_DELTA,  IQ1M_DELTA, 1 + IQ1M_DELTA};
4719    const float x_m[3] = {-1 - IQ1M_DELTA, -IQ1M_DELTA, 1 - IQ1M_DELTA};
4720    const uint8_t masks[4] = {0x00, 0x80, 0x08, 0x88};
4721
4722    int * idx = (int *)(pairs + 1);
4723
4724    float sumqx[4], sumq2[4];
4725
4726    iq1m_scale_t s;
4727    const float * xx;
4728
4729    for (int ibl = 0; ibl < nbl; ++ibl) {
4730        memset(y[ibl].qs, 0, QK_K/8);
4731        memset(y[ibl].qh, 0, QK_K/16);
4732        memset(y[ibl].scales, 0, QK_K/32);
4733
4734        float max_scale = 0;
4735
4736        const float * xbl = x + QK_K*ibl;
4737        float sumx2 = 0;
4738        for (int i = 0; i < QK_K; ++i) sumx2 += xbl[i]*xbl[i];
4739        float sigma2 = 2*sumx2/QK_K;
4740
4741        for (int ib = 0; ib < QK_K/block_size; ++ib) {
4742            const float * xb = xbl + block_size*ib;
4743            if (quant_weights) {
4744                const float * qw = quant_weights + QK_K*ibl + block_size*ib;
4745                for (int i = 0; i < block_size; ++i) weight[i] = qw[i] * sqrtf(sigma2 + xb[i]*xb[i]);
4746            } else {
4747                for (int i = 0; i < block_size; ++i) weight[i] = xb[i]*xb[i];
4748            }
4749            float max = fabsf(xb[0]);
4750            for (int i = 1; i < block_size; ++i) max = MAX(max, fabsf(xb[i]));
4751            if (max < GROUP_MAX_EPS_IQ1_M) {
4752                scales[ib] = 0;
4753                shifts[ib] = 0;
4754                memset(L, 1, block_size);
4755                continue;
4756            }
4757            // Here we solve exactly the sum of squared difference (SSD) weighted minimization problem.
4758            // With just 3 allowed quant values (-1, 0, 1), we can search exhaustively for the two
4759            // boundaries that split the weights xb[i] into 3 groups. To do so, we sort the weights
4760            // in ascending order, compute Si = sum[weight[j] xb[j], j = 0...i] and
4761            // Wi = sum[weight[j], j = 0...i], and use these to quckly get get the optimum scale
4762            // for each possible and score for each split.
4763            for (int j = 0; j < block_size; ++j) {
4764                pairs[2*j] = xb[j];
4765                idx[2*j] = j;
4766            }
4767            qsort(pairs, block_size, 2*sizeof(float), iq1_sort_helper);
4768            float best_score = -FLT_MAX, scale = max;
4769            int besti1 = -1, besti2 = -1, best_k = -1;
4770            // 0: +, +
4771            // 1: +, -
4772            // 2: -, +
4773            // 3: -, -
4774            for (int i1 = 0; i1 <= block_size; ++i1) {
4775                for (int i2 = i1; i2 <= block_size; ++i2) {
4776                    memset(sumqx, 0, 4*sizeof(float));
4777                    memset(sumq2, 0, 4*sizeof(float));
4778                    for (int j = 0; j < i1; ++j) {
4779                        int i = idx[2*j];
4780                        if (i < block_size/2) {
4781                            sumqx[0] += weight[i]*x_p[0]*xb[i];
4782                            sumqx[1] += weight[i]*x_p[0]*xb[i];
4783                            sumqx[2] += weight[i]*x_m[0]*xb[i];
4784                            sumqx[3] += weight[i]*x_m[0]*xb[i];
4785                            sumq2[0] += weight[i]*x_p[0]*x_p[0];
4786                            sumq2[1] += weight[i]*x_p[0]*x_p[0];
4787                            sumq2[2] += weight[i]*x_m[0]*x_m[0];
4788                            sumq2[3] += weight[i]*x_m[0]*x_m[0];
4789                        } else {
4790                            sumqx[0] += weight[i]*x_p[0]*xb[i];
4791                            sumqx[2] += weight[i]*x_p[0]*xb[i];
4792                            sumqx[1] += weight[i]*x_m[0]*xb[i];
4793                            sumqx[3] += weight[i]*x_m[0]*xb[i];
4794                            sumq2[0] += weight[i]*x_p[0]*x_p[0];
4795                            sumq2[2] += weight[i]*x_p[0]*x_p[0];
4796                            sumq2[1] += weight[i]*x_m[0]*x_m[0];
4797                            sumq2[3] += weight[i]*x_m[0]*x_m[0];
4798                        }
4799                    }
4800                    for (int j = i1; j < i2; ++j) {
4801                        int i = idx[2*j];
4802                        if (i < block_size/2) {
4803                            sumqx[0] += weight[i]*x_p[1]*xb[i];
4804                            sumqx[1] += weight[i]*x_p[1]*xb[i];
4805                            sumqx[2] += weight[i]*x_m[1]*xb[i];
4806                            sumqx[3] += weight[i]*x_m[1]*xb[i];
4807                            sumq2[0] += weight[i]*x_p[1]*x_p[1];
4808                            sumq2[1] += weight[i]*x_p[1]*x_p[1];
4809                            sumq2[2] += weight[i]*x_m[1]*x_m[1];
4810                            sumq2[3] += weight[i]*x_m[1]*x_m[1];
4811                        } else {
4812                            sumqx[0] += weight[i]*x_p[1]*xb[i];
4813                            sumqx[2] += weight[i]*x_p[1]*xb[i];
4814                            sumqx[1] += weight[i]*x_m[1]*xb[i];
4815                            sumqx[3] += weight[i]*x_m[1]*xb[i];
4816                            sumq2[0] += weight[i]*x_p[1]*x_p[1];
4817                            sumq2[2] += weight[i]*x_p[1]*x_p[1];
4818                            sumq2[1] += weight[i]*x_m[1]*x_m[1];
4819                            sumq2[3] += weight[i]*x_m[1]*x_m[1];
4820                        }
4821                    }
4822                    for (int j = i2; j < block_size; ++j) {
4823                        int i = idx[2*j];
4824                        if (i < block_size/2) {
4825                            sumqx[0] += weight[i]*x_p[2]*xb[i];
4826                            sumqx[1] += weight[i]*x_p[2]*xb[i];
4827                            sumqx[2] += weight[i]*x_m[2]*xb[i];
4828                            sumqx[3] += weight[i]*x_m[2]*xb[i];
4829                            sumq2[0] += weight[i]*x_p[2]*x_p[2];
4830                            sumq2[1] += weight[i]*x_p[2]*x_p[2];
4831                            sumq2[2] += weight[i]*x_m[2]*x_m[2];
4832                            sumq2[3] += weight[i]*x_m[2]*x_m[2];
4833                        } else {
4834                            sumqx[0] += weight[i]*x_p[2]*xb[i];
4835                            sumqx[2] += weight[i]*x_p[2]*xb[i];
4836                            sumqx[1] += weight[i]*x_m[2]*xb[i];
4837                            sumqx[3] += weight[i]*x_m[2]*xb[i];
4838                            sumq2[0] += weight[i]*x_p[2]*x_p[2];
4839                            sumq2[2] += weight[i]*x_p[2]*x_p[2];
4840                            sumq2[1] += weight[i]*x_m[2]*x_m[2];
4841                            sumq2[3] += weight[i]*x_m[2]*x_m[2];
4842                        }
4843                    }
4844                    for (int k = 0; k < 4; ++k) {
4845                        if (sumq2[k] > 0 && sumqx[k]*sumqx[k] > best_score*sumq2[k]) {
4846                            scale = sumqx[k]/sumq2[k]; best_score = scale*sumqx[k];
4847                            besti1 = i1; besti2 = i2; best_k = k;
4848                        }
4849                    }
4850                }
4851            }
4852            if (besti1 < 0 || besti2 < 0 || best_k < 0) {
4853                scales[ib] = 0;
4854                shifts[ib] = 0;
4855                memset(L, 1, block_size);
4856                continue;
4857            }
4858            for (int j =      0; j < besti1; ++j) L[idx[2*j]] = 0;
4859            for (int j = besti1; j < besti2; ++j) L[idx[2*j]] = 1;
4860            for (int j = besti2; j < block_size; ++j) L[idx[2*j]] = 2;
4861            if (scale < 0) {
4862                for (int j = 0; j < block_size; ++j) L[j] = 2 - L[j];
4863                scale = -scale;
4864                best_k = best_k == 0 ? 3 : best_k == 1 ? 2 : best_k == 2 ? 1 : 0;
4865            }
4866            bool all_on_grid = true;
4867            for (int k = 0; k < block_size/8; ++k) {
4868                if (k == 0) xx = best_k < 2 ? x_p : x_m;
4869                else xx = best_k%2 == 0 ? x_p : x_m;
4870                uint16_t u = 0;
4871                for (int j = 0; j < 8; ++j) u |= (L[8*k+j] << 2*j);
4872                int grid_index = kmap_q2xs[u];
4873                if (grid_index < 0) {
4874                    all_on_grid = false;
4875                    const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1;
4876                    grid_index = iq1_find_best_neighbour2(neighbours, kgrid_q2xs, xb + 8*k, weight + 8*k, scale, xx, L + 8*k, NGRID_IQ1S);
4877                    GGML_ASSERT(grid_index >= 0);
4878                }
4879                index[k] = grid_index;
4880            }
4881            if (!all_on_grid) {
4882                float sumqx_f = 0, sumq2_f = 0;
4883                for (int k = 0; k < block_size/8; ++k) {
4884                    if (k == 0) xx = best_k < 2 ? x_p : x_m;
4885                    else xx = best_k%2 == 0 ? x_p : x_m;
4886                    const int8_t * pg = (const int8_t *)(kgrid_q2xs + index[k]);
4887                    for (int j = 0; j < 8; ++j) {
4888                        float w = weight[8*k + j];
4889                        float q = xx[(pg[j] - 1)/2];
4890                        sumqx_f += w*q*xb[8*k+j];
4891                        sumq2_f += w*q*q;
4892                    }
4893                }
4894                if (sumqx_f > 0 && sumq2_f > 0) scale = sumqx_f/sumq2_f;
4895            }
4896            y[ibl].qs[2*ib + 0] = index[0] & 255;
4897            y[ibl].qs[2*ib + 1] = index[1] & 255;
4898            y[ibl].qh[ib] = (index[0] >> 8) | ((index[1] >> 8) << 4);
4899            GGML_ASSERT(scale >= 0);
4900            scales[ib] = scale;
4901            shifts[ib] = best_k;
4902            max_scale = MAX(max_scale, scale);
4903        }
4904
4905        if (!max_scale) {
4906            continue;
4907        }
4908
4909        uint16_t * sc = (uint16_t *)y[ibl].scales;
4910        float d = max_scale/15;
4911        float id = 1/d;
4912        float sumqx_f = 0, sumq2_f = 0;
4913        for (int ib = 0; ib < QK_K/block_size; ++ib) {
4914            int l = nearest_int(0.5f*(id*scales[ib+0]-1));
4915            l = MAX(0, MIN(7, l));
4916            sc[ib/4] |= (l << 3*(ib%4));
4917            y[ibl].qh[ib] |= masks[shifts[ib]];
4918            const float * xb = xbl + block_size*ib;
4919            if (quant_weights) {
4920                const float * qw = quant_weights + QK_K*ibl + block_size*ib;
4921                for (int i = 0; i < block_size; ++i) weight[i] = qw[i] * sqrtf(sigma2 + xb[i]*xb[i]);
4922            } else {
4923                for (int i = 0; i < block_size; ++i) weight[i] = xb[i]*xb[i];
4924            }
4925            for (int k = 0; k < block_size/8; ++k) {
4926                if (k == 0) xx = shifts[ib] < 2 ? x_p : x_m;
4927                else xx = shifts[ib]%2 == 0 ? x_p : x_m;
4928                const int8_t * pg = (const int8_t *)(kgrid_q2xs + y[ibl].qs[2*ib+k] + ((y[ibl].qh[ib] << (8 - 4*k)) & 0x700));
4929                for (int j = 0; j < 8; ++j) {
4930                    float w = weight[8*k + j];
4931                    float q = xx[(pg[j] - 1)/2]*(2*l+1);
4932                    sumqx_f += w*q*xb[8*k+j];
4933                    sumq2_f += w*q*q;
4934                }
4935            }
4936        }
4937        if (sumq2_f > 0) d = sumqx_f/sumq2_f;
4938        s.f16 = GGML_FP32_TO_FP16(d*1.1125f); // 1.1125f is another fudge factor. Don't ask me why it is needed.
4939        sc[0] |= ((s.u16 & 0x000f) << 12);
4940        sc[1] |= ((s.u16 & 0x00f0) <<  8);
4941        sc[2] |= ((s.u16 & 0x0f00) <<  4);
4942        sc[3] |= ((s.u16 & 0xf000) <<  0);
4943    }
4944}
4945
4946size_t quantize_iq1_m(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
4947    GGML_ASSERT(n_per_row%QK_K == 0);
4948    float  scales[QK_K/IQ1M_BLOCK_SIZE];
4949    float  weight[IQ1M_BLOCK_SIZE];
4950    int8_t L[IQ1M_BLOCK_SIZE];
4951    float  pairs[2*IQ1M_BLOCK_SIZE];
4952    uint16_t index[IQ1M_BLOCK_SIZE/8];
4953    int8_t shifts[QK_K/IQ1M_BLOCK_SIZE];
4954    int64_t nblock = n_per_row/QK_K;
4955    char * qrow = (char *)dst;
4956    for (int64_t row = 0; row < nrow; ++row) {
4957        quantize_row_iq1_m_impl(src, qrow, n_per_row, quant_weights, scales, weight, pairs, L, index, shifts);
4958        src += n_per_row;
4959        qrow += nblock*sizeof(block_iq1_m);
4960    }
4961    return nrow * nblock * sizeof(block_iq1_m);
4962}
4963
4964// ============================ 4-bit non-linear quants
4965
4966static void quantize_row_iq4_nl_impl(const int super_block_size, const int block_size, const float * GGML_RESTRICT x,
4967        ggml_fp16_t * dh, uint8_t * q4, uint16_t * scales_h, uint8_t * scales_l,
4968        float * scales, float * weight, uint8_t * L,
4969        const int8_t * values,
4970        const float * quant_weights,
4971        const int ntry) {
4972
4973    float sigma2 = 0;
4974    for (int j = 0; j < super_block_size; ++j) sigma2 += x[j]*x[j];
4975    sigma2 *= 2.f/super_block_size;
4976
4977    memset(q4, 0, super_block_size/2);
4978    dh[0] = GGML_FP32_TO_FP16(0.f);
4979
4980    float max_scale = 0, amax_scale = 0;
4981    for (int ib = 0; ib < super_block_size/block_size; ++ib) {
4982        const float * xb = x + ib*block_size;
4983        uint8_t * Lb = L + ib*block_size;
4984        if (quant_weights) {
4985            const float * qw = quant_weights + ib*block_size;
4986            for (int j = 0; j < block_size; ++j) weight[j] = qw[j] * sqrtf(sigma2 + xb[j]*xb[j]);
4987        } else {
4988            for (int j = 0; j < block_size; ++j) weight[j] = xb[j]*xb[j];
4989        }
4990        float amax = 0, max = 0;
4991        for (int j = 0; j < block_size; ++j) {
4992            float ax = fabsf(xb[j]);
4993            if (ax > amax) {
4994                amax = ax; max = xb[j];
4995            }
4996        }
4997        if (amax < GROUP_MAX_EPS) {
4998            scales[ib] = 0;
4999            continue;
5000        }
5001        float d = ntry > 0 ? -max/values[0] : max/values[0];
5002        float id = 1/d;
5003        float sumqx = 0, sumq2 = 0;
5004        for (int j = 0; j < block_size; ++j) {
5005            float al = id*xb[j];
5006            int l = best_index_int8(16, values, al);
5007            Lb[j] = l;
5008            float q = values[l];
5009            float w = weight[j];
5010            sumqx += w*q*xb[j];
5011            sumq2 += w*q*q;
5012        }
5013        d = sumq2 > 0 ? sumqx/sumq2 : 0.f;
5014        float best = d*sumqx;
5015        for (int itry = -ntry; itry <= ntry; ++itry) {
5016            id = (itry + values[0])/max;
5017            sumqx = sumq2 = 0;
5018            for (int j = 0; j < block_size; ++j) {
5019                float al = id*xb[j];
5020                int l = best_index_int8(16, values, al);
5021                float q = values[l];
5022                float w = weight[j];
5023                sumqx += w*q*xb[j];
5024                sumq2 += w*q*q;
5025            }
5026            if (sumq2 > 0 && sumqx*sumqx > best*sumq2) {
5027                d = sumqx/sumq2; best = d * sumqx;
5028            }
5029        }
5030        scales[ib] = d;
5031        float abs_d = fabsf(d);
5032        if (abs_d > amax_scale) {
5033            amax_scale = abs_d; max_scale = d;
5034        }
5035    }
5036
5037    if (super_block_size/block_size > 1) {
5038        int nb = super_block_size/block_size;
5039        memset(scales_h, 0, ((nb+7)/8)*sizeof(uint16_t));
5040        float d = -max_scale/32;
5041        dh[0] = GGML_FP32_TO_FP16(d);
5042        float id = d ? 1/d : 0.f;
5043        for (int ib = 0; ib < super_block_size/block_size; ++ib) {
5044            int l = nearest_int(id*scales[ib]);
5045            l = MAX(-32, MIN(31, l));
5046            float dl = d * l;
5047            float idl = dl ? 1/dl : 0.f;
5048            uint8_t * Lb = L + ib*block_size;
5049            const float * xb = x + ib*block_size;
5050            for (int j = 0; j < block_size; ++j) {
5051                Lb[j] = best_index_int8(16, values, idl*xb[j]);
5052            }
5053            l += 32;
5054            uint8_t l_l = l & 0xf;
5055            uint8_t l_h = l >>  4;
5056            if (ib%2 == 0) scales_l[ib/2] = l_l;
5057            else scales_l[ib/2] |= (l_l << 4);
5058            scales_h[ib/8] |= (l_h << 2*(ib%8));
5059        }
5060    } else {
5061        dh[0] = GGML_FP32_TO_FP16(scales[0]);
5062        if (ntry > 0) {
5063            float id = scales[0] ? 1/scales[0] : 0;
5064            for (int j = 0; j < super_block_size; ++j) {
5065                L[j] = best_index_int8(16, values, id*x[j]);
5066            }
5067        }
5068    }
5069
5070    for (int i = 0; i < super_block_size/32; ++i) {
5071        for (int j = 0; j < 16; ++j) {
5072            q4[16*i + j] = L[32*i + j] | (L[32*i + 16 + j] << 4);
5073        }
5074    }
5075}
5076
5077size_t quantize_iq4_nl(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
5078    GGML_ASSERT(n_per_row%QK4_NL == 0);
5079    int64_t nblock = n_per_row/QK4_NL;
5080    char * qrow = (char *)dst;
5081    uint8_t L[QK4_NL];
5082    float weight[QK4_NL];
5083    uint16_t unused_h;
5084    uint8_t * unused_l = NULL;
5085    float scale;
5086    for (int64_t row = 0; row < nrow; ++row) {
5087        block_iq4_nl * iq4 = (block_iq4_nl *)qrow;
5088        for (int ibl = 0; ibl < nblock; ++ibl) {
5089            const float * qw = quant_weights ? quant_weights + QK4_NL*ibl : NULL;
5090            quantize_row_iq4_nl_impl(QK4_NL, 32, src + QK4_NL*ibl, &iq4[ibl].d, iq4[ibl].qs, &unused_h, unused_l,
5091                    &scale, weight, L, kvalues_iq4nl, qw, 7);
5092        }
5093        src += n_per_row;
5094        qrow += nblock*sizeof(block_iq4_nl);
5095    }
5096    return nrow * nblock * sizeof(block_iq4_nl);
5097}
5098
5099//void quantize_row_iq4_nl_ref(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t k) {
5100void quantize_row_iq4_nl_ref(const float * GGML_RESTRICT x, block_iq4_nl * GGML_RESTRICT y, int64_t k) {
5101    GGML_ASSERT(k%QK4_NL == 0);
5102    int64_t nblock = k/QK4_NL;
5103    uint8_t L[QK4_NL];
5104    float weight[QK4_NL];
5105    uint16_t unused_h;
5106    uint8_t * unused_l = NULL;
5107    float scale;
5108    block_iq4_nl * iq4 = y;
5109    for (int ibl = 0; ibl < nblock; ++ibl) {
5110        quantize_row_iq4_nl_impl(QK4_NL, 32, x + QK4_NL*ibl, &iq4[ibl].d, iq4[ibl].qs, &unused_h, unused_l,
5111                &scale, weight, L, kvalues_iq4nl, NULL, -1);
5112    }
5113}
5114
5115size_t quantize_iq4_xs(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
5116    GGML_ASSERT(n_per_row%QK_K == 0);
5117    int64_t nblock = n_per_row/QK_K;
5118    char * qrow = (char *)dst;
5119    uint8_t L[QK_K];
5120    float weight[32];
5121    float scales[QK_K/32];
5122    for (int64_t row = 0; row < nrow; ++row) {
5123        block_iq4_xs * iq4 = (block_iq4_xs *)qrow;
5124        for (int ibl = 0; ibl < nblock; ++ibl) {
5125            const float * qw = quant_weights ? quant_weights + QK_K*ibl : NULL;
5126            quantize_row_iq4_nl_impl(QK_K, 32, src + QK_K*ibl, &iq4[ibl].d, iq4[ibl].qs, &iq4[ibl].scales_h, iq4[ibl].scales_l,
5127                    scales, weight, L, kvalues_iq4nl, qw, 7);
5128        }
5129        src += n_per_row;
5130        qrow += nblock*sizeof(block_iq4_xs);
5131    }
5132    return nrow * nblock * sizeof(block_iq4_xs);
5133}
5134
5135void quantize_row_iq4_xs_ref(const float * GGML_RESTRICT x, block_iq4_xs * GGML_RESTRICT y, int64_t k) {
5136    assert(k % QK_K == 0);
5137    quantize_iq4_xs(x, y, 1, k, NULL);
5138}
5139
5140// =============================== 2.5625 bpw
5141
5142static void quantize_row_iq2_s_impl(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t n, const float * GGML_RESTRICT quant_weights) {
5143
5144    const int gindex = iq2_data_index(GGML_TYPE_IQ2_S);
5145
5146    const uint64_t * kgrid_q2xs      = iq2_data[gindex].grid;
5147    const int      * kmap_q2xs       = iq2_data[gindex].map;
5148    const uint16_t * kneighbors_q2xs = iq2_data[gindex].neighbours;
5149
5150    GGML_ASSERT(kmap_q2xs       && "forgot to call ggml_quantize_init()?");
5151    GGML_ASSERT(kgrid_q2xs      && "forgot to call ggml_quantize_init()?");
5152    GGML_ASSERT(kneighbors_q2xs && "forgot to call ggml_quantize_init()?");
5153    GGML_ASSERT(n%QK_K == 0);
5154
5155    const int kMaxQ = 3;
5156
5157    const int64_t nbl = n/QK_K;
5158
5159    block_iq2_s * y = vy;
5160
5161    float scales[QK_K/16];
5162    float weight[16];
5163    float xval[16];
5164    int8_t L[16];
5165    int8_t Laux[16];
5166    float  waux[16];
5167    bool   is_on_grid[2];
5168    bool   is_on_grid_aux[2];
5169    uint8_t block_signs[2];
5170
5171    for (int ibl = 0; ibl < nbl; ++ibl) {
5172
5173        memset(&y[ibl], 0, sizeof(block_iq2_s));
5174        y[ibl].d = GGML_FP32_TO_FP16(0.f);
5175
5176        float max_scale = 0;
5177
5178        const float * xbl = x + QK_K*ibl;
5179        float sumx2 = 0;
5180        for (int i = 0; i < QK_K; ++i) sumx2 += xbl[i]*xbl[i];
5181        float sigma2 = 2*sumx2/QK_K;
5182
5183        for (int ib = 0; ib < QK_K/16; ++ib) {
5184            const float * xb = xbl + 16*ib;
5185            if (quant_weights) {
5186                const float * qw = quant_weights + QK_K*ibl + 16*ib;
5187                for (int i = 0; i < 16; ++i) weight[i] = qw[i] * sqrtf(sigma2 + xb[i]*xb[i]);
5188            } else {
5189                for (int i = 0; i < 16; ++i) weight[i] = 0.25f*sigma2 + xb[i]*xb[i];
5190            }
5191            for (int i = 0; i < 16; ++i) waux[i] = sqrtf(weight[i]);
5192            for (int k = 0; k < 2; ++k) {
5193                uint8_t s = 0;
5194                for (int i = 0; i < 8; ++i) {
5195                    if (xb[8*k + i] >= 0) xval[8*k + i] = xb[8*k + i];
5196                    else {
5197                        xval[8*k + i] = -xb[8*k + i]; s |= (1 << i);
5198                    }
5199                }
5200                block_signs[k] = s;
5201            }
5202            float max = xval[0];
5203            for (int i = 1; i < 16; ++i) max = MAX(max, xval[i]);
5204            memset(L, 0, 16);
5205            if (max < GROUP_MAX_EPS_IQ2_S) {
5206                scales[ib] = 0;
5207                continue;
5208            }
5209            float best = 0;
5210            float scale = max/(2*kMaxQ-1);
5211            is_on_grid[0] = is_on_grid[1] = true;
5212            for (int is = -9; is <= 9; ++is) {
5213                float id = (2*kMaxQ-1+is*0.1f)/max;
5214                float this_scale = 1/id;
5215                for (int k = 0; k < 2; ++k) {
5216                    for (int i = 0; i < 8; ++i) {
5217                        int l = nearest_int(0.5f*(id*xval[8*k+i]-1));
5218                        Laux[8*k+i] = MAX(0, MIN(kMaxQ-1, l));
5219                    }
5220                    uint16_t u = 0;
5221                    for (int i = 0; i < 8; ++i) u |= (Laux[8*k+i] << 2*i);
5222                    int grid_index = kmap_q2xs[u];
5223                    is_on_grid_aux[k] = true;
5224                    if (grid_index < 0) {
5225                        is_on_grid_aux[k] = false;
5226                        const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1;
5227                        grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, this_scale, Laux + 8*k);
5228                    }
5229                }
5230                float sumqx = 0, sumq2 = 0;
5231                for (int i = 0; i < 16; ++i) {
5232                    float w = weight[i];
5233                    float q = 2*Laux[i] + 1;
5234                    sumqx += w*xval[i]*q;
5235                    sumq2 += w*q*q;
5236                }
5237                if (sumq2 > 0 && sumqx*sumqx > best*sumq2) {
5238                    scale = sumqx/sumq2; best = scale*sumqx;
5239                    for (int i = 0; i < 16; ++i) L[i] = Laux[i];
5240                    for (int k = 0; k <  2; ++k) is_on_grid[k] = is_on_grid_aux[k];
5241                }
5242            }
5243            int n_not_ongrid = 0;
5244            for (int k = 0; k < 2; ++k) if (!is_on_grid[k]) ++n_not_ongrid;
5245            if (n_not_ongrid > 0 && scale > 0) {
5246                float id = 1/scale;
5247                for (int k = 0; k < 2; ++k) {
5248                    if (is_on_grid[k]) continue;
5249                    uint16_t u = 0;
5250                    for (int i = 0; i < 8; ++i) {
5251                        int l = nearest_int(0.5f*(id*xval[8*k+i]-1));
5252                        l = MAX(0, MIN(kMaxQ-1, l));
5253                        u |= (l << 2*i);
5254                        L[8*k + i] = l;
5255                    }
5256                    int grid_index = kmap_q2xs[u];
5257                    if (grid_index < 0) {
5258                        const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1;
5259                        grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, scale, L + 8*k);
5260                    }
5261                }
5262                float sumqx = 0, sumq2 = 0;
5263                for (int i = 0; i < 16; ++i) {
5264                    float w = weight[i];
5265                    float q = 2*L[i] + 1;
5266                    sumqx += w*xval[i]*q;
5267                    sumq2 += w*q*q;
5268                }
5269                if (sumq2 > 0) scale = sumqx/sumq2;
5270            }
5271            if (scale < 0) {
5272                scale = -scale;
5273                for (int k = 0; k < 2; ++k) block_signs[k] = ~block_signs[k];
5274            }
5275            for (int k = 0; k < 2; ++k) {
5276                uint16_t u = 0;
5277                for (int i = 0; i < 8; ++i) u |= (L[8*k+i] << 2*i);
5278                int grid_index = kmap_q2xs[u];
5279                if (grid_index < 0) {
5280                    printf("Oops: found point %u not on grid:", u);
5281                    for (int i = 0; i < 8; ++i) printf(" %d", L[8*k+i]);
5282                    printf("\n");
5283                    GGML_ABORT("fatal error");
5284                }
5285                const int i8 = 2*ib + k;
5286                y[ibl].qs[i8] = grid_index & 255;
5287                y[ibl].qh[i8/4] |= ((grid_index >> 8) << 2*(i8%4));
5288                y[ibl].qs[QK_K/8 + i8] = block_signs[k];
5289            }
5290            GGML_ASSERT(scale >= 0);
5291            scales[ib] = scale;
5292            max_scale = MAX(max_scale, scale);
5293        }
5294
5295        if (!max_scale) {
5296            continue;
5297        }
5298
5299        float d = max_scale/31;
5300        y[ibl].d = GGML_FP32_TO_FP16(d * 0.9875f);
5301        float id = 1/d;
5302        for (int ib = 0; ib < QK_K/16; ++ib) {
5303            int l = nearest_int(0.5f*(id*scales[ib]-1));
5304            l = MAX(0, MIN(15, l));
5305            if (ib%2 == 0) y[ibl].scales[ib/2] = l;
5306            else y[ibl].scales[ib/2] |= (l << 4);
5307        }
5308    }
5309}
5310
5311size_t quantize_iq2_s(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) {
5312    GGML_ASSERT(n_per_row%QK_K == 0);
5313    int64_t nblock = n_per_row/QK_K;
5314    char * qrow = (char *)dst;
5315    for (int64_t row = 0; row < nrow; ++row) {
5316        quantize_row_iq2_s_impl(src, qrow, n_per_row, quant_weights);
5317        src += n_per_row;
5318        qrow += nblock*sizeof(block_iq2_s);
5319    }
5320    return nrow * nblock * sizeof(block_iq2_s);
5321}
5322
5323void quantize_row_iq2_s_ref(const float * GGML_RESTRICT x, block_iq2_s * GGML_RESTRICT y, int64_t k) {
5324    assert(k % QK_K == 0);
5325    quantize_iq2_s(x, y, 1, k, NULL);
5326}
5327
5328// =============================== data validation
5329
5330static bool validate_float(float f, size_t i) {
5331    if (isinf(f)) {
5332        fprintf(stderr, "ggml_validate_row_data: found inf value at block %zu\n", i);
5333        return false;
5334    }
5335
5336    if (isnan(f)) {
5337        fprintf(stderr, "ggml_validate_row_data: found nan value at block %zu\n", i);
5338        return false;
5339    }
5340
5341    return true;
5342}
5343
5344static bool isinf_fp16(ggml_fp16_t f) {
5345    return (f & 0x7c00) == 0x7c00 && (f & 0x03ff) == 0;
5346}
5347
5348static bool isnan_fp16(ggml_fp16_t f) {
5349    return (f & 0x7c00) == 0x7c00 && (f & 0x03ff) != 0;
5350}
5351
5352static bool validate_fp16(ggml_fp16_t f, size_t i) {
5353    if (isinf_fp16(f)) {
5354        fprintf(stderr, "ggml_validate_row_data: found inf value at block %zu\n", i);
5355        return false;
5356    }
5357
5358    if (isnan_fp16(f)) {
5359        fprintf(stderr, "ggml_validate_row_data: found nan value at block %zu\n", i);
5360        return false;
5361    }
5362
5363    return true;
5364}
5365
5366static bool validate_e_e8m0(uint8_t e, size_t i) {
5367    if (e == 0xff) {
5368        fprintf(stderr, "ggml_validate_row_data: found invalid e value %d at block %zu\n", e, i);
5369        return false;
5370    }
5371
5372    return true;
5373}
5374
5375#define VALIDATE_ROW_DATA_D_F16_IMPL(type, data, nb) \
5376    const type * q = (const type *) (data); \
5377    for (size_t i = 0; i < (nb); ++i) { \
5378        if (!validate_fp16(q[i].d, i)) { \
5379            return false; \
5380        } \
5381    }
5382
5383#define VALIDATE_ROW_DATA_DM_F16_IMPL(type, data, nb, d, m) \
5384    const type * q = (const type *) (data); \
5385    for (size_t i = 0; i < (nb); ++i) { \
5386        if (!validate_fp16(q[i].d, i) || !validate_fp16(q[i].m, i)) { \
5387            return false; \
5388        } \
5389    }
5390
5391#define VALIDATE_ROW_DATA_E_E8M0_IMPL(type, data, nb) \
5392    const type * q = (const type *) (data); \
5393    for (size_t i = 0; i < (nb); ++i) { \
5394        if (!validate_e_e8m0(q[i].e, i)) { \
5395            return false; \
5396        } \
5397    }
5398
5399#define VALIDATE_ROW_DATA_DVEC_F16_IMPL(type, data, nb, nr) \
5400    const type * q = (const type *) (data); \
5401    for (size_t i = 0; i < (nb); ++i) { \
5402        for (size_t j = 0; j < (nr); ++j) { \
5403            if (!validate_fp16(q[i].d[j], i)) { \
5404                return false; \
5405            } \
5406        } \
5407    }
5408
5409bool ggml_validate_row_data(enum ggml_type type, const void * data, size_t nbytes) {
5410    if (type < 0 || type >= GGML_TYPE_COUNT) {
5411        fprintf(stderr, "%s: invalid type %d\n", __func__, type);
5412        return false;
5413    }
5414
5415    if (nbytes % ggml_type_size(type) != 0) {
5416        fprintf(stderr, "%s: invalid size %zu for type %s (type size = %zu)\n", __func__, nbytes, ggml_type_name(type), ggml_type_size(type));
5417        return false;
5418    }
5419
5420    const size_t nb = nbytes/ggml_type_size(type);
5421
5422    switch (type) {
5423        case GGML_TYPE_BF16:
5424            {
5425                int nans = 0;
5426                int infs = 0;
5427                const unsigned short * f = (const unsigned short *) data;
5428                for (size_t i = 0; i < nb; ++i) {
5429                    nans += (f[i] & 0x7fff) > 0x7f80;
5430                    infs += (f[i] & 0x7fff) == 0x7f80;
5431                }
5432                if (nans) {
5433                    fprintf(stderr, "%s: found %d NaNs in row of %zu BF16 values\n", __func__, nans, nb);
5434                    return false;
5435                }
5436                if (infs) {
5437                    fprintf(stderr, "%s: found %d infinities in row of %zu BF16 values\n", __func__, infs, nb);
5438                    return false;
5439                }
5440            } break;
5441        case GGML_TYPE_F16:
5442            {
5443                const ggml_fp16_t * f = (const ggml_fp16_t *) data;
5444                size_t i = 0;
5445#if defined(__AVX2__)
5446                for (; i + 15 < nb; i += 16) {
5447                    __m256i v = _mm256_loadu_si256((const __m256i *)(f + i));
5448                    __m256i vexp = _mm256_and_si256(v, _mm256_set1_epi16(0x7c00));
5449                    __m256i cmp = _mm256_cmpeq_epi16(vexp, _mm256_set1_epi16(0x7c00));
5450                    int mask = _mm256_movemask_epi8(cmp);
5451                    if (mask) {
5452                        for (size_t j = 0; j < 16; ++j) {
5453                            if (!validate_fp16(f[i + j], i + j)) {
5454                                return false;
5455                            }
5456                        }
5457                        GGML_UNREACHABLE();
5458                    }
5459                }
5460#elif defined(__ARM_NEON)
5461                for (; i + 7 < nb; i += 8) {
5462                    uint16x8_t v = vld1q_u16(f + i);
5463                    uint16x8_t vexp = vandq_u16(v, vdupq_n_u16(0x7c00));
5464                    uint16x8_t cmp = vceqq_u16(vexp, vdupq_n_u16(0x7c00));
5465                    uint64_t mask = vget_lane_u64(vreinterpret_u64_u8(vshrn_n_u16(cmp, 4)), 0);
5466                    if (mask) {
5467                        for (size_t j = 0; j < 8; ++j) {
5468                            if (!validate_fp16(f[i + j], i + j)) {
5469                                return false;
5470                            }
5471                        }
5472                        GGML_UNREACHABLE();
5473                    }
5474                }
5475#endif
5476                for (; i < nb; ++i) {
5477                    if (!validate_fp16(f[i], i)) {
5478                        return false;
5479                    }
5480                }
5481            } break;
5482        case GGML_TYPE_F32:
5483            {
5484                const float * f = (const float *) data;
5485                size_t i = 0;
5486#if defined(__AVX2__)
5487                for (; i + 7 < nb; i += 8) {
5488                    __m256i v = _mm256_loadu_si256((const __m256i *)(f + i));
5489                    __m256i vexp = _mm256_and_si256(v, _mm256_set1_epi32(0x7f800000));
5490                    __m256i cmp = _mm256_cmpeq_epi32(vexp, _mm256_set1_epi32(0x7f800000));
5491                    int mask = _mm256_movemask_epi8(cmp);
5492                    if (mask) {
5493                        for (size_t j = 0; j < 8; ++j) {
5494                            if (!validate_float(f[i + j], i + j)) {
5495                                return false;
5496                            }
5497                        }
5498                        GGML_UNREACHABLE();
5499                    }
5500                }
5501#elif defined(__ARM_NEON)
5502                for (; i + 3 < nb; i += 4) {
5503                    uint32x4_t v = vld1q_u32((const uint32_t *)f + i);
5504                    uint32x4_t vexp = vandq_u32(v, vdupq_n_u32(0x7f800000));
5505                    uint32x4_t cmp = vceqq_u32(vexp, vdupq_n_u32(0x7f800000));
5506                    uint64_t mask = vget_lane_u64(vreinterpret_u64_u16(vshrn_n_u32(cmp, 8)), 0);
5507                    if (mask) {
5508                        for (size_t j = 0; j < 4; ++j) {
5509                            if (!validate_float(f[i + j], i + j)) {
5510                                return false;
5511                            }
5512                        }
5513                        GGML_UNREACHABLE();
5514                    }
5515                }
5516#endif
5517                for (; i < nb; ++i) {
5518                    if (!validate_float(f[i], i)) {
5519                        return false;
5520                    }
5521                }
5522            } break;
5523        case GGML_TYPE_F64:
5524            {
5525                const double * f = (const double *) data;
5526                for (size_t i = 0; i < nb; ++i) {
5527                    if (!validate_float(f[i], i)) {
5528                        return false;
5529                    }
5530                }
5531            } break;
5532        case GGML_TYPE_Q1_0:
5533            {
5534                VALIDATE_ROW_DATA_D_F16_IMPL(block_q1_0, data, nb);
5535            } break;
5536        case GGML_TYPE_Q2_0:
5537            {
5538                VALIDATE_ROW_DATA_D_F16_IMPL(block_q2_0, data, nb);
5539            } break;
5540        case GGML_TYPE_Q4_0:
5541            {
5542                VALIDATE_ROW_DATA_D_F16_IMPL(block_q4_0, data, nb);
5543            } break;
5544        case GGML_TYPE_Q4_1:
5545            {
5546                VALIDATE_ROW_DATA_DM_F16_IMPL(block_q4_1, data, nb, d, m);
5547            } break;
5548        case GGML_TYPE_Q5_0:
5549            {
5550                VALIDATE_ROW_DATA_D_F16_IMPL(block_q5_0, data, nb);
5551            } break;
5552        case GGML_TYPE_Q5_1:
5553            {
5554                VALIDATE_ROW_DATA_DM_F16_IMPL(block_q5_1, data, nb, d, m);
5555            } break;
5556        case GGML_TYPE_Q8_0:
5557            {
5558                VALIDATE_ROW_DATA_D_F16_IMPL(block_q8_0, data, nb);
5559            } break;
5560        case GGML_TYPE_MXFP4:
5561            {
5562                VALIDATE_ROW_DATA_E_E8M0_IMPL(block_mxfp4, data, nb);
5563            } break;
5564        case GGML_TYPE_NVFP4:
5565            {
5566                // UE4M3 scales are uint8_t — all byte values are valid
5567                GGML_UNUSED(data);
5568                GGML_UNUSED(nb);
5569            } break;
5570        case GGML_TYPE_Q2_K:
5571            {
5572                VALIDATE_ROW_DATA_DM_F16_IMPL(block_q2_K, data, nb, d, dmin);
5573            } break;
5574        case GGML_TYPE_Q3_K:
5575            {
5576                VALIDATE_ROW_DATA_D_F16_IMPL(block_q3_K, data, nb);
5577            } break;
5578        case GGML_TYPE_Q4_K:
5579            {
5580                VALIDATE_ROW_DATA_DM_F16_IMPL(block_q4_K, data, nb, d, dmin);
5581            } break;
5582        case GGML_TYPE_Q5_K:
5583            {
5584                VALIDATE_ROW_DATA_DM_F16_IMPL(block_q5_K, data, nb, d, dmin);
5585            } break;
5586        case GGML_TYPE_Q6_K:
5587            {
5588                VALIDATE_ROW_DATA_D_F16_IMPL(block_q6_K, data, nb);
5589            } break;
5590        case GGML_TYPE_Q8_K:
5591            {
5592                const block_q8_K * q = (const block_q8_K *) data;
5593                for (size_t i = 0; i < nb; ++i) {
5594                    if (!validate_float(q[i].d, i)) {
5595                        return false;
5596                    }
5597                }
5598            } break;
5599        case GGML_TYPE_TQ1_0:
5600            {
5601                VALIDATE_ROW_DATA_D_F16_IMPL(block_tq1_0, data, nb);
5602            } break;
5603        case GGML_TYPE_TQ2_0:
5604            {
5605                VALIDATE_ROW_DATA_D_F16_IMPL(block_tq2_0, data, nb);
5606            } break;
5607        case GGML_TYPE_IQ1_S:
5608            {
5609                VALIDATE_ROW_DATA_D_F16_IMPL(block_iq1_s, data, nb);
5610            } break;
5611        case GGML_TYPE_IQ1_M:
5612            {
5613                const block_iq1_m * q = (const block_iq1_m *) data;
5614                for (size_t i = 0; i < nb; ++i) {
5615                    iq1m_scale_t scale;
5616                    const uint16_t * sc = (const uint16_t *)q[i].scales;
5617                    scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000);
5618                    if (!validate_fp16(scale.f16, i)) {
5619                        return false;
5620                    }
5621                }
5622            } break;
5623        case GGML_TYPE_IQ2_XXS:
5624            {
5625                VALIDATE_ROW_DATA_D_F16_IMPL(block_iq2_xxs, data, nb);
5626            } break;
5627        case GGML_TYPE_IQ2_XS:
5628            {
5629                VALIDATE_ROW_DATA_D_F16_IMPL(block_iq2_xs, data, nb);
5630            } break;
5631        case GGML_TYPE_IQ2_S:
5632            {
5633                VALIDATE_ROW_DATA_D_F16_IMPL(block_iq2_s, data, nb);
5634            } break;
5635        case GGML_TYPE_IQ3_XXS:
5636            {
5637                VALIDATE_ROW_DATA_D_F16_IMPL(block_iq3_xxs, data, nb);
5638            } break;
5639
5640        case GGML_TYPE_IQ3_S:
5641            {
5642                VALIDATE_ROW_DATA_D_F16_IMPL(block_iq3_s, data, nb);
5643            } break;
5644        case GGML_TYPE_IQ4_XS:
5645            {
5646                VALIDATE_ROW_DATA_D_F16_IMPL(block_iq4_xs, data, nb);
5647            } break;
5648        case GGML_TYPE_IQ4_NL:
5649            {
5650                VALIDATE_ROW_DATA_D_F16_IMPL(block_iq4_nl, data, nb);
5651            } break;
5652
5653        case GGML_TYPE_I8:
5654        case GGML_TYPE_I16:
5655        case GGML_TYPE_I32:
5656        case GGML_TYPE_I64:
5657            // nothing to validate
5658            break;
5659        default:
5660            {
5661                fprintf(stderr, "%s: invalid type %d\n", __func__, type);
5662                return false;
5663            }
5664    }
5665
5666    return true;
5667}