Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
/*++
 
Copyright (c) Microsoft Corporation. All rights reserved.
 
Licensed under the MIT License.
 
Module Name:
 
    qkv_quant.cpp
 
Abstract:
 
    Portable scalar reference implementation of the symmetric INT4 / INT8
    quantized KV-cache GEMM API declared in mlas_qkv_quant.h. This file provides
    a correct scalar fallback; SIMD-optimized backends (AVX2, AVX512-VNNI, NEON)
    are dispatched at runtime via the platform dispatch table.
 
    See mlas_qkv_quant.h for the packing, scaling, and layout contract.
 
--*/
 
#include "mlas_qkv_quant.h"
#include "mlasi.h"
#include "qkv_quant_kernel.h"
#include "qkv_quant_common.h"
 
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <memory>
 
using namespace MlasKVQuantInternal;
 
namespace {
 
constexpr int kInt4Min = -8;
constexpr int kInt4Max = 7;
constexpr int kInt8Min = -128;
constexpr int kInt8Max = 127;
 
// Round-to-nearest-even via rintf, matching the CUDA QDQ implementation.
inline int8_t
QuantizeInt8(float x, float inv_scale)
{
    const float q = std::rintf(x * inv_scale);
    const int qi = static_cast<int>(std::max(static_cast<float>(kInt8Min),
                                             std::min(static_cast<float>(kInt8Max), q)));
    return static_cast<int8_t>(qi);
}
 
inline int
QuantizeInt4Nibble(float x, float inv_scale)
{
    const float q = std::rintf(x * inv_scale);
    const int qi = static_cast<int>(std::max(static_cast<float>(kInt4Min),
                                             std::min(static_cast<float>(kInt4Max), q)));
    return qi;
}
 
inline float
SafeInvScale(float scale)
{
    // A zero scale (typically meaning "no data yet") is treated as 1.0 so the
    // quantize step degenerates to a clamp/round rather than producing NaN.
    return (scale != 0.0f) ? (1.0f / scale) : 1.0f;
}
 
inline float
DequantInt8(int8_t q, float scale)
{
    return static_cast<float>(q) * scale;
}
 
// Decode a single nibble from a packed byte. `col` is the unpacked column
// index; even columns occupy the low nibble, odd columns the high nibble.
inline float
DequantInt4FromByte(uint8_t packed, size_t col, float scale)
{
    const int nibble = (col & 1U) == 0 ? (packed & 0x0F) : ((packed >> 4) & 0x0F);
    return static_cast<float>(nibble - kInt4Bias) * scale;
}
 
// Pack one row of FP32 source into INT8 destination.
void
QuantizeRowInt8(
    const float* src,
    int8_t* dst,
    size_t cols,
    bool per_channel,
    const float* scales)
{
    if (per_channel) {
        for (size_t c = 0; c < cols; ++c) {
            dst[c] = QuantizeInt8(src[c], SafeInvScale(scales[c]));
        }
    } else {
        const float inv_scale = SafeInvScale(scales[0]);
        for (size_t c = 0; c < cols; ++c) {
            dst[c] = QuantizeInt8(src[c], inv_scale);
        }
    }
}
 
// Pack one row of FP32 source into INT4 destination using the +8-biased
// two-per-byte convention. If `cols` is odd, the trailing high nibble is set
// to 0 (which decodes to -8 * scale; matches the CUDA "pair with q1 = 0"
// convention and is fine because such columns are out of range for the
// consumer).
void
QuantizeRowInt4(
    const float* src,
    uint8_t* dst,
    size_t cols,
    bool per_channel,
    const float* scales)
{
    const size_t out_bytes = (cols + 1) / 2;
    for (size_t b = 0; b < out_bytes; ++b) {
        const size_t c0 = 2 * b;
        const size_t c1 = c0 + 1;
 
        const float inv0 = per_channel ? SafeInvScale(scales[c0])
                                       : SafeInvScale(scales[0]);
        const int q0 = QuantizeInt4Nibble(src[c0], inv0);
        int q1 = 0;
        if (c1 < cols) {
            const float inv1 = per_channel ? SafeInvScale(scales[c1])
                                           : SafeInvScale(scales[0]);
            q1 = QuantizeInt4Nibble(src[c1], inv1);
        }
        dst[b] = static_cast<uint8_t>(
            (((q0 + kInt4Bias) & 0x0F)) |
            ((((q1 + kInt4Bias) & 0x0F)) << 4));
    }
}
 
void
QuantizeRowInt8Fp16(
    const MLAS_FP16* src,
    int8_t* dst,
    size_t cols,
    bool per_channel,
    const float* scales)
{
    if (per_channel) {
        for (size_t c = 0; c < cols; ++c) {
            dst[c] = QuantizeInt8(static_cast<float>(src[c]), SafeInvScale(scales[c]));
        }
    } else {
        const float inv_scale = SafeInvScale(scales[0]);
        for (size_t c = 0; c < cols; ++c) {
            dst[c] = QuantizeInt8(static_cast<float>(src[c]), inv_scale);
        }
    }
}
 
void
QuantizeRowInt4Fp16(
    const MLAS_FP16* src,
    uint8_t* dst,
    size_t cols,
    bool per_channel,
    const float* scales)
{
    const size_t out_bytes = (cols + 1) / 2;
    for (size_t b = 0; b < out_bytes; ++b) {
        const size_t c0 = 2 * b;
        const size_t c1 = c0 + 1;
        const float inv0 = per_channel ? SafeInvScale(scales[c0])
                                       : SafeInvScale(scales[0]);
        const int q0 = QuantizeInt4Nibble(static_cast<float>(src[c0]), inv0);
        int q1 = 0;
        if (c1 < cols) {
            const float inv1 = per_channel ? SafeInvScale(scales[c1])
                                           : SafeInvScale(scales[0]);
            q1 = QuantizeInt4Nibble(static_cast<float>(src[c1]), inv1);
        }
        dst[b] = static_cast<uint8_t>(
            (((q0 + kInt4Bias) & 0x0F)) |
            ((((q1 + kInt4Bias) & 0x0F)) << 4));
    }
}
 
// Dequantize one row from INT8.
void
DequantizeRowInt8(
    const int8_t* src,
    float* dst,
    size_t cols,
    bool per_channel,
    const float* scales)
{
    if (per_channel) {
        for (size_t c = 0; c < cols; ++c) {
            dst[c] = DequantInt8(src[c], scales[c]);
        }
    } else {
        const float scale = scales[0];
        for (size_t c = 0; c < cols; ++c) {
            dst[c] = DequantInt8(src[c], scale);
        }
    }
}
 
// Dequantize one row from packed INT4.
void
DequantizeRowInt4(
    const uint8_t* src,
    float* dst,
    size_t cols,
    bool per_channel,
    const float* scales)
{
    for (size_t c = 0; c < cols; ++c) {
        const uint8_t packed = src[c / 2];
        const float scale = per_channel ? scales[c] : scales[0];
        dst[c] = DequantInt4FromByte(packed, c, scale);
    }
}
 
}  // namespace
 
bool
MLASCALL
MlasIsKVQuantGemmSupported(MLAS_KV_QUANT_TYPE /*QuantType*/)
{
    // The portable reference path supports every mode on every platform.
    return true;
}
 
size_t
MLASCALL
MlasKVQuantPackedRowBytes(MLAS_KV_QUANT_TYPE QuantType, size_t Cols)
{
    return IsInt4Mode(QuantType) ? (Cols + 1) / 2 : Cols;
}
 
void
MLASCALL
MlasKVQuantize(
    const float* Src,
    void* Dst,
    size_t Rows,
    size_t Cols,
    size_t lda,
    MLAS_KV_QUANT_TYPE QuantType,
    const float* Scales,
    MLAS_THREADPOOL* ThreadPool)
{
    if (Rows == 0 || Cols == 0) {
        return;
    }
 
    const bool int4 = IsInt4Mode(QuantType);
    const bool per_channel = IsPerChannelMode(QuantType);
    const size_t row_bytes = MlasKVQuantPackedRowBytes(QuantType, Cols);
    auto* dst_bytes = static_cast<uint8_t*>(Dst);
 
    MlasTrySimpleParallel(
        ThreadPool, static_cast<ptrdiff_t>(Rows),
        [&](ptrdiff_t r_idx) {
            const size_t r = static_cast<size_t>(r_idx);
            const float* src_row = Src + r * lda;
            uint8_t* dst_row = dst_bytes + r * row_bytes;
            if (int4) {
                QuantizeRowInt4(src_row, dst_row, Cols, per_channel, Scales);
            } else {
                QuantizeRowInt8(src_row, reinterpret_cast<int8_t*>(dst_row),
                                Cols, per_channel, Scales);
            }
        });
}
 
void
MLASCALL
MlasKVQuantizeFp16(
    const MLAS_FP16* Src,
    void* Dst,
    size_t Rows,
    size_t Cols,
    size_t lda,
    MLAS_KV_QUANT_TYPE QuantType,
    const float* Scales,
    MLAS_THREADPOOL* ThreadPool)
{
    if (Rows == 0 || Cols == 0) {
        return;
    }
 
    const bool int4 = IsInt4Mode(QuantType);
    const bool per_channel = IsPerChannelMode(QuantType);
    const size_t row_bytes = MlasKVQuantPackedRowBytes(QuantType, Cols);
    auto* dst_bytes = static_cast<uint8_t*>(Dst);
 
    MlasTrySimpleParallel(
        ThreadPool, static_cast<ptrdiff_t>(Rows),
        [&](ptrdiff_t r_idx) {
            const size_t r = static_cast<size_t>(r_idx);
            const MLAS_FP16* src_row = Src + r * lda;
            uint8_t* dst_row = dst_bytes + r * row_bytes;
            if (int4) {
                QuantizeRowInt4Fp16(src_row, dst_row, Cols, per_channel, Scales);
            } else {
                QuantizeRowInt8Fp16(src_row, reinterpret_cast<int8_t*>(dst_row),
                                    Cols, per_channel, Scales);
            }
        });
}
 
void
MLASCALL
MlasKVDequantize(
    const void* Src,
    float* Dst,
    size_t Rows,
    size_t Cols,
    size_t ldb,
    MLAS_KV_QUANT_TYPE QuantType,
    const float* Scales,
    MLAS_THREADPOOL* ThreadPool)
{
    if (Rows == 0 || Cols == 0) {
        return;
    }
 
    const bool int4 = IsInt4Mode(QuantType);
    const bool per_channel = IsPerChannelMode(QuantType);
    const size_t row_bytes = MlasKVQuantPackedRowBytes(QuantType, Cols);
    const auto* src_bytes = static_cast<const uint8_t*>(Src);
 
    MlasTrySimpleParallel(
        ThreadPool, static_cast<ptrdiff_t>(Rows),
        [&](ptrdiff_t r_idx) {
            const size_t r = static_cast<size_t>(r_idx);
            const uint8_t* src_row = src_bytes + r * row_bytes;
            float* dst_row = Dst + r * ldb;
            if (int4) {
                DequantizeRowInt4(src_row, dst_row, Cols, per_channel, Scales);
            } else {
                DequantizeRowInt8(reinterpret_cast<const int8_t*>(src_row),
                                  dst_row, Cols, per_channel, Scales);
            }
        });
}
 
void
MLASCALL
MlasQKGemm(
    size_t M,
    size_t N,
    size_t K,
    float Alpha,
    const float* A,
    size_t lda,
    const void* B,
    MLAS_KV_QUANT_TYPE QuantType,
    const float* Scales,
    float* C,
    size_t ldc,
    MLAS_THREADPOOL* ThreadPool)
{
    if (M == 0 || N == 0) {
        return;
    }
    if (K == 0) {
        for (size_t m = 0; m < M; ++m) {
            std::memset(C + m * ldc, 0, N * sizeof(float));
        }
        return;
    }
 
    //
    // Try the SIMD-optimized dispatch path. The vectorized kernels handle
    // the full M×N×K computation in a single call (no thread pool — the
    // caller's thread-pool loop already partitions across heads/batches).
    //
    const auto* Dispatch = GetMlasPlatform().KVQuantGemmDispatch;
    if (Dispatch != nullptr && Dispatch->QKGemm != nullptr) {
        // The dispatch kernels are designed to be called per-(batch,head) tile
        // from an outer parallel loop, so we invoke them directly here. For
        // large N the outer loop in gqa_attention_base already parallelizes.
        Dispatch->QKGemm(M, N, K, Alpha, A, lda, B, QuantType, Scales, C, ldc);
        return;
    }
 
    //
    // Scalar reference fallback.
    //
    const bool int4 = IsInt4Mode(QuantType);
    const bool per_channel = IsPerChannelMode(QuantType);
    const size_t row_bytes = MlasKVQuantPackedRowBytes(QuantType, K);
    const auto* B_bytes = static_cast<const uint8_t*>(B);
 
    // Parallelize over N (independent output columns -> independent B rows).
    MlasTrySimpleParallel(
        ThreadPool, static_cast<ptrdiff_t>(N),
        [&](ptrdiff_t n_idx) {
            const size_t n = static_cast<size_t>(n_idx);
            const uint8_t* b_row = B_bytes + n * row_bytes;
 
            // Dequantize B row [K] once and reuse across all M.
            // Small buffer (K = head_size, typically <= 256).
            float b_dequant[1024];
            float* b_buf = b_dequant;
            std::unique_ptr<float[]> heap_buf;
            if (K > sizeof(b_dequant) / sizeof(b_dequant[0])) {
                heap_buf.reset(new float[K]);
                b_buf = heap_buf.get();
            }
            if (int4) {
                DequantizeRowInt4(b_row, b_buf, K, per_channel, Scales);
            } else {
                DequantizeRowInt8(reinterpret_cast<const int8_t*>(b_row),
                                  b_buf, K, per_channel, Scales);
            }
 
            for (size_t m = 0; m < M; ++m) {
                const float* a_row = A + m * lda;
                float acc = 0.0f;
                for (size_t k = 0; k < K; ++k) {
                    acc += a_row[k] * b_buf[k];
                }
                C[m * ldc + n] = Alpha * acc;
            }
        });
}
 
void
MLASCALL
MlasQKGemmFp16(
    size_t M,
    size_t N,
    size_t K,
    float Alpha,
    const MLAS_FP16* A,
    size_t lda,
    const void* B,
    MLAS_KV_QUANT_TYPE QuantType,
    const float* Scales,
    float* C,
    size_t ldc,
    MLAS_THREADPOOL* ThreadPool)
{
    if (M == 0 || N == 0) {
        return;
    }
    if (K == 0) {
        for (size_t m = 0; m < M; ++m) {
            std::memset(C + m * ldc, 0, N * sizeof(float));
        }
        return;
    }
 
    const auto* Dispatch = GetMlasPlatform().KVQuantGemmDispatch;
    if (GetMlasPlatform().KVQuantGemmFp16Supported_ &&
        Dispatch != nullptr && Dispatch->QKGemmFp16 != nullptr) {
        Dispatch->QKGemmFp16(M, N, K, Alpha, A, lda, B, QuantType, Scales, C, ldc);
        return;
    }
 
    const bool int4 = IsInt4Mode(QuantType);
    const bool per_channel = IsPerChannelMode(QuantType);
    const size_t row_bytes = MlasKVQuantPackedRowBytes(QuantType, K);
    const auto* B_bytes = static_cast<const uint8_t*>(B);
 
    MlasTrySimpleParallel(
        ThreadPool, static_cast<ptrdiff_t>(N),
        [&](ptrdiff_t n_idx) {
            const size_t n = static_cast<size_t>(n_idx);
            const uint8_t* b_row = B_bytes + n * row_bytes;
            for (size_t m = 0; m < M; ++m) {
                const MLAS_FP16* a_row = A + m * lda;
                float acc = 0.0f;
                for (size_t k = 0; k < K; ++k) {
                    const float b = int4
                                        ? DequantInt4FromByte(b_row[k / 2], k, per_channel ? Scales[k] : Scales[0])
                                        : DequantInt8(reinterpret_cast<const int8_t*>(b_row)[k], per_channel ? Scales[k] : Scales[0]);
                    acc += static_cast<float>(a_row[k]) * b;
                }
                C[m * ldc + n] = Alpha * acc;
            }
        });
}
 
void
MLASCALL
MlasSVGemm(
    size_t M,
    size_t N,
    size_t K,
    const float* A,
    size_t lda,
    const void* B,
    MLAS_KV_QUANT_TYPE QuantType,
    const float* Scales,
    float* C,
    size_t ldc,
    float Beta,
    MLAS_THREADPOOL* ThreadPool)
{
    if (M == 0 || N == 0) {
        return;
    }
    if (K == 0) {
        if (Beta == 0.0f) {
            for (size_t m = 0; m < M; ++m) {
                std::memset(C + m * ldc, 0, N * sizeof(float));
            }
        } else if (Beta != 1.0f) {
            for (size_t m = 0; m < M; ++m) {
                for (size_t n = 0; n < N; ++n) {
                    C[m * ldc + n] *= Beta;
                }
            }
        }
        return;
    }
 
    //
    // Try the SIMD-optimized dispatch path.
    //
    const auto* Dispatch = GetMlasPlatform().KVQuantGemmDispatch;
    if (Dispatch != nullptr && Dispatch->SVGemm != nullptr) {
        Dispatch->SVGemm(M, N, K, A, lda, B, QuantType, Scales, C, ldc, Beta);
        return;
    }
 
    //
    // Scalar reference fallback.
    //
    const bool int4 = IsInt4Mode(QuantType);
    const bool per_channel = IsPerChannelMode(QuantType);
    const size_t row_bytes = MlasKVQuantPackedRowBytes(QuantType, N);
    const auto* B_bytes = static_cast<const uint8_t*>(B);
 
    // Parallelize over M (output rows). Each M iterates over the full K
    // reduction, dequantizing B rows one at a time.
    MlasTrySimpleParallel(
        ThreadPool, static_cast<ptrdiff_t>(M),
        [&](ptrdiff_t m_idx) {
            const size_t m = static_cast<size_t>(m_idx);
            const float* a_row = A + m * lda;
            float* c_row = C + m * ldc;
            if (Beta == 0.0f) {
                std::memset(c_row, 0, N * sizeof(float));
            } else if (Beta != 1.0f) {
                for (size_t n = 0; n < N; ++n) {
                    c_row[n] *= Beta;
                }
            }
 
            // Per-row scratch for one dequantized B row of length N.
            float b_dequant[1024];
            float* b_buf = b_dequant;
            std::unique_ptr<float[]> heap_buf;
            if (N > sizeof(b_dequant) / sizeof(b_dequant[0])) {
                heap_buf.reset(new float[N]);
                b_buf = heap_buf.get();
            }
 
            for (size_t k = 0; k < K; ++k) {
                const uint8_t* b_row_packed = B_bytes + k * row_bytes;
                if (int4) {
                    DequantizeRowInt4(b_row_packed, b_buf, N, per_channel, Scales);
                } else {
                    DequantizeRowInt8(reinterpret_cast<const int8_t*>(b_row_packed),
                                      b_buf, N, per_channel, Scales);
                }
                const float a_val = a_row[k];
                for (size_t n = 0; n < N; ++n) {
                    c_row[n] += a_val * b_buf[n];
                }
            }
        });
}
 
 
void
MLASCALL
MlasSVGemmFp16(
    size_t M,
    size_t N,
    size_t K,
    const float* A,
    size_t lda,
    const void* B,
    MLAS_KV_QUANT_TYPE QuantType,
    const float* Scales,
    MLAS_FP16* C,
    size_t ldc,
    float Beta,
    MLAS_THREADPOOL* ThreadPool)
{
    if (M == 0 || N == 0) {
        return;
    }
    if (K == 0) {
        for (size_t m = 0; m < M; ++m) {
            for (size_t n = 0; n < N; ++n) {
                C[m * ldc + n] = MLAS_FP16(Beta == 0.0f ? 0.0f : Beta * static_cast<float>(C[m * ldc + n]));
            }
        }
        return;
    }
 
    const auto* Dispatch = GetMlasPlatform().KVQuantGemmDispatch;
    if (GetMlasPlatform().KVQuantGemmFp16Supported_ &&
        Dispatch != nullptr && Dispatch->SVGemmFp16 != nullptr) {
        Dispatch->SVGemmFp16(M, N, K, A, lda, B, QuantType, Scales, C, ldc, Beta);
        return;
    }
 
    const bool int4 = IsInt4Mode(QuantType);
    const bool per_channel = IsPerChannelMode(QuantType);
    const size_t row_bytes = MlasKVQuantPackedRowBytes(QuantType, N);
    const auto* B_bytes = static_cast<const uint8_t*>(B);
 
    MlasTrySimpleParallel(
        ThreadPool, static_cast<ptrdiff_t>(M),
        [&](ptrdiff_t m_idx) {
            const size_t m = static_cast<size_t>(m_idx);
            const float* a_row = A + m * lda;
            MLAS_FP16* c_row = C + m * ldc;
            for (size_t n = 0; n < N; ++n) {
                float acc = Beta == 0.0f ? 0.0f : Beta * static_cast<float>(c_row[n]);
                for (size_t k = 0; k < K; ++k) {
                    const uint8_t* b_row = B_bytes + k * row_bytes;
                    const float b = int4
                                        ? DequantInt4FromByte(b_row[n / 2], n, per_channel ? Scales[n] : Scales[0])
                                        : DequantInt8(reinterpret_cast<const int8_t*>(b_row)[n], per_channel ? Scales[n] : Scales[0]);
                    acc += a_row[k] * b;
                }
                c_row[n] = MLAS_FP16(acc);
            }
        });
}