forked from zhongkaifu/TensorSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathManagedQuantizedOps.cs
More file actions
2120 lines (1872 loc) · 90.1 KB
/
Copy pathManagedQuantizedOps.cs
File metadata and controls
2120 lines (1872 loc) · 90.1 KB
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Zhongkai Fu. All rights reserved.
// https://github.com/zhongkaifu/TensorSharp
//
// This file is part of TensorSharp.
//
// TensorSharp is licensed under the BSD-3-Clause license found in the LICENSE file in the root directory of this source tree.
//
// TensorSharp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the BSD-3-Clause License for more details.
using System;
using System.Buffers;
using System.Numerics;
using System.Numerics.Tensors;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
using System.Threading.Tasks;
namespace TensorSharp.Models
{
internal static class ManagedQuantizedOps
{
private const int QK4_0 = 32;
private const int QK4_1 = 32;
private const int QK5_0 = 32;
private const int QK5_1 = 32;
private const int QK8_0 = 32;
private const int QK8_1 = 32;
private const int QK4_NL = 32;
private const int QK_MXFP4 = 32;
private const int QK_K = 256;
private const int K_SCALE_SIZE = 12;
private const int Q4_0BlockBytes = 2 + QK4_0 / 2;
private const int Q4_1BlockBytes = 4 + QK4_1 / 2;
private const int Q5_0BlockBytes = 2 + 4 + QK5_0 / 2;
private const int Q5_1BlockBytes = 4 + 4 + QK5_1 / 2;
private const int Q8_0BlockBytes = 2 + QK8_0;
private const int Q8_1BlockBytes = 4 + QK8_1;
private const int Q4_KBlockBytes = 4 + K_SCALE_SIZE + QK_K / 2;
private const int Q5_KBlockBytes = 4 + K_SCALE_SIZE + QK_K / 8 + QK_K / 2;
private const int Q6_KBlockBytes = QK_K / 2 + QK_K / 4 + QK_K / 16 + 2;
private const int Q8_KBlockBytes = 4 + QK_K + 2 * (QK_K / 16);
private static readonly sbyte[] Iq4NlValues =
{
-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113,
};
private static readonly sbyte[] Mxfp4Values =
{
0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12,
};
public static bool SupportsCpuQuantizedStorage(GgmlTensorType type)
{
return type switch
{
GgmlTensorType.F16 => true,
GgmlTensorType.BF16 => true,
GgmlTensorType.Q4_0 => true,
GgmlTensorType.Q4_1 => true,
GgmlTensorType.Q5_0 => true,
GgmlTensorType.Q5_1 => true,
GgmlTensorType.Q8_0 => true,
GgmlTensorType.Q8_1 => true,
GgmlTensorType.Q2_K => true,
GgmlTensorType.Q3_K => true,
GgmlTensorType.Q4_K => true,
GgmlTensorType.Q5_K => true,
GgmlTensorType.Q6_K => true,
GgmlTensorType.IQ4_NL => true,
GgmlTensorType.IQ2_XXS => true,
GgmlTensorType.IQ2_S => true,
GgmlTensorType.IQ3_S => true,
GgmlTensorType.MXFP4 => true,
_ => false,
};
}
public static bool SupportsDequantization(GgmlTensorType type)
{
return type switch
{
GgmlTensorType.F32 => true,
GgmlTensorType.F16 => true,
GgmlTensorType.BF16 => true,
GgmlTensorType.I8 => true,
GgmlTensorType.I16 => true,
GgmlTensorType.I32 => true,
GgmlTensorType.I64 => true,
GgmlTensorType.F64 => true,
_ => SupportsCpuQuantizedStorage(type),
};
}
public static long RowSize(int ggmlType, long ne)
{
var type = (GgmlTensorType)ggmlType;
if (!SupportsDequantization(type))
throw new NotSupportedException($"Pure C# backend does not support GGUF tensor type {type}.");
long blockSize = GgufFile.GetBlockSize(type);
if (ne % blockSize != 0)
throw new NotSupportedException($"Tensor type {type} requires row length aligned to {blockSize}, got {ne}.");
return (ne / blockSize) * GgufFile.GetTypeSize(type);
}
public static unsafe void DequantizeToFloat32(int ggmlType, byte[] src, int srcOffset, float[] dst, int dstOffset, long numElements)
{
var type = (GgmlTensorType)ggmlType;
if (!SupportsDequantization(type))
throw new NotSupportedException($"Pure C# backend does not support GGUF tensor type {type}.");
fixed (byte* srcBase = src)
fixed (float* dstBase = dst)
{
DequantizeToFloat32(type, srcBase + srcOffset, dstBase + dstOffset, numElements);
}
}
public static unsafe void DequantizeToFloat32(int ggmlType, IntPtr src, float[] dst, int dstOffset, long numElements)
{
var type = (GgmlTensorType)ggmlType;
if (!SupportsDequantization(type))
throw new NotSupportedException($"Pure C# backend does not support GGUF tensor type {type}.");
fixed (float* dstBase = dst)
{
DequantizeToFloat32(type, (byte*)src.ToPointer(), dstBase + dstOffset, numElements);
}
}
public static unsafe void DequantizeToFloat32Native(int ggmlType, IntPtr src, IntPtr dst, long numElements)
{
var type = (GgmlTensorType)ggmlType;
if (!SupportsDequantization(type))
throw new NotSupportedException($"Pure C# backend does not support GGUF tensor type {type}.");
DequantizeToFloat32(type, (byte*)src.ToPointer(), (float*)dst.ToPointer(), numElements);
}
public static unsafe void DequantizeRowToFloat32(int ggmlType, IntPtr src, float* dst, long numElements)
{
var type = (GgmlTensorType)ggmlType;
if (!SupportsDequantization(type))
throw new NotSupportedException($"Pure C# backend does not support GGUF tensor type {type}.");
DequantizeToFloat32(type, (byte*)src.ToPointer(), dst, numElements);
}
/// <summary>
/// Quantize a contiguous run of <paramref name="numElements"/> F32 values into a
/// block-quantized buffer (Q4_0 or Q8_0), matching ggml's reference block layout
/// (fp16 block scale + packed quants). Used by the managed KV-cache write path so
/// that block-quantized caches (<c>--kv-cache-dtype q4_0/q8_0</c>) can be appended
/// to from the per-op prefill path; the bytes it produces are dequantized
/// identically by ggml's native kernels on the subsequent fused decode read.
/// <paramref name="numElements"/> must be a multiple of the 32-element block size.
/// </summary>
public static unsafe void QuantizeRowFromFloat32(int ggmlType, float* src, IntPtr dst, long numElements)
{
var type = (GgmlTensorType)ggmlType;
byte* d = (byte*)dst.ToPointer();
switch (type)
{
case GgmlTensorType.Q4_0:
if (numElements % QK4_0 != 0)
throw new NotSupportedException($"Q4_0 requires {QK4_0}-element alignment, got {numElements}.");
QuantizeF32ToQ4_0(src, d, (int)numElements);
break;
case GgmlTensorType.Q8_0:
if (numElements % QK8_0 != 0)
throw new NotSupportedException($"Q8_0 requires {QK8_0}-element alignment, got {numElements}.");
QuantizeF32ToQ8_0(src, d, (int)numElements);
break;
default:
throw new NotSupportedException($"QuantizeRowFromFloat32 does not support GGUF tensor type {type}.");
}
}
public static unsafe void QuantizeRowFromFloat32(int ggmlType, float[] src, int srcOffset, byte[] dst, int dstOffset, long numElements)
{
fixed (float* s = src)
fixed (byte* d = dst)
{
QuantizeRowFromFloat32(ggmlType, s + srcOffset, (IntPtr)(d + dstOffset), numElements);
}
}
public static unsafe void DotRowBatchToFloat32(int ggmlType, byte[] src, int srcOffset,
float[] inputs, int inputOffset, int inputRowStride, int rowCount, long numElements,
float[] outputs, int outputOffset)
{
var type = (GgmlTensorType)ggmlType;
if (!SupportsDequantization(type))
throw new NotSupportedException($"Pure C# backend does not support GGUF tensor type {type}.");
fixed (byte* srcBase = src)
fixed (float* inputBase = inputs)
fixed (float* outputBase = outputs)
{
DotRowBatchToFloat32(
ggmlType,
(IntPtr)(srcBase + srcOffset),
inputBase + inputOffset,
inputRowStride,
rowCount,
numElements,
outputBase + outputOffset);
}
}
public static unsafe void DotRowBatchToFloat32(int ggmlType, IntPtr src, float* inputs,
int inputRowStride, int rowCount, long numElements, float* outputs)
{
var type = (GgmlTensorType)ggmlType;
if (!SupportsDequantization(type))
throw new NotSupportedException($"Pure C# backend does not support GGUF tensor type {type}.");
if (rowCount < 1)
throw new ArgumentOutOfRangeException(nameof(rowCount));
if (inputRowStride < numElements)
throw new ArgumentOutOfRangeException(nameof(inputRowStride));
long blockSize = GgufFile.GetBlockSize(type);
if (numElements % blockSize != 0)
throw new NotSupportedException($"Tensor type {type} requires row length aligned to {blockSize}, got {numElements}.");
for (int row = 0; row < rowCount; row++)
outputs[row] = 0.0f;
if (type == GgmlTensorType.F32)
{
float* weight = (float*)src.ToPointer();
for (int row = 0; row < rowCount; row++)
outputs[row] = DotFloat(inputs + (long)row * inputRowStride, weight, (int)numElements);
return;
}
float* scratch = stackalloc float[QK_K];
byte* chunkPtr = (byte*)src.ToPointer();
long elementOffset = 0;
while (elementOffset < numElements)
{
int chunkElements = GetDotChunkSize(type, numElements - elementOffset);
DequantizeToFloat32(type, chunkPtr, scratch, chunkElements);
float* inputChunk = inputs + elementOffset;
for (int row = 0; row < rowCount; row++)
{
outputs[row] += DotFloat(inputChunk + (long)row * inputRowStride, scratch, chunkElements);
}
chunkPtr += GetDotChunkBytes(type, chunkElements);
elementOffset += chunkElements;
}
}
public static unsafe bool TryAddmmQuantizedToFloat32(
int ggmlType,
IntPtr weights,
long ne0,
long ne1,
float* input,
int inputRowStride,
int rowCount,
float* output,
int outputRowStride)
{
var type = (GgmlTensorType)ggmlType;
if (ne0 > int.MaxValue || ne1 > int.MaxValue)
return false;
if (!TryGetDirectMatMulPlan(type, (int)ne0, out ActivationQuantKind activationKind, out int activationRowBytes))
return false;
if (weights == IntPtr.Zero)
throw new ArgumentException("Quantized weights pointer cannot be null.", nameof(weights));
if (inputRowStride < ne0)
throw new ArgumentOutOfRangeException(nameof(inputRowStride));
if (outputRowStride < ne1)
throw new ArgumentOutOfRangeException(nameof(outputRowStride));
long totalActivationBytes = (long)rowCount * activationRowBytes;
if (totalActivationBytes > int.MaxValue)
return false;
byte[] rented = ArrayPool<byte>.Shared.Rent((int)totalActivationBytes);
try
{
fixed (byte* activationBase = rented)
{
for (int row = 0; row < rowCount; row++)
{
byte* dst = activationBase + (long)row * activationRowBytes;
float* src = input + (long)row * inputRowStride;
QuantizeActivation(src, dst, (int)ne0, activationKind);
}
byte* weightBase = (byte*)weights.ToPointer();
int weightRowBytes = (int)RowSize(ggmlType, ne0);
int outDim = (int)ne1;
int inDim = (int)ne0;
nint activationAddress = (nint)activationBase;
nint weightAddress = (nint)weightBase;
nint outputAddress = (nint)output;
void ComputeColumnRange(int startCol, int endCol)
{
byte* activationPtr = (byte*)activationAddress;
byte* weightPtr = (byte*)weightAddress;
float* outputPtr = (float*)outputAddress;
for (int col = startCol; col < endCol; col++)
{
byte* weightRow = weightPtr + (long)col * weightRowBytes;
for (int row = 0; row < rowCount; row++)
{
byte* activationRow = activationPtr + (long)row * activationRowBytes;
outputPtr[(long)row * outputRowStride + col] =
DotQuantized(type, weightRow, activationRow, inDim);
}
}
}
bool useParallel = outDim >= 128 && (long)rowCount * outDim >= 512 && Environment.ProcessorCount > 1;
if (useParallel)
{
Parallel.For(0, outDim, col => ComputeColumnRange(col, col + 1));
}
else
{
ComputeColumnRange(0, outDim);
}
}
}
finally
{
ArrayPool<byte>.Shared.Return(rented);
}
return true;
}
public static unsafe bool TryAddmmQuantizedToFloat32(
int ggmlType,
byte[] weights,
int weightsOffset,
long ne0,
long ne1,
float[] input,
int inputOffset,
int inputRowStride,
int rowCount,
float[] output,
int outputOffset,
int outputRowStride)
{
if (weights == null)
throw new ArgumentNullException(nameof(weights));
if (input == null)
throw new ArgumentNullException(nameof(input));
if (output == null)
throw new ArgumentNullException(nameof(output));
fixed (byte* weightPtr = weights)
fixed (float* inputPtr = input)
fixed (float* outputPtr = output)
{
return TryAddmmQuantizedToFloat32(
ggmlType,
(IntPtr)(weightPtr + weightsOffset),
ne0,
ne1,
inputPtr + inputOffset,
inputRowStride,
rowCount,
outputPtr + outputOffset,
outputRowStride);
}
}
private enum ActivationQuantKind
{
Q8_0,
Q8_1,
Q8_K,
}
private static bool TryGetDirectMatMulPlan(
GgmlTensorType type,
int elementCount,
out ActivationQuantKind activationKind,
out int activationRowBytes)
{
activationKind = default;
activationRowBytes = 0;
switch (type)
{
case GgmlTensorType.Q4_0:
case GgmlTensorType.Q5_0:
case GgmlTensorType.Q8_0:
case GgmlTensorType.Q8_1:
if (elementCount % QK8_0 != 0)
return false;
activationKind = ActivationQuantKind.Q8_0;
activationRowBytes = elementCount / QK8_0 * Q8_0BlockBytes;
return true;
case GgmlTensorType.Q4_1:
case GgmlTensorType.Q5_1:
if (elementCount % QK8_1 != 0)
return false;
activationKind = ActivationQuantKind.Q8_1;
activationRowBytes = elementCount / QK8_1 * Q8_1BlockBytes;
return true;
case GgmlTensorType.Q4_K:
case GgmlTensorType.Q5_K:
case GgmlTensorType.Q6_K:
if (elementCount % QK_K != 0)
return false;
activationKind = ActivationQuantKind.Q8_K;
activationRowBytes = elementCount / QK_K * Q8_KBlockBytes;
return true;
default:
return false;
}
}
private static unsafe void QuantizeActivation(float* src, byte* dst, int elementCount, ActivationQuantKind kind)
{
switch (kind)
{
case ActivationQuantKind.Q8_0:
QuantizeF32ToQ8_0(src, dst, elementCount);
return;
case ActivationQuantKind.Q8_1:
QuantizeF32ToQ8_1(src, dst, elementCount);
return;
case ActivationQuantKind.Q8_K:
QuantizeF32ToQ8_K(src, dst, elementCount);
return;
default:
throw new ArgumentOutOfRangeException(nameof(kind), kind, null);
}
}
private static unsafe float DotQuantized(GgmlTensorType type, byte* weightRow, byte* activationRow, int elementCount)
{
return type switch
{
GgmlTensorType.Q4_0 => VecDotQ4_0Q8_0(weightRow, activationRow, elementCount / QK4_0),
GgmlTensorType.Q4_1 => VecDotQ4_1Q8_1(weightRow, activationRow, elementCount / QK4_1),
GgmlTensorType.Q5_0 => VecDotQ5_0Q8_0(weightRow, activationRow, elementCount / QK5_0),
GgmlTensorType.Q5_1 => VecDotQ5_1Q8_1(weightRow, activationRow, elementCount / QK5_1),
GgmlTensorType.Q8_0 => VecDotQ8_0Q8_0(weightRow, activationRow, elementCount / QK8_0),
GgmlTensorType.Q8_1 => VecDotQ8_1Q8_0(weightRow, activationRow, elementCount / QK8_1),
GgmlTensorType.Q4_K => VecDotQ4_KQ8_K(weightRow, activationRow, elementCount / QK_K),
GgmlTensorType.Q5_K => VecDotQ5_KQ8_K(weightRow, activationRow, elementCount / QK_K),
GgmlTensorType.Q6_K => VecDotQ6_KQ8_K(weightRow, activationRow, elementCount / QK_K),
_ => throw new NotSupportedException($"Direct managed quantized matmul does not support {type}."),
};
}
private static unsafe void DequantizeToFloat32(GgmlTensorType type, byte* src, float* dst, long numElements)
{
switch (type)
{
case GgmlTensorType.F32:
Buffer.MemoryCopy(src, dst, numElements * sizeof(float), numElements * sizeof(float));
return;
case GgmlTensorType.F16:
DequantizeF16(src, dst, numElements);
return;
case GgmlTensorType.BF16:
DequantizeBf16(src, dst, numElements);
return;
case GgmlTensorType.I8:
DequantizeI8(src, dst, numElements);
return;
case GgmlTensorType.I16:
DequantizeI16(src, dst, numElements);
return;
case GgmlTensorType.I32:
DequantizeI32(src, dst, numElements);
return;
case GgmlTensorType.I64:
DequantizeI64(src, dst, numElements);
return;
case GgmlTensorType.F64:
DequantizeF64(src, dst, numElements);
return;
case GgmlTensorType.Q4_0:
DequantizeQ40(src, dst, numElements);
return;
case GgmlTensorType.Q4_1:
DequantizeQ41(src, dst, numElements);
return;
case GgmlTensorType.Q5_0:
DequantizeQ50(src, dst, numElements);
return;
case GgmlTensorType.Q5_1:
DequantizeQ51(src, dst, numElements);
return;
case GgmlTensorType.Q8_0:
DequantizeQ80(src, dst, numElements);
return;
case GgmlTensorType.Q8_1:
DequantizeQ81(src, dst, numElements);
return;
case GgmlTensorType.Q2_K:
DequantizeQ2K(src, dst, numElements);
return;
case GgmlTensorType.Q3_K:
DequantizeQ3K(src, dst, numElements);
return;
case GgmlTensorType.Q4_K:
DequantizeQ4K(src, dst, numElements);
return;
case GgmlTensorType.Q5_K:
DequantizeQ5K(src, dst, numElements);
return;
case GgmlTensorType.Q6_K:
DequantizeQ6K(src, dst, numElements);
return;
case GgmlTensorType.IQ4_NL:
DequantizeIq4Nl(src, dst, numElements);
return;
case GgmlTensorType.IQ2_XXS:
DequantizeIq2Xxs(src, dst, numElements);
return;
case GgmlTensorType.IQ2_S:
DequantizeIq2S(src, dst, numElements);
return;
case GgmlTensorType.IQ3_S:
DequantizeIq3S(src, dst, numElements);
return;
case GgmlTensorType.MXFP4:
DequantizeMxfp4(src, dst, numElements);
return;
default:
throw new NotSupportedException($"Pure C# backend does not support GGUF tensor type {type}.");
}
}
private static unsafe void DequantizeF16(byte* src, float* dst, long numElements)
{
for (long i = 0; i < numElements; i++)
dst[i] = HalfToSingle(ReadUInt16(src + i * 2));
}
private static unsafe void DequantizeBf16(byte* src, float* dst, long numElements)
{
for (long i = 0; i < numElements; i++)
{
uint bits = (uint)ReadUInt16(src + i * 2) << 16;
dst[i] = BitConverter.Int32BitsToSingle((int)bits);
}
}
private static unsafe void DequantizeI8(byte* src, float* dst, long numElements)
{
for (long i = 0; i < numElements; i++)
dst[i] = ((sbyte*)src)[i];
}
private static unsafe void DequantizeI16(byte* src, float* dst, long numElements)
{
for (long i = 0; i < numElements; i++)
dst[i] = (short)ReadUInt16(src + i * 2);
}
private static unsafe void DequantizeI32(byte* src, float* dst, long numElements)
{
for (long i = 0; i < numElements; i++)
dst[i] = ReadInt32(src + i * 4);
}
private static unsafe void DequantizeI64(byte* src, float* dst, long numElements)
{
for (long i = 0; i < numElements; i++)
dst[i] = ReadInt64(src + i * 8);
}
private static unsafe void DequantizeF64(byte* src, float* dst, long numElements)
{
for (long i = 0; i < numElements; i++)
dst[i] = (float)ReadDouble(src + i * 8);
}
private static unsafe void DequantizeQ40(byte* src, float* dst, long numElements)
{
if (numElements % QK4_0 != 0)
throw new NotSupportedException($"Q4_0 requires {QK4_0}-element alignment, got {numElements}.");
int nb = (int)(numElements / QK4_0);
for (int i = 0; i < nb; i++)
{
byte* block = src + i * (2 + QK4_0 / 2);
float d = HalfToSingle(ReadUInt16(block));
byte* qs = block + 2;
float* y = dst + i * QK4_0;
for (int j = 0; j < QK4_0 / 2; j++)
{
int x0 = (qs[j] & 0x0F) - 8;
int x1 = (qs[j] >> 4) - 8;
y[j] = x0 * d;
y[j + QK4_0 / 2] = x1 * d;
}
}
}
private static unsafe void DequantizeQ41(byte* src, float* dst, long numElements)
{
if (numElements % QK4_1 != 0)
throw new NotSupportedException($"Q4_1 requires {QK4_1}-element alignment, got {numElements}.");
int nb = (int)(numElements / QK4_1);
for (int i = 0; i < nb; i++)
{
byte* block = src + i * (4 + QK4_1 / 2);
float d = HalfToSingle(ReadUInt16(block));
float m = HalfToSingle(ReadUInt16(block + 2));
byte* qs = block + 4;
float* y = dst + i * QK4_1;
for (int j = 0; j < QK4_1 / 2; j++)
{
int x0 = qs[j] & 0x0F;
int x1 = qs[j] >> 4;
y[j] = x0 * d + m;
y[j + QK4_1 / 2] = x1 * d + m;
}
}
}
private static unsafe void DequantizeQ50(byte* src, float* dst, long numElements)
{
if (numElements % QK5_0 != 0)
throw new NotSupportedException($"Q5_0 requires {QK5_0}-element alignment, got {numElements}.");
int blockBytes = 2 + 4 + QK5_0 / 2;
int nb = (int)(numElements / QK5_0);
for (int i = 0; i < nb; i++)
{
byte* block = src + i * blockBytes;
float d = HalfToSingle(ReadUInt16(block));
uint qh = ReadUInt32(block + 2);
byte* qs = block + 6;
float* y = dst + i * QK5_0;
for (int j = 0; j < QK5_0 / 2; j++)
{
int xh0 = (int)(((qh >> j) << 4) & 0x10);
int xh1 = (int)((qh >> (j + 12)) & 0x10);
int x0 = ((qs[j] & 0x0F) | xh0) - 16;
int x1 = ((qs[j] >> 4) | xh1) - 16;
y[j] = x0 * d;
y[j + QK5_0 / 2] = x1 * d;
}
}
}
private static unsafe void DequantizeQ51(byte* src, float* dst, long numElements)
{
if (numElements % QK5_1 != 0)
throw new NotSupportedException($"Q5_1 requires {QK5_1}-element alignment, got {numElements}.");
int blockBytes = 4 + 4 + QK5_1 / 2;
int nb = (int)(numElements / QK5_1);
for (int i = 0; i < nb; i++)
{
byte* block = src + i * blockBytes;
float d = HalfToSingle(ReadUInt16(block));
float m = HalfToSingle(ReadUInt16(block + 2));
uint qh = ReadUInt32(block + 4);
byte* qs = block + 8;
float* y = dst + i * QK5_1;
for (int j = 0; j < QK5_1 / 2; j++)
{
int xh0 = (int)(((qh >> j) << 4) & 0x10);
int xh1 = (int)((qh >> (j + 12)) & 0x10);
int x0 = (qs[j] & 0x0F) | xh0;
int x1 = (qs[j] >> 4) | xh1;
y[j] = x0 * d + m;
y[j + QK5_1 / 2] = x1 * d + m;
}
}
}
private static unsafe void DequantizeQ80(byte* src, float* dst, long numElements)
{
if (numElements % QK8_0 != 0)
throw new NotSupportedException($"Q8_0 requires {QK8_0}-element alignment, got {numElements}.");
int blockBytes = 2 + QK8_0;
int nb = (int)(numElements / QK8_0);
for (int i = 0; i < nb; i++)
{
byte* block = src + i * blockBytes;
float d = HalfToSingle(ReadUInt16(block));
sbyte* qs = (sbyte*)(block + 2);
float* y = dst + i * QK8_0;
for (int j = 0; j < QK8_0; j++)
y[j] = qs[j] * d;
}
}
private static unsafe void DequantizeQ81(byte* src, float* dst, long numElements)
{
if (numElements % QK8_1 != 0)
throw new NotSupportedException($"Q8_1 requires {QK8_1}-element alignment, got {numElements}.");
int blockBytes = 4 + QK8_1;
int nb = (int)(numElements / QK8_1);
for (int i = 0; i < nb; i++)
{
byte* block = src + i * blockBytes;
float d = HalfToSingle(ReadUInt16(block));
sbyte* qs = (sbyte*)(block + 4);
float* y = dst + i * QK8_1;
for (int j = 0; j < QK8_1; j++)
y[j] = qs[j] * d;
}
}
private static unsafe void DequantizeQ4K(byte* src, float* dst, long numElements)
{
if (numElements % QK_K != 0)
throw new NotSupportedException($"Q4_K requires {QK_K}-element alignment, got {numElements}.");
int blockBytes = 4 + K_SCALE_SIZE + QK_K / 2;
int nb = (int)(numElements / QK_K);
for (int i = 0; i < nb; i++)
{
byte* block = src + i * blockBytes;
float d = HalfToSingle(ReadUInt16(block));
float min = HalfToSingle(ReadUInt16(block + 2));
byte* scales = block + 4;
byte* q = block + 4 + K_SCALE_SIZE;
float* y = dst + i * QK_K;
int isIdx = 0;
for (int j = 0; j < QK_K; j += 64)
{
GetScaleMinK4(isIdx, scales, out byte sc1, out byte m1q);
GetScaleMinK4(isIdx + 1, scales, out byte sc2, out byte m2q);
float d1 = d * sc1;
float d2 = d * sc2;
float m1 = min * m1q;
float m2 = min * m2q;
for (int l = 0; l < 32; l++)
y[j + l] = d1 * (q[l] & 0x0F) - m1;
for (int l = 0; l < 32; l++)
y[j + l + 32] = d2 * (q[l] >> 4) - m2;
q += 32;
isIdx += 2;
}
}
}
private static unsafe void DequantizeQ5K(byte* src, float* dst, long numElements)
{
if (numElements % QK_K != 0)
throw new NotSupportedException($"Q5_K requires {QK_K}-element alignment, got {numElements}.");
int blockBytes = 4 + K_SCALE_SIZE + QK_K / 8 + QK_K / 2;
int nb = (int)(numElements / QK_K);
for (int i = 0; i < nb; i++)
{
byte* block = src + i * blockBytes;
float d = HalfToSingle(ReadUInt16(block));
float min = HalfToSingle(ReadUInt16(block + 2));
byte* scales = block + 4;
byte* qh = block + 4 + K_SCALE_SIZE;
byte* ql = qh + QK_K / 8;
float* y = dst + i * QK_K;
int isIdx = 0;
byte u1 = 1;
byte u2 = 2;
for (int j = 0; j < QK_K; j += 64)
{
GetScaleMinK4(isIdx, scales, out byte sc1, out byte m1q);
GetScaleMinK4(isIdx + 1, scales, out byte sc2, out byte m2q);
float d1 = d * sc1;
float d2 = d * sc2;
float m1 = min * m1q;
float m2 = min * m2q;
for (int l = 0; l < 32; l++)
y[j + l] = d1 * ((ql[l] & 0x0F) + ((qh[l] & u1) != 0 ? 16 : 0)) - m1;
for (int l = 0; l < 32; l++)
y[j + l + 32] = d2 * ((ql[l] >> 4) + ((qh[l] & u2) != 0 ? 16 : 0)) - m2;
ql += 32;
isIdx += 2;
u1 <<= 2;
u2 <<= 2;
}
}
}
private static unsafe void DequantizeQ6K(byte* src, float* dst, long numElements)
{
if (numElements % QK_K != 0)
throw new NotSupportedException($"Q6_K requires {QK_K}-element alignment, got {numElements}.");
int blockBytes = QK_K / 2 + QK_K / 4 + QK_K / 16 + 2;
int nb = (int)(numElements / QK_K);
for (int i = 0; i < nb; i++)
{
byte* block = src + i * blockBytes;
byte* ql = block;
byte* qh = ql + QK_K / 2;
sbyte* scales = (sbyte*)(qh + QK_K / 4);
float d = HalfToSingle(ReadUInt16((byte*)(scales + QK_K / 16)));
float* y = dst + i * QK_K;
for (int n = 0; n < QK_K; n += 128)
{
for (int l = 0; l < 32; l++)
{
int isIdx = l / 16;
sbyte q1 = (sbyte)(((ql[l] & 0x0F) | (((qh[l] >> 0) & 0x03) << 4)) - 32);
sbyte q2 = (sbyte)(((ql[l + 32] & 0x0F) | (((qh[l] >> 2) & 0x03) << 4)) - 32);
sbyte q3 = (sbyte)(((ql[l] >> 4) | (((qh[l] >> 4) & 0x03) << 4)) - 32);
sbyte q4 = (sbyte)(((ql[l + 32] >> 4) | (((qh[l] >> 6) & 0x03) << 4)) - 32);
y[n + l] = d * scales[isIdx] * q1;
y[n + l + 32] = d * scales[isIdx + 2] * q2;
y[n + l + 64] = d * scales[isIdx + 4] * q3;
y[n + l + 96] = d * scales[isIdx + 6] * q4;
}
ql += 64;
qh += 32;
scales += 8;
}
}
}
// Q2_K: 16 sub-blocks of 16. Ported verbatim from ggml dequantize_row_q2_K.
// block layout: scales[16] | qs[64] | d(fp16) | dmin(fp16) = 84 bytes.
private static unsafe void DequantizeQ2K(byte* src, float* dst, long numElements)
{
if (numElements % QK_K != 0)
throw new NotSupportedException($"Q2_K requires {QK_K}-element alignment, got {numElements}.");
int blockBytes = QK_K / 16 + QK_K / 4 + 2 + 2; // 16 + 64 + 2 + 2 = 84
int nb = (int)(numElements / QK_K);
for (int i = 0; i < nb; i++)
{
byte* block = src + i * blockBytes;
byte* scales = block; // [16]
byte* q = block + QK_K / 16; // qs [64]
float d = HalfToSingle(ReadUInt16(block + QK_K / 16 + QK_K / 4)); // +80
float min = HalfToSingle(ReadUInt16(block + QK_K / 16 + QK_K / 4 + 2)); // +82
float* y = dst + i * QK_K;
int si = 0;
for (int n = 0; n < QK_K; n += 128)
{
int shift = 0;
for (int j = 0; j < 4; ++j)
{
byte sc = scales[si++];
float dl = d * (sc & 0xF), ml = min * (sc >> 4);
for (int l = 0; l < 16; ++l) *y++ = dl * ((sbyte)((q[l] >> shift) & 3)) - ml;
sc = scales[si++];
dl = d * (sc & 0xF); ml = min * (sc >> 4);
for (int l = 0; l < 16; ++l) *y++ = dl * ((sbyte)((q[l + 16] >> shift) & 3)) - ml;
shift += 2;
}
q += 32;
}
}
}
// Q3_K: 16 sub-blocks of 16, 6-bit scales packed in 12 bytes, high bit in hmask.
// Ported verbatim from ggml dequantize_row_q3_K.
// block layout: hmask[32] | qs[64] | scales[12] | d(fp16) = 110 bytes.
private static unsafe void DequantizeQ3K(byte* src, float* dst, long numElements)
{
if (numElements % QK_K != 0)
throw new NotSupportedException($"Q3_K requires {QK_K}-element alignment, got {numElements}.");
const uint kmask1 = 0x03030303, kmask2 = 0x0f0f0f0f;
int blockBytes = QK_K / 8 + QK_K / 4 + 12 + 2; // 32 + 64 + 12 + 2 = 110
int nb = (int)(numElements / QK_K);
uint* aux = stackalloc uint[4];
sbyte* scales = (sbyte*)aux;
for (int i = 0; i < nb; i++)
{
byte* block = src + i * blockBytes;
byte* hm = block; // hmask [32]
byte* q = block + QK_K / 8; // qs [64]
byte* sc = block + QK_K / 8 + QK_K / 4; // scales [12]
float dAll = HalfToSingle(ReadUInt16(sc + 12)); // d at +108
aux[0] = ReadUInt32(sc + 0);
aux[1] = ReadUInt32(sc + 4);
aux[2] = ReadUInt32(sc + 8);
uint tmp = aux[2];
aux[2] = ((aux[0] >> 4) & kmask2) | (((tmp >> 4) & kmask1) << 4);
aux[3] = ((aux[1] >> 4) & kmask2) | (((tmp >> 6) & kmask1) << 4);
aux[0] = (aux[0] & kmask2) | (((tmp >> 0) & kmask1) << 4);
aux[1] = (aux[1] & kmask2) | (((tmp >> 2) & kmask1) << 4);
float* y = dst + i * QK_K;
int si = 0; byte m = 1; byte* qq = q;
for (int n = 0; n < QK_K; n += 128)
{
int shift = 0;
for (int j = 0; j < 4; ++j)
{
float dl = dAll * (scales[si++] - 32);
for (int l = 0; l < 16; ++l)
*y++ = dl * ((sbyte)((qq[l] >> shift) & 3) - ((hm[l] & m) != 0 ? 0 : 4));
dl = dAll * (scales[si++] - 32);
for (int l = 0; l < 16; ++l)
*y++ = dl * ((sbyte)((qq[l + 16] >> shift) & 3) - ((hm[l + 16] & m) != 0 ? 0 : 4));
shift += 2; m <<= 1;
}
qq += 32;
}
}
}
// IQ2_XXS: 2.0625 bpw codebook quant. Ported verbatim from ggml dequantize_row_iq2_xxs.
// block layout: d(fp16) | qs[32] (uint16) = 66 bytes. grid/sign tables in IQuantGrids.
private static unsafe void DequantizeIq2Xxs(byte* src, float* dst, long numElements)
{
if (numElements % QK_K != 0)
throw new NotSupportedException($"IQ2_XXS requires {QK_K}-element alignment, got {numElements}.");
int blockBytes = 2 + (QK_K / 8) * 2; // 2 + 32*2 = 66
int nb = (int)(numElements / QK_K);
fixed (ulong* grid = IQuantGrids.iq2xxs_grid)
fixed (byte* ksigns = IQuantGrids.ksigns_iq2xs)
fixed (byte* kmask = IQuantGrids.kmask_iq2xs)
{
uint* aux32 = stackalloc uint[2];
byte* aux8 = (byte*)aux32;
for (int i = 0; i < nb; i++)
{
byte* block = src + i * blockBytes;
float d = HalfToSingle(ReadUInt16(block));
byte* qs = block + 2;
float* y = dst + i * QK_K;
for (int ib32 = 0; ib32 < QK_K / 32; ++ib32)
{
byte* p = qs + 8 * ib32; // 4 uint16 = 8 bytes per ib32
aux32[0] = ReadUInt32(p);
aux32[1] = ReadUInt32(p + 4);
float db = d * (0.5f + (aux32[1] >> 28)) * 0.25f;
for (int l = 0; l < 4; ++l)
{
byte* g = (byte*)(grid + aux8[l]);
byte signs = ksigns[(aux32[1] >> (7 * l)) & 127];
for (int j = 0; j < 8; ++j)
y[j] = db * g[j] * ((signs & kmask[j]) != 0 ? -1f : 1f);
y += 8;
}
}
}
}
}
// IQ2_S: 2.5625 bpw codebook quant. Ported verbatim from ggml dequantize_row_iq2_s.
// block layout: d(fp16) | qs[64] | qh[8] | scales[8] = 82 bytes; signs are qs[32..63].
private static unsafe void DequantizeIq2S(byte* src, float* dst, long numElements)
{
if (numElements % QK_K != 0)
throw new NotSupportedException($"IQ2_S requires {QK_K}-element alignment, got {numElements}.");
int blockBytes = 2 + QK_K / 4 + QK_K / 32 + QK_K / 32; // 2 + 64 + 8 + 8 = 82
int nb = (int)(numElements / QK_K);
fixed (ulong* grid = IQuantGrids.iq2s_grid)
fixed (byte* kmask = IQuantGrids.kmask_iq2xs)
{
for (int i = 0; i < nb; i++)
{
byte* block = src + i * blockBytes;
float d = HalfToSingle(ReadUInt16(block));
byte* qs = block + 2; // [64]
byte* qh = qs + QK_K / 4; // [8]
byte* scales = qh + QK_K / 32; // [8]
byte* signs = qs + QK_K / 8; // qs + 32
float* y = dst + i * QK_K;
byte* qsp = qs, signsp = signs;
for (int ib32 = 0; ib32 < QK_K / 32; ++ib32)
{
float db0 = d * (0.5f + (scales[ib32] & 0xf)) * 0.25f;
float db1 = d * (0.5f + (scales[ib32] >> 4)) * 0.25f;
for (int l = 0; l < 4; ++l)
{
float dl = l < 2 ? db0 : db1;