-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgguf_gpu.py
1574 lines (1324 loc) · 68.1 KB
/
gguf_gpu.py
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
# modified from https://github.com/ggerganov/llama.cpp/blob/master/gguf-py/gguf/quants.py
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, Sequence
from math import log2, ceil
from typing import Tuple
from gguf.constants import GGML_QUANT_SIZES, GGMLQuantizationType, QK_K
from gguf.lazy import LazyNumpyTensor
import numpy as np
import torch
def quant_shape_to_byte_shape(
shape: Sequence[int], quant_type: GGMLQuantizationType
) -> tuple[int, ...]:
block_size, type_size = GGML_QUANT_SIZES[quant_type]
if shape[-1] % block_size != 0:
raise ValueError(
f"Quantized tensor row size ({shape[-1]}) is not a multiple of {quant_type.name} block size ({block_size})"
)
return (*shape[:-1], shape[-1] // block_size * type_size)
def quant_shape_from_byte_shape(
shape: Sequence[int], quant_type: GGMLQuantizationType
) -> tuple[int, ...]:
block_size, type_size = GGML_QUANT_SIZES[quant_type]
if shape[-1] % type_size != 0:
raise ValueError(
f"Quantized tensor bytes per row ({shape[-1]}) is not a multiple of {quant_type.name} type size ({type_size})"
)
return (*shape[:-1], shape[-1] // type_size * block_size)
# use GPU to dequantize the entire tensor at once
def _apply_over_grouped_rows(func, arr, otype, oshape, expert_idx=None) -> torch.Tensor:
"""
Applies the given function `func` over the entire input array on the GPU.
This version does not split the input into groups but runs the entire operation at once.
"""
if expert_idx is not None:
arr = arr[expert_idx]
oshape = oshape[1:]
# Convert the input array to a GPU tensor and flatten all but the last dimension.
rows = torch.from_numpy(arr).to("cuda", non_blocking=True).view(-1, arr.shape[-1])
# Apply the function to the entire tensor.
out = func(rows)
# Reshape the output to the desired shape.
return out.view(oshape)
# round away from zero
# ref: https://stackoverflow.com/a/59143326/22827863
def np_roundf(n: np.ndarray) -> np.ndarray:
a = abs(n)
floored = np.floor(a)
b = floored + np.floor(2 * (a - floored))
return np.sign(n) * b
class QuantError(Exception): ...
_type_traits: dict[GGMLQuantizationType, type[__Quant]] = {}
def quantize(data: np.ndarray, qtype: GGMLQuantizationType) -> np.ndarray:
if qtype == GGMLQuantizationType.F32:
return data.astype(np.float32, copy=False)
elif qtype == GGMLQuantizationType.F16:
return data.astype(np.float16, copy=False)
elif (q := _type_traits.get(qtype)) is not None:
return q.quantize(data)
else:
raise NotImplementedError(
f"Quantization for {qtype.name} is not yet implemented"
)
def dequantize(
data: np.ndarray, qtype: GGMLQuantizationType, expert_idx: int | None = None
) -> torch.Tensor:
if qtype == GGMLQuantizationType.F32:
# return data.view(np.float32)
return torch.from_numpy(data).to("cuda")
elif qtype == GGMLQuantizationType.F16:
# return data.view(np.float16).astype(np.float32)
return torch.from_numpy(data.view(np.float16)).float() # .to(torch.float16)
elif (q := _type_traits.get(qtype)) is not None:
return q.dequantize(data, expert_idx).float()
else:
raise NotImplementedError(
f"Dequantization for {qtype.name} is not yet implemented"
)
class __Quant(ABC):
qtype: GGMLQuantizationType
block_size: int
type_size: int
grid: np.ndarray[Any, np.dtype[np.float32]] | None = None
grid_shape: tuple[int, int] = (0, 0)
grid_map: tuple[int | float, ...] = ()
grid_hex: bytes | None = None
def __init__(self):
return TypeError("Quant conversion classes can't have instances")
def __init_subclass__(cls, qtype: GGMLQuantizationType) -> None:
cls.qtype = qtype
cls.block_size, cls.type_size = GGML_QUANT_SIZES[qtype]
cls.__quantize_lazy = LazyNumpyTensor._wrap_fn(
cls.__quantize_array, meta_noop=(np.uint8, cls.__shape_to_bytes)
)
cls.__dequantize_lazy = LazyNumpyTensor._wrap_fn(
cls.__dequantize_array, meta_noop=(np.float32, cls.__shape_from_bytes)
)
# assert qtype not in _type_traits #changed
_type_traits[qtype] = cls
@classmethod
def init_grid(cls):
if cls.grid is not None or cls.grid_hex is None:
return
bits_per_elem = ceil(log2(len(cls.grid_map)))
assert bits_per_elem != 0, cls.qtype.name
elems_per_byte = 8 // bits_per_elem
grid = np.frombuffer(cls.grid_hex, dtype=np.uint8)
# decode hexadecimal chars from grid
grid = grid.reshape((-1, 2))
grid = (np.where(grid > 0x40, grid + 9, grid) & 0x0F) << np.array(
[4, 0], dtype=np.uint8
).reshape((1, 2))
grid = grid[..., 0] | grid[..., 1]
# unpack the grid values
grid = grid.reshape((-1, 1)) >> np.array(
[i for i in range(0, 8, 8 // elems_per_byte)], dtype=np.uint8
).reshape((1, elems_per_byte))
grid = (grid & ((1 << bits_per_elem) - 1)).reshape((-1, 1))
grid_map = np.array(cls.grid_map, dtype=np.float32).reshape((1, -1))
grid = np.take_along_axis(grid_map, grid, axis=-1)
cls.grid = grid.reshape((1, 1, *cls.grid_shape))
cls.grid = torch.from_numpy(cls.grid).to(torch.float32).cuda()
@classmethod
@abstractmethod
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
raise NotImplementedError
@classmethod
@abstractmethod
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
raise NotImplementedError
@classmethod
def quantize_rows(cls, rows: np.ndarray) -> np.ndarray:
rows = rows.astype(np.float32, copy=False)
shape = rows.shape
n_blocks = rows.size // cls.block_size
blocks = rows.reshape((n_blocks, cls.block_size))
blocks = cls.quantize_blocks(blocks)
assert blocks.dtype == np.uint8
assert blocks.shape[-1] == cls.type_size
return blocks.reshape(cls.__shape_to_bytes(shape))
@classmethod
def dequantize_rows(cls, rows: np.ndarray) -> np.ndarray:
# rows = rows.view(np.uint8)
rows = rows.view(torch.uint8)
shape = rows.shape
n_blocks = rows.numel() // cls.type_size
blocks = rows.view((n_blocks, cls.type_size))
blocks = cls.dequantize_blocks(blocks)
# assert blocks.dtype == np.float32
assert blocks.shape[-1] == cls.block_size
return blocks.view(cls.__shape_from_bytes(shape))
@classmethod
def __shape_to_bytes(cls, shape: Sequence[int]):
return quant_shape_to_byte_shape(shape, cls.qtype)
@classmethod
def __shape_from_bytes(cls, shape: Sequence[int]):
return quant_shape_from_byte_shape(shape, cls.qtype)
@classmethod
def __quantize_array(cls, array: np.ndarray) -> np.ndarray:
return _apply_over_grouped_rows(
cls.quantize_rows,
arr=array,
otype=np.uint8,
oshape=cls.__shape_to_bytes(array.shape),
)
@classmethod
def __dequantize_array(
cls, array: np.ndarray, expert_idx: int | None = None
) -> torch.Tensor:
cls.init_grid()
return _apply_over_grouped_rows(
cls.dequantize_rows,
arr=array,
otype=np.float32,
oshape=cls.__shape_from_bytes(array.shape),
expert_idx=expert_idx,
)
@classmethod
def __quantize_lazy(cls, lazy_tensor: LazyNumpyTensor, /) -> Any:
pass
@classmethod
def __dequantize_lazy(cls, lazy_tensor: LazyNumpyTensor, /) -> Any:
pass
@classmethod
def can_quantize(cls, tensor: np.ndarray | LazyNumpyTensor) -> bool:
return tensor.shape[-1] % cls.block_size == 0
@classmethod
def quantize(cls, tensor: np.ndarray | LazyNumpyTensor) -> np.ndarray:
if not cls.can_quantize(tensor):
raise QuantError(
f"Can't quantize tensor with shape {tensor.shape} to {cls.qtype.name}"
)
if isinstance(tensor, LazyNumpyTensor):
return cls.__quantize_lazy(tensor)
else:
return cls.__quantize_array(tensor)
@classmethod
def dequantize(
cls, tensor: np.ndarray | LazyNumpyTensor, expert_idx: int | None = None
) -> torch.Tensor:
if isinstance(tensor, LazyNumpyTensor):
return cls.__dequantize_lazy(tensor)
else:
return cls.__dequantize_array(tensor, expert_idx)
class BF16(__Quant, qtype=GGMLQuantizationType.BF16):
@classmethod
# same as ggml_compute_fp32_to_bf16 in ggml-impl.h
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
n = blocks.view(np.uint32)
# force nan to quiet
n = np.where(
(n & 0x7FFFFFFF) > 0x7F800000,
(n & np.uint32(0xFFFF0000)) | np.uint32(64 << 16),
n,
)
# round to nearest even
n = (np.uint64(n) + (0x7FFF + ((n >> 16) & 1))) >> 16
return n.astype(np.uint16).view(np.uint8)
@classmethod
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
return (blocks.view(np.int16).astype(np.int32) << 16).view(np.float32)
class Q4_0(__Quant, qtype=GGMLQuantizationType.Q4_0):
@classmethod
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
n_blocks = blocks.shape[0]
imax = abs(blocks).argmax(axis=-1, keepdims=True)
max_vals = np.take_along_axis(blocks, imax, axis=-1)
d = max_vals / -8
with np.errstate(divide="ignore"):
id = np.where(d == 0, 0, 1 / d)
# Note: The reference rounding here is “cursed” (see original comment)
qs = (
np.trunc((np.float64(blocks) * np.float64(id)) + 8.5)
.astype(np.uint8)
.clip(0, 15)
)
qs = qs.reshape((n_blocks, 2, cls.block_size // 2))
qs = qs[..., 0, :] | (qs[..., 1, :] << np.uint8(4))
d = d.astype(np.float16).view(np.uint8)
return np.concatenate([d, qs], axis=-1)
@classmethod
def dequantize_blocks(cls, blocks: torch.Tensor) -> torch.Tensor:
"""
Expects a tensor `blocks` of shape (n_blocks, 2 + block_size//2) with dtype torch.uint8.
The first 2 bytes represent the float16 'd' value (stored as raw bytes),
and the remaining bytes store packed 4-bit quantized values.
"""
n_blocks = blocks.size(0)
# Split into the first 2 bytes (d) and the rest (qs)
d, qs = torch.split(blocks, [2, blocks.size(1) - 2], dim=1)
# --- Reinterpret the first two uint8 bytes as a float16 ---
# (Since PyTorch lacks a direct bitcast, we use NumPy for the reinterpretation)
d = d.view(torch.float16).to(torch.float32)
# --- Unpack the quantized values ---
# In the original NumPy code, qs is reshaped to (n_blocks, 1, 1, block_size//2)
qs = qs.view(n_blocks, 1, 1, cls.block_size // 2)
# Create a tensor for the shift amounts: one nibble is at shift 0 and the other at shift 4.
shift = torch.tensor([0, 4], dtype=torch.uint8, device=blocks.device).view(
1, 1, 2, 1
)
# Expand qs so that it broadcasts over the two shifts.
qs = qs.expand(-1, 1, 2, -1) # shape becomes (n_blocks, 1, 2, block_size//2)
qs = qs >> shift # perform element-wise right-shift by 0 and 4 respectively
qs = qs & 0x0F # mask out only the lower 4 bits from each nibble
# Reshape qs to (n_blocks, block_size) and convert to signed integers, then subtract 8
qs = qs.view(n_blocks, -1).to(torch.int8) - 8
# Multiply the scaling factor d (broadcast along the quantized values)
# d *= qs.to(torch.float32)
qs = qs.to(torch.float32)
qs *= d
return qs
class Q4_1(__Quant, qtype=GGMLQuantizationType.Q4_1):
@classmethod
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
n_blocks = blocks.shape[0]
max = blocks.max(axis=-1, keepdims=True)
min = blocks.min(axis=-1, keepdims=True)
d = (max - min) / 15
with np.errstate(divide="ignore"):
id = np.where(d == 0, 0, 1 / d)
qs = (
np.trunc((blocks - min) * id + np.float32(0.5), dtype=np.float32)
.astype(np.uint8)
.clip(0, 15)
)
qs = qs.reshape((n_blocks, 2, cls.block_size // 2))
qs = qs[..., 0, :] | (qs[..., 1, :] << np.uint8(4))
d = d.astype(np.float16).view(np.uint8)
m = min.astype(np.float16).view(np.uint8)
return np.concatenate([d, m, qs], axis=-1)
@classmethod
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
n_blocks = blocks.shape[0]
d, rest = np.hsplit(blocks, [2])
m, qs = np.hsplit(rest, [2])
d = d.view(np.float16).astype(np.float32)
m = m.view(np.float16).astype(np.float32)
qs = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array(
[0, 4], dtype=np.uint8
).reshape((1, 1, 2, 1))
qs = (qs & np.uint8(0x0F)).reshape((n_blocks, -1)).astype(np.float32)
return (d * qs) + m
class Q5_0(__Quant, qtype=GGMLQuantizationType.Q5_0):
@classmethod
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
n_blocks = blocks.shape[0]
imax = abs(blocks).argmax(axis=-1, keepdims=True)
max = np.take_along_axis(blocks, imax, axis=-1)
d = max / -16
with np.errstate(divide="ignore"):
id = np.where(d == 0, 0, 1 / d)
# FIXME: Q5_0's reference rounding is cursed and depends on FMA
q = (
np.trunc(
(np.float64(blocks) * np.float64(id)) + np.float64(16.5),
dtype=np.float32,
)
.astype(np.uint8)
.clip(0, 31)
)
qs = q.reshape((n_blocks, 2, cls.block_size // 2))
qs = (qs[..., 0, :] & np.uint8(0x0F)) | (qs[..., 1, :] << np.uint8(4))
qh = np.packbits(
q.reshape((n_blocks, 1, 32)) >> np.uint8(4), axis=-1, bitorder="little"
).reshape(n_blocks, 4)
d = d.astype(np.float16).view(np.uint8)
return np.concatenate([d, qh, qs], axis=-1)
@classmethod
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
n_blocks = blocks.shape[0]
d, rest = np.hsplit(blocks, [2])
qh, qs = np.hsplit(rest, [4])
d = d.view(np.float16).astype(np.float32)
qh = qh.view(np.uint32)
qh = qh.reshape((n_blocks, 1)) >> np.array(
[i for i in range(32)], dtype=np.uint32
).reshape((1, 32))
ql = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array(
[0, 4], dtype=np.uint8
).reshape((1, 1, 2, 1))
qh = (qh & np.uint32(0x01)).astype(np.uint8)
ql = (ql & np.uint8(0x0F)).reshape((n_blocks, -1))
qs = (ql | (qh << np.uint8(4))).astype(np.int8) - np.int8(16)
return d * qs.astype(np.float32)
class Q5_1(__Quant, qtype=GGMLQuantizationType.Q5_1):
@classmethod
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
n_blocks = blocks.shape[0]
max = blocks.max(axis=-1, keepdims=True)
min = blocks.min(axis=-1, keepdims=True)
d = (max - min) / 31
with np.errstate(divide="ignore"):
id = np.where(d == 0, 0, 1 / d)
q = (
np.trunc((blocks - min) * id + np.float32(0.5), dtype=np.float32)
.astype(np.uint8)
.clip(0, 31)
)
qs = q.reshape((n_blocks, 2, cls.block_size // 2))
qs = (qs[..., 0, :] & np.uint8(0x0F)) | (qs[..., 1, :] << np.uint8(4))
qh = np.packbits(
q.reshape((n_blocks, 1, 32)) >> np.uint8(4), axis=-1, bitorder="little"
).reshape(n_blocks, 4)
d = d.astype(np.float16).view(np.uint8)
m = min.astype(np.float16).view(np.uint8)
return np.concatenate([d, m, qh, qs], axis=-1)
@classmethod
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
n_blocks = blocks.shape[0]
d, rest = np.hsplit(blocks, [2])
m, rest = np.hsplit(rest, [2])
qh, qs = np.hsplit(rest, [4])
d = d.view(np.float16).astype(np.float32)
m = m.view(np.float16).astype(np.float32)
qh = qh.view(np.uint32)
qh = qh.reshape((n_blocks, 1)) >> np.array(
[i for i in range(32)], dtype=np.uint32
).reshape((1, 32))
ql = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array(
[0, 4], dtype=np.uint8
).reshape((1, 1, 2, 1))
qh = (qh & np.uint32(0x01)).astype(np.uint8)
ql = (ql & np.uint8(0x0F)).reshape((n_blocks, -1))
qs = (ql | (qh << np.uint8(4))).astype(np.float32)
return (d * qs) + m
class Q8_0(__Quant, qtype=GGMLQuantizationType.Q8_0):
@classmethod
# Implementation of Q8_0 with bit-exact same results as reference implementation in ggml-quants.c
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
d = abs(blocks).max(axis=1, keepdims=True) / 127
with np.errstate(divide="ignore"):
id = np.where(d == 0, 0, 1 / d)
qs = np_roundf(blocks * id)
# (n_blocks, 2)
d = d.astype(np.float16).view(np.uint8)
# (n_blocks, block_size)
qs = qs.astype(np.int8).view(np.uint8)
return np.concatenate([d, qs], axis=1)
@classmethod
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
d, x = np.split(blocks, [2], axis=1)
d = d.view(np.float16).astype(np.float32)
x = x.view(np.int8).astype(np.float32)
return x * d
class Q2_K(__Quant, qtype=GGMLQuantizationType.Q2_K):
@classmethod
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
n_blocks = blocks.shape[0]
scales, rest = np.hsplit(blocks, [QK_K // 16])
qs, rest = np.hsplit(rest, [QK_K // 4])
d, dmin = np.hsplit(rest, [2])
d = d.view(np.float16).astype(np.float32)
dmin = dmin.view(np.float16).astype(np.float32)
# (n_blocks, 16, 1)
dl = (d * (scales & 0xF).astype(np.float32)).reshape((n_blocks, QK_K // 16, 1))
ml = (dmin * (scales >> 4).astype(np.float32)).reshape(
(n_blocks, QK_K // 16, 1)
)
shift = np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 1, 4, 1))
qs = (qs.reshape((n_blocks, -1, 1, 32)) >> shift) & np.uint8(3)
qs = qs.reshape((n_blocks, QK_K // 16, 16)).astype(np.float32)
qs = dl * qs - ml
return qs.reshape((n_blocks, -1))
class Q3_K(__Quant, qtype=GGMLQuantizationType.Q3_K):
@classmethod
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
n_blocks = blocks.shape[0]
hmask, rest = np.hsplit(blocks, [QK_K // 8])
qs, rest = np.hsplit(rest, [QK_K // 4])
scales, d = np.hsplit(rest, [12])
d = d.view(np.float16).astype(np.float32)
# The scales are packed at 6-bit each in this pattern:
# 0: IIIIAAAA
# 1: JJJJBBBB
# 2: KKKKCCCC
# 3: LLLLDDDD
# 4: MMMMEEEE
# 5: NNNNFFFF
# 6: OOOOGGGG
# 7: PPPPHHHH
# 8: MMIIEEAA
# 9: NNJJFFBB
# 10: OOKKGGCC
# 11: PPLLHHDD
lscales, hscales = np.hsplit(scales, [8])
lscales = lscales.reshape((n_blocks, 1, 8)) >> np.array(
[0, 4], dtype=np.uint8
).reshape((1, 2, 1))
lscales = lscales.reshape((n_blocks, 16))
hscales = hscales.reshape((n_blocks, 1, 4)) >> np.array(
[0, 2, 4, 6], dtype=np.uint8
).reshape((1, 4, 1))
hscales = hscales.reshape((n_blocks, 16))
scales = (lscales & np.uint8(0x0F)) | (
(hscales & np.uint8(0x03)) << np.uint8(4)
)
scales = (scales.astype(np.int8) - np.int8(32)).astype(np.float32)
dl = (d * scales).reshape((n_blocks, 16, 1))
ql = qs.reshape((n_blocks, -1, 1, 32)) >> np.array(
[0, 2, 4, 6], dtype=np.uint8
).reshape((1, 1, 4, 1))
qh = hmask.reshape(n_blocks, -1, 1, 32) >> np.array(
[i for i in range(8)], dtype=np.uint8
).reshape((1, 1, 8, 1))
ql = ql.reshape((n_blocks, 16, QK_K // 16)) & np.uint8(3)
qh = qh.reshape((n_blocks, 16, QK_K // 16)) & np.uint8(1)
qh = qh ^ np.uint8(1) # strangely, the offset is zero when the bitmask is 1
q = (ql.astype(np.int8) - (qh << np.uint8(2)).astype(np.int8)).astype(
np.float32
)
return (dl * q).reshape((n_blocks, QK_K))
class Q4_K(__Quant, qtype=GGMLQuantizationType.Q4_K):
K_SCALE_SIZE = 12
@staticmethod
def get_scale_min(scales: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Unpacks the scale and minimum values from a tensor of shape (n_blocks, 12)
(stored as uint8) into two tensors of shape (n_blocks, 8) each.
The original layout (per block) is:
byte0: EEAAAAAA
byte1: FFBBBBBB
byte2: GGCCCCCC
byte3: HHDDDDDD
byte4: eeaaaaaa
byte5: ffbbbbbb
byte6: ggcccccc
byte7: hhdddddd
byte8: eeeeEEEE
byte9: ffffFFFF
byte10: ggggGGGG
byte11: hhhhHHHH
where bit-level operations extract the two 8-element vectors.
"""
n_blocks = scales.size(0)
# Reshape to (n_blocks, 3, 4) so that each “row” corresponds to 4 bytes
scales = scales.view(n_blocks, 3, 4)
# Split along the second dimension into d, m, m_d (each with shape (n_blocks, 1, 4))
d, m, m_d = torch.chunk(scales, 3, dim=1)
# Compute the scale factors:
# First half: lower 6 bits of d
sc_part1 = d & 0x3F
# Second half: combine lower 4 bits of m_d with bits [2:6] of d (masked by 0x30)
sc_part2 = (m_d & 0x0F) | ((d >> 2) & 0x30)
sc = torch.cat([sc_part1, sc_part2], dim=-1)
# Similarly, compute the minimum values:
min_part1 = m & 0x3F
min_part2 = (m_d >> 4) | ((m >> 2) & 0x30)
min_val = torch.cat([min_part1, min_part2], dim=-1)
# Flatten the last two dimensions so that each is (n_blocks, 8)
sc = sc.view(n_blocks, 8)
min_val = min_val.view(n_blocks, 8)
return sc, min_val
@classmethod
def dequantize_blocks(cls, blocks: torch.Tensor) -> torch.Tensor:
"""
Expects a tensor `blocks` of dtype torch.uint8 and shape (n_blocks, total_bytes),
where each block is structured as:
- First 2 bytes: float16 'd' (scaling factor) stored in raw bytes.
- Next 2 bytes: float16 'dmin' (minimum) stored in raw bytes.
- Next K_SCALE_SIZE (12) bytes: packed scale/min information.
- The remaining bytes: packed 4-bit quantized values.
The function returns a tensor of shape (n_blocks, QK_K) as float32.
"""
n_blocks = blocks.size(0)
# Split off the first 2 bytes (d) and the rest.
d, rest = torch.split(blocks, [2, blocks.size(1) - 2], dim=1)
# Next 2 bytes are dmin; split them from the rest.
dmin, rest = torch.split(rest, [2, rest.size(1) - 2], dim=1)
# Next K_SCALE_SIZE bytes hold the scales/mins; the remaining bytes are qs.
scales, qs = torch.split(
rest, [Q4_K.K_SCALE_SIZE, rest.size(1) - Q4_K.K_SCALE_SIZE], dim=1
)
# Reinterpret the raw 2-byte sequences as float16 and convert to float32.
# (This view-based reinterpretation works when the underlying memory layout is correct.)
d = d.view(torch.float16).to(torch.float32)
dmin = dmin.view(torch.float16).to(torch.float32)
# Extract the per-block scale and minimum vectors (each shape (n_blocks, 8))
sc, m = cls.get_scale_min(scales)
# Convert these from uint8 to float32 for multiplication
sc = sc.to(torch.float32)
m = m.to(torch.float32)
# Multiply the extracted d and dmin by their corresponding scales.
# d has shape (n_blocks, 1) and sc is (n_blocks, 8) → result will broadcast to (n_blocks, 8).
d = (d * sc).view(n_blocks, -1, 1) # shape: (n_blocks, 8, 1)
dm = (dmin * m).view(n_blocks, -1, 1) # shape: (n_blocks, 8, 1)
# Unpack the quantized values from the remaining bytes.
# Each byte holds two 4-bit values. First, reshape qs so that
# we eventually obtain a tensor of shape (n_blocks, 8, 32).
qs = qs.reshape(n_blocks, -1, 1, 32)
# Create a shift tensor to extract the lower and upper nibbles.
shift = torch.tensor([0, 4], dtype=torch.uint8, device=blocks.device).view(
1, 1, 2, 1
)
qs = qs >> shift
qs &= 0x0F
qs = qs.view(n_blocks, -1, 32).to(torch.float32) # shape now (n_blocks, 8, 32)
# Perform the dequantization: scale the quantized values and subtract the offset.
# d (shape (n_blocks, 8, 1)) multiplies qs (shape (n_blocks, 8, 32)) by broadcasting,
# and dm is subtracted before finally reshaping to (n_blocks, QK_K)
# result = (d * qs - dm).view(n_blocks, QK_K)
qs *= d
qs -= dm
return qs.view(n_blocks, QK_K)
class Q5_K(__Quant, qtype=GGMLQuantizationType.Q5_K):
@classmethod
def dequantize_blocks(cls, blocks: torch.Tensor) -> torch.Tensor:
"""
Expects a tensor `blocks` of dtype torch.uint8 and shape (n_blocks, TOTAL_BYTES),
where TOTAL_BYTES for Q5_K is 176.
"""
n_blocks = blocks.size(0)
# Split the blocks: first 2 bytes for d, next 2 bytes for dmin, and remaining parts
d, rest = torch.split(blocks, [2, blocks.size(1) - 2], dim=1)
dmin, rest = torch.split(rest, [2, rest.size(1) - 2], dim=1)
scales, rest = torch.split(
rest, [Q4_K.K_SCALE_SIZE, rest.size(1) - Q4_K.K_SCALE_SIZE], dim=1
)
qh, qs = torch.split(rest, [QK_K // 8, rest.size(1) - QK_K // 8], dim=1)
# Reinterpret the first two bytes as float16 and convert to float32.
d = d.view(torch.float16).to(torch.float32)
dmin = dmin.view(torch.float16).to(torch.float32)
# Unpack scale and min values
sc, m = Q4_K.get_scale_min(scales)
sc = sc.to(torch.float32)
m = m.to(torch.float32)
# Multiply d by scale factors and reshape for broadcasting
d = (d * sc).view(n_blocks, -1, 1) # shape (n_blocks, 8, 1)
dm = (dmin * m).view(n_blocks, -1, 1) # shape (n_blocks, 8, 1)
# Process qs for lower 4-bits (ql)
ql = qs.reshape(n_blocks, -1, 1, 32)
shift_q = torch.tensor([0, 4], dtype=torch.uint8, device=blocks.device).view(
1, 1, 2, 1
)
ql = ql >> shift_q
ql = (ql & 0x0F).reshape(n_blocks, -1, 32)
# Process qh for higher 1-bit values
qh = qh.reshape(n_blocks, -1, 1, 32)
shift_qh = torch.tensor(
[i for i in range(8)], dtype=torch.uint8, device=blocks.device
).view(1, 1, 8, 1)
qh = qh >> shift_qh
qh = (qh & 0x01).reshape(n_blocks, -1, 32)
# Combine ql and qh to form the final quantized value
q = (ql | (qh << 4)).to(torch.float32)
# Dequantization and reshape to (n_blocks, QK_K)
# result = (d * q - dm).view(n_blocks, QK_K)
q *= d
q -= dm
return q.view(n_blocks, QK_K)
class Q6_K(__Quant, qtype=GGMLQuantizationType.Q6_K):
@classmethod
def dequantize_blocks(cls, blocks: torch.Tensor) -> torch.Tensor:
"""
Torch implementation of the first dequantization method.
Expects blocks to be a 2D tensor of dtype torch.uint8 with shape (n_blocks, total_bytes)
where total_bytes = QK_K//2 + QK_K//4 + (QK_K//16) + 2*(QK_K//16).
"""
n_blocks = blocks.size(0)
# Split into segments.
ql, rest = torch.split(blocks, [QK_K // 2, blocks.size(1) - QK_K // 2], dim=1)
qh, rest = torch.split(rest, [QK_K // 4, rest.size(1) - QK_K // 4], dim=1)
scales, d = torch.split(rest, [QK_K // 16, rest.size(1) - QK_K // 16], dim=1)
scales = scales.view(torch.int8).to(torch.float32)
d = d.view(torch.float16).to(torch.float32)
# d = d.view(n_blocks, QK_K // 16, 1)
d = (d * scales).view(n_blocks, QK_K // 16, 1)
# Unpack low 4-bit values from ql.
ql = ql.view(n_blocks, -1, 1, 64)
shift_tensor = torch.tensor(
[0, 4], dtype=torch.uint8, device=blocks.device
).view(1, 1, 2, 1)
ql = ql >> shift_tensor
ql = (ql & 0x0F).view(n_blocks, -1, 32)
# Unpack 2-bit values from qh.
qh = qh.view(n_blocks, -1, 1, 32)
shift_tensor_qh = torch.tensor(
[0, 2, 4, 6], dtype=torch.uint8, device=blocks.device
).view(1, 1, 4, 1)
qh = qh >> shift_tensor_qh
qh = (qh & 0x03).view(n_blocks, -1, 32)
# Combine ql and qh.
q = (ql | (qh << 4)).to(torch.int8) - 32
q = q.view(n_blocks, QK_K // 16, -1).to(torch.float32)
q *= d
return q.view(n_blocks, QK_K)
class TQ1_0(__Quant, qtype=GGMLQuantizationType.TQ1_0):
@classmethod
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
n_blocks = blocks.shape[0]
d = abs(blocks).max(axis=-1, keepdims=True)
with np.errstate(divide="ignore"):
id = np.where(d == 0, 0, 1 / d)
qs = np_roundf(blocks * id)
qs = (qs.astype(np.int8) + np.int8(1)).astype(np.uint8)
qs0, qs1, qh = (
qs[..., : (32 * 5)],
qs[..., (32 * 5) : (48 * 5)],
qs[..., (48 * 5) :],
)
qs0 = qs0.reshape((n_blocks, -1, 5, 32)) * np.array(
[81, 27, 9, 3, 1], dtype=np.uint8
).reshape((1, 1, 5, 1))
qs0 = np.sum(qs0, axis=-2).reshape((n_blocks, -1))
qs1 = qs1.reshape((n_blocks, -1, 5, 16)) * np.array(
[81, 27, 9, 3, 1], dtype=np.uint8
).reshape((1, 1, 5, 1))
qs1 = np.sum(qs1, axis=-2).reshape((n_blocks, -1))
qh = qh.reshape((n_blocks, -1, 4, 4)) * np.array(
[81, 27, 9, 3], dtype=np.uint8
).reshape((1, 1, 4, 1))
qh = np.sum(qh, axis=-2).reshape((n_blocks, -1))
qs = np.concatenate([qs0, qs1, qh], axis=-1)
qs = (qs.astype(np.uint16) * 256 + (243 - 1)) // 243
qs = qs.astype(np.uint8)
d = d.astype(np.float16).view(np.uint8)
return np.concatenate([qs, d], axis=-1)
@classmethod
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
n_blocks = blocks.shape[0]
qs, rest = np.hsplit(blocks, [(QK_K - 4 * QK_K // 64) // 5])
qh, d = np.hsplit(rest, [QK_K // 64])
d = d.view(np.float16).astype(np.float32)
qs0, qs1 = qs[..., :32], qs[..., 32:]
qs0 = qs0.reshape((n_blocks, -1, 1, 32)) * np.array(
[1, 3, 9, 27, 81], dtype=np.uint8
).reshape((1, 1, 5, 1))
qs0 = qs0.reshape((n_blocks, -1))
qs1 = qs1.reshape((n_blocks, -1, 1, 16)) * np.array(
[1, 3, 9, 27, 81], dtype=np.uint8
).reshape((1, 1, 5, 1))
qs1 = qs1.reshape((n_blocks, -1))
qh = qh.reshape((n_blocks, -1, 1, 4)) * np.array(
[1, 3, 9, 27], dtype=np.uint8
).reshape((1, 1, 4, 1))
qh = qh.reshape((n_blocks, -1))
qs = np.concatenate([qs0, qs1, qh], axis=-1)
qs = ((qs.astype(np.uint16) * 3) >> 8).astype(np.int8) - np.int8(1)
return d * qs.astype(np.float32)
class TQ2_0(__Quant, qtype=GGMLQuantizationType.TQ2_0):
@classmethod
def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
n_blocks = blocks.shape[0]
d = abs(blocks).max(axis=-1, keepdims=True)
with np.errstate(divide="ignore"):
id = np.where(d == 0, 0, 1 / d)
qs = np_roundf(blocks * id)
qs = (qs.astype(np.int8) + np.int8(1)).astype(np.uint8)
qs = qs.reshape((n_blocks, -1, 4, 32)) << np.array(
[0, 2, 4, 6], dtype=np.uint8
).reshape((1, 1, 4, 1))
qs = qs[..., 0, :] | qs[..., 1, :] | qs[..., 2, :] | qs[..., 3, :]
qs = qs.reshape((n_blocks, -1))
d = d.astype(np.float16).view(np.uint8)
return np.concatenate([qs, d], axis=-1)
@classmethod
def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
n_blocks = blocks.shape[0]
qs, d = np.hsplit(blocks, [QK_K // 4])
d = d.view(np.float16).astype(np.float32)
qs = qs.reshape((n_blocks, -1, 1, 32)) >> np.array(
[0, 2, 4, 6], dtype=np.uint8
).reshape((1, 1, 4, 1))
qs = (qs & 0x03).reshape((n_blocks, -1)).astype(np.int8) - np.int8(1)
return d * qs.astype(np.float32)
class IQ2_XXS(__Quant, qtype=GGMLQuantizationType.IQ2_XXS):
ksigns: bytes = (
b"\x00\x81\x82\x03\x84\x05\x06\x87\x88\x09\x0a\x8b\x0c\x8d\x8e\x0f"
b"\x90\x11\x12\x93\x14\x95\x96\x17\x18\x99\x9a\x1b\x9c\x1d\x1e\x9f"
b"\xa0\x21\x22\xa3\x24\xa5\xa6\x27\x28\xa9\xaa\x2b\xac\x2d\x2e\xaf"
b"\x30\xb1\xb2\x33\xb4\x35\x36\xb7\xb8\x39\x3a\xbb\x3c\xbd\xbe\x3f"
b"\xc0\x41\x42\xc3\x44\xc5\xc6\x47\x48\xc9\xca\x4b\xcc\x4d\x4e\xcf"
b"\x50\xd1\xd2\x53\xd4\x55\x56\xd7\xd8\x59\x5a\xdb\x5c\xdd\xde\x5f"
b"\x60\xe1\xe2\x63\xe4\x65\x66\xe7\xe8\x69\x6a\xeb\x6c\xed\xee\x6f"
b"\xf0\x71\x72\xf3\x74\xf5\xf6\x77\x78\xf9\xfa\x7b\xfc\x7d\x7e\xff"
)
# iq2xxs_grid, but with each byte of the original packed in 2 bits,
# by mapping 0x08 to 0, 0x19 to 1, and 0x2b to 2.
grid_shape = (256, 8)
grid_map = (0x08, 0x19, 0x2B)
grid_hex = (
b"00000200050008000a00110014002000220028002a0041004400500058006100"
b"6400800082008a00a20001010401100115014001840198010002020222028202"
b"010404041004210424044004420448046004810484049004a404000502050805"
b"200546056905800591050906100640068406a406000805080808140828084108"
b"440850085208880804094009020a140a01100410101021104010601084109010"
b"951000110811201150115a118011241245120014081420142514491480141815"
b"6215001616160118041810184018811800190519a019511a002002200a204420"
b"6120802082202921482100220222012404241024402456240025412564259026"
b"082820289428442a014004401040184021402440404048405640604081408440"
b"9040004120416141804185410142104248425642684200440844204480449944"
b"124524450046014804481048404845480049584961498249454a904a00500850"
b"1150195020508050885004514251a4519152905492540a550156545600581158"
b"195864584059085a046010604060686000615561186260620064056410651265"
b"84654268008002800a8041808280048118814081118201840484108415844084"
b"608400854685948509864086608602880489118a0490109024904090a1901691"
b"8091459200942294449451958198209902a050a085a009a100a218a450a804a9"
)
@classmethod
def dequantize_blocks(cls, blocks: torch.Tensor) -> torch.Tensor:
cls.init_grid()
n_blocks = blocks.size(0)
d, qs = torch.split(blocks, [2, blocks.size(1) - 2], dim=1)
d = d.view(torch.float16).to(torch.float32)
qs = qs.contiguous().view(torch.int32).view(n_blocks, -1, 2)
shifted = (qs[..., 1] >> 28) & 0xF
db = d * (0.5 + shifted.to(torch.float32)) * 0.25
db = db.view((n_blocks, -1, 1, 1))
signs = qs[..., 1].view((n_blocks, -1, 1)) >> torch.tensor(
[0, 7, 14, 21], dtype=torch.int32, device=blocks.device
).view((1, 1, 4))
ksigns = (
torch.frombuffer(cls.ksigns, dtype=torch.uint8).view((1, 1, 1, 128)).cuda()
)
signs = (signs & 0x7F).view((n_blocks, -1, 4, 1)).long()
signs = torch.take_along_dim(ksigns, signs, dim=-1)
signs = signs.view((n_blocks, -1, 4, 1)) >> torch.tensor(
[i for i in range(8)], dtype=torch.uint8, device=blocks.device
).reshape((1, 1, 1, 8))
signs = signs & 0x01
signs = torch.where(signs == 0, 1.0, -1.0)
signs = signs.view((n_blocks, -1, 4, 8))
grid = torch.take_along_dim(
cls.grid,
qs[..., 0]
.clone()
.view(torch.uint8)
.view(n_blocks, -1, 1, 1)
.to(torch.long),
dim=-2,
)
grid = grid.view((n_blocks, -1, 4, 8))
grid *= signs
grid *= db
return grid.view((n_blocks, -1))
class IQ2_XS(__Quant, qtype=GGMLQuantizationType.IQ2_XS):
# iq2xs_grid, but with each byte of the original packed in 2 bits,
# by mapping 0x08 to 0, 0x19 to 1, and 0x2b to 2.
grid_shape = (512, 8)
grid_map = (0x08, 0x19, 0x2B)
grid_hex = (
b"00000200050008000a0011001400160019002000220025002800410044004600"
b"49005000520055005800610064008000820085008800910094009900a0000101"
b"04010601090110011201150118011a0121012401400142014501480151015401"
b"6001680181018401900100020202050208021102140220024102440250025502"
b"80028a0201040404060409041004120415041804210424044004420445044804"
b"5104540456046004810484049004000502050505080511051405200541054405"
b"500561058005010604061006260640064206840600080208050808080a081108"
b"14082008250841084408500858088008a008aa08010904091009400981098909"
b"000a200a280a960aa00a01100410061009101010121015101810211024104010"
b"4210451048105110541060106a10811084109010001102110511081111111411"
b"2011411144115011801194119611011204120612101240126012001402140514"
b"0814111414142014411444144914501464148014011504151015401500161416"
b"49160118041810181218401854188618001905196619511aa91a002002200520"
b"08200a201120142020204120442050208020a020012104211021402148216521"
b"002222228022a82201240424102429244024002541255225992501261a26a626"
b"002808280a28202855288828a22868299029082a202a822a882a8a2a01400440"
b"0640094010401240154018402140244040404240454048404a40514054406040"
b"6540814084409040004102410541084111411441204141414441504180418541"
b"a241014204421042124229424042004402440544084411441444194420444144"
b"4444504480449444014504451045244540459a4500460a464446504601480448"
b"1048404845485448624800491149444950496949044a00500250055008501150"
b"145020502850415044505050805001510451105115514051425100524452aa52"
b"0154045410542154405460548154a154005508558055885521566856a1560058"
b"14584158505899581a5940594259855a0160046010604060546062608660a960"
b"006124624a62926200641664106540654565a46501686a682569066a546a626a"