okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0f1e5e4cb
main
1"""tools/strata_quants.py - Strata's own numpy dequantizers and the few quantizers the pack tools need (replaces gguf-py's `quants`). 2 3dequantize(data, qtype) -> float32 data: uint8 array whose last axis holds whole rows of blocks (gguf-py's byte shape); 4F32 / F16 / BF16 are views and conversions of the raw values 5quantize(values, qtype) -> uint8 values: float array whose last axis is a multiple of the block size 6 7Dequantize covers every type a GGUF file of ours can carry: BF16, Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q2_K, Q3_K, Q4_K, Q5_K, Q6_K, TQ1_0, TQ2_0, MXFP4, 8NVFP4, IQ1_S, IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S, IQ4_NL, IQ4_XS and Q2_0 (Strata's own 2-bit type). Quantize covers BF16, Q8_0, Q4_0, 9Q4_1, Q5_0, Q5_1 (what the tools and tests use); anything else raises NotImplementedError. 10 11The results are bit-identical to llama.cpp's gguf-py (the pin vendored in third_party/strata-gguf-py): every float32 operation is done in 12the same order, which tools/test_strata_gguf.py proves against it. The block formats are ggml's (third_party/strata-ggml/strata-quant-common.h); 13the grids come from tools/strata_quant_tables.py, generated from that header. 14""" 15from __future__import annotations 16 17import numpy as np 18 19import strata_quant_tables as T 20 21# the block geometry (elements per block, bytes per block); strata_gguf.GGML_QUANT_SIZES is built from the same facts 22BLOCK = {"F32" : (1 ,4 ),"F16" : (1 ,2 ),"BF16" : (1 ,2 ),"Q4_0" : (32 ,18 ),"Q4_1" : (32 ,20 ),"Q5_0" : (32 ,22 ),"Q5_1" : (32 ,24 ), 23"Q8_0" : (32 ,34 ),"Q2_K" : (256 ,84 ),"Q3_K" : (256 ,110 ),"Q4_K" : (256 ,144 ),"Q5_K" : (256 ,176 ),"Q6_K" : (256 ,210 ), 24"TQ1_0" : (256 ,54 ),"TQ2_0" : (256 ,66 ),"MXFP4" : (32 ,17 ),"NVFP4" : (64 ,36 ), 25"IQ2_XXS" : (256 ,66 ),"IQ2_XS" : (256 ,74 ),"IQ2_S" : (256 ,82 ),"IQ3_XXS" : (256 ,98 ),"IQ3_S" : (256 ,110 ), 26"IQ1_S" : (256 ,50 ),"IQ1_M" : (256 ,56 ),"IQ4_NL" : (32 ,18 ),"IQ4_XS" : (256 ,136 ),"Q2_0" : (64 ,18 )} 27 28_CHUNK_ELEMS = 1 << 22 # blocks are processed in groups of about 4M values: the temporaries of the IQ types are 8x the output 29f32 = np .float32 30 31 32class QuantError (Exception ): 33pass 34 35 36def _name (qtype )-> str : 37return qtype .name if hasattr (qtype ,"name" )else str (qtype ) 38 39 40# ------------------------------------------------------------------------------------------------------------ small helpers 41def _f16 (b :np .ndarray ,a :int )-> np .ndarray : 42"""the fp16 at byte offset a of every block, as float32 (n, 1)""" 43return np .ascontiguousarray (b [:,a :a + 2 ]).view (np .float16 ).astype (f32 ) 44 45 46def _nib (qs :np .ndarray )-> np .ndarray : 47"""(n, k) bytes -> (n, 2k): all the low nibbles, then all the high nibbles (ggml's 4-bit order inside a block)""" 48return np .concatenate ([qs & 0x0F ,qs >> 4 ],axis = 1 ) 49 50 51def _bits (b :np .ndarray ,width :int )-> np .ndarray : 52"""(n, k) uint8 -> (n, k*8) bits, least significant first""" 53return ((b [:, :,None ]>> np .arange (8 ,dtype = np .uint8 ))& 1 ).reshape (b .shape [0 ],- 1 ) 54 55 56def _signs (bits :np .ndarray )-> np .ndarray : 57return np .where (bits == 0 ,f32 (1 ),f32 (- 1 )) 58 59 60def _u32 (b :np .ndarray ,a :int ,n :int )-> np .ndarray : 61return np .ascontiguousarray (b [:,a :a + 4 * n ]).view ("<u4" ) 62 63 64def _u16 (b :np .ndarray ,a :int ,n :int )-> np .ndarray : 65return np .ascontiguousarray (b [:,a :a + 2 * n ]).view ("<u2" ) 66 67 68_GRID = {} 69 70 71def _grid (name :str )-> np .ndarray : 72"""a grid table as float32 (entries, values per entry)""" 73if name not in _GRID : 74if name == "iq1s" : 75g = np .frombuffer (T .IQ1S_GRID ,dtype = np .int8 ).reshape (- 1 ,8 ).astype (f32 ) 76elif name in ("iq2xxs" ,"iq2xs" ,"iq2s" ): 77g = np .frombuffer (getattr (T ,name .upper ()+ "_GRID" ),dtype = np .uint8 ).reshape (- 1 ,8 ).astype (f32 ) 78else : 79g = np .frombuffer (getattr (T ,name .upper ()+ "_GRID" ),dtype = np .uint8 ).reshape (- 1 ,4 ).astype (f32 ) 80_GRID [name ]= g 81return _GRID [name ] 82 83 84# ------------------------------------------------------------------------------------------------------------ dequantizers (blocks -> float32) 85def _bf16 (b ): 86return (np .ascontiguousarray (b ).view ("<i2" ).astype (np .int32 )<< 16 ).view (f32 ) 87 88 89def _q4_0 (b ): 90d = _f16 (b ,0 ) 91q = _nib (b [:,2 :]).astype (np .int8 )- np .int8 (8 ) 92return d * q .astype (f32 ) 93 94 95def _q4_1 (b ): 96d ,m = _f16 (b ,0 ),_f16 (b ,2 ) 97return (d * _nib (b [:,4 :]).astype (f32 ))+ m 98 99 100def _q5_hi (b ,a ): 101"""the fifth bit of the 32 values, from the 4 bytes at a, already shifted into place (n, 32)""" 102qh = _u32 (b ,a ,1 ) 103return (((qh >> np .arange (32 ,dtype = np .uint32 ))& np .uint32 (1 )).astype (np .uint8 ))<< np .uint8 (4 ) 104 105 106def _q5_0 (b ): 107d = _f16 (b ,0 ) 108q = (_nib (b [:,6 :])| _q5_hi (b ,2 )).astype (np .int8 )- np .int8 (16 ) 109return d * q .astype (f32 ) 110 111 112def _q5_1 (b ): 113d ,m = _f16 (b ,0 ),_f16 (b ,2 ) 114return (d * (_nib (b [:,8 :])| _q5_hi (b ,4 )).astype (f32 ))+ m 115 116 117def _q8_0 (b ): 118return np .ascontiguousarray (b [:,2 :]).view (np .int8 ).astype (f32 )* _f16 (b ,0 ) 119 120 121def _q2_k (b ): 122n = b .shape [0 ] 123scales ,qs = b [:, :16 ],b [:,16 :80 ] 124d ,dmin = _f16 (b ,80 ),_f16 (b ,82 ) 125dl = (d * (scales & 0xF ).astype (f32 )).reshape (n ,16 ,1 ) 126ml = (dmin * (scales >> 4 ).astype (f32 )).reshape (n ,16 ,1 ) 127q = ((qs .reshape (n ,2 ,1 ,32 )>> np .array ([0 ,2 ,4 ,6 ],dtype = np .uint8 ).reshape (1 ,1 ,4 ,1 ))& np .uint8 (3 )) 128return (dl * q .reshape (n ,16 ,16 ).astype (f32 )- ml ).reshape (n ,256 ) 129 130 131def _q3_k (b ): 132n = b .shape [0 ] 133hmask ,qs ,sc = b [:, :32 ],b [:,32 :96 ],b [:,96 :108 ] 134d = _f16 (b ,108 ) 135lo = (sc [:, :8 ].reshape (n ,1 ,8 )>> np .array ([0 ,4 ],dtype = np .uint8 ).reshape (1 ,2 ,1 )).reshape (n ,16 ) 136hi = (sc [:,8 :].reshape (n ,1 ,4 )>> np .array ([0 ,2 ,4 ,6 ],dtype = np .uint8 ).reshape (1 ,4 ,1 )).reshape (n ,16 ) 137s = ((lo & np .uint8 (0x0F ))| ((hi & np .uint8 (3 ))<< np .uint8 (4 ))).astype (np .int8 )- np .int8 (32 ) 138dl = (d * s .astype (f32 )).reshape (n ,16 ,1 ) 139ql = (qs .reshape (n ,2 ,1 ,32 )>> np .array ([0 ,2 ,4 ,6 ],dtype = np .uint8 ).reshape (1 ,1 ,4 ,1 )).reshape (n ,16 ,16 )& np .uint8 (3 ) 140qh = ((hmask .reshape (n ,1 ,1 ,32 )>> np .arange (8 ,dtype = np .uint8 ).reshape (1 ,1 ,8 ,1 )).reshape (n ,16 ,16 )& np .uint8 (1 ))^ np .uint8 (1 ) 141q = (ql .astype (np .int8 )- (qh << np .uint8 (2 )).astype (np .int8 )).astype (f32 ) 142return (dl * q ).reshape (n ,256 ) 143 144 145def _scale_min_k4 (sc ): 146"""the 12 bytes of 6-bit scales and mins of Q4_K / Q5_K -> (scales, mins), each (n, 8)""" 147n = sc .shape [0 ] 148d ,m ,md = sc [:,0 :4 ],sc [:,4 :8 ],sc [:,8 :12 ] 149s = np .concatenate ([d & 0x3F , (md & 0x0F )| ((d >> 2 )& 0x30 )],axis = 1 ) 150mn = np .concatenate ([m & 0x3F , (md >> 4 )| ((m >> 2 )& 0x30 )],axis = 1 ) 151return s .reshape (n ,8 ),mn .reshape (n ,8 ) 152 153 154def _q4_k (b ): 155n = b .shape [0 ] 156d ,dmin = _f16 (b ,0 ),_f16 (b ,2 ) 157s ,m = _scale_min_k4 (b [:,4 :16 ]) 158dd = (d * s .astype (f32 )).reshape (n ,8 ,1 ) 159dm = (dmin * m .astype (f32 )).reshape (n ,8 ,1 ) 160q = ((b [:,16 :].reshape (n ,4 ,1 ,32 )>> np .array ([0 ,4 ],dtype = np .uint8 ).reshape (1 ,1 ,2 ,1 ))& np .uint8 (0x0F )).reshape (n ,8 ,32 ) 161return (dd * q .astype (f32 )- dm ).reshape (n ,256 ) 162 163 164def _q5_k (b ): 165n = b .shape [0 ] 166d ,dmin = _f16 (b ,0 ),_f16 (b ,2 ) 167s ,m = _scale_min_k4 (b [:,4 :16 ]) 168dd = (d * s .astype (f32 )).reshape (n ,8 ,1 ) 169dm = (dmin * m .astype (f32 )).reshape (n ,8 ,1 ) 170qh ,qs = b [:,16 :48 ],b [:,48 :] 171ql = ((qs .reshape (n ,4 ,1 ,32 )>> np .array ([0 ,4 ],dtype = np .uint8 ).reshape (1 ,1 ,2 ,1 ))& np .uint8 (0x0F )).reshape (n ,8 ,32 ) 172hb = ((qh .reshape (n ,1 ,1 ,32 )>> np .arange (8 ,dtype = np .uint8 ).reshape (1 ,1 ,8 ,1 ))& np .uint8 (1 )).reshape (n ,8 ,32 ) 173return (dd * (ql | (hb << np .uint8 (4 ))).astype (f32 )- dm ).reshape (n ,256 ) 174 175 176def _q6_k (b ): 177n = b .shape [0 ] 178ql ,qh ,sc ,d = b [:, :128 ],b [:,128 :192 ],b [:,192 :208 ],_f16 (b ,208 ) 179dl = (d * np .ascontiguousarray (sc ).view (np .int8 ).astype (f32 )).reshape (n ,16 ,1 ) 180lo = ((ql .reshape (n ,2 ,1 ,64 )>> np .array ([0 ,4 ],dtype = np .uint8 ).reshape (1 ,1 ,2 ,1 ))& np .uint8 (0x0F )).reshape (n ,8 ,32 ) 181hi = ((qh .reshape (n ,2 ,1 ,32 )>> np .array ([0 ,2 ,4 ,6 ],dtype = np .uint8 ).reshape (1 ,1 ,4 ,1 ))& np .uint8 (3 )).reshape (n ,8 ,32 ) 182q = (lo | (hi << np .uint8 (4 ))).astype (np .int8 )- np .int8 (32 ) 183return (dl * q .reshape (n ,16 ,16 ).astype (f32 )).reshape (n ,256 ) 184 185 186_P3 = np .array ([1 ,3 ,9 ,27 ,81 ],dtype = np .uint8 ) 187 188 189def _tq1_0 (b ): 190n = b .shape [0 ] 191qs ,qh ,d = b [:, :48 ],b [:,48 :52 ],_f16 (b ,52 ) 192a = (qs [:, :32 ].reshape (n ,1 ,32 )* _P3 .reshape (1 ,5 ,1 )).reshape (n ,160 )# uint8 wraps, as in the C code 193c = (qs [:,32 :].reshape (n ,1 ,16 )* _P3 .reshape (1 ,5 ,1 )).reshape (n ,80 ) 194e = (qh .reshape (n ,1 ,4 )* _P3 [:4 ].reshape (1 ,4 ,1 )).reshape (n ,16 ) 195q = np .concatenate ([a ,c ,e ],axis = 1 ) 196q = ((q .astype (np .uint16 )* 3 )>> 8 ).astype (np .int8 )- np .int8 (1 ) 197return d * q .astype (f32 ) 198 199 200def _tq2_0 (b ): 201n = b .shape [0 ] 202d = _f16 (b ,64 ) 203q = ((b [:, :64 ].reshape (n ,2 ,1 ,32 )>> np .array ([0 ,2 ,4 ,6 ],dtype = np .uint8 ).reshape (1 ,1 ,4 ,1 ))& 3 ).reshape (n ,256 ) 204return d * (q .astype (np .int8 )- np .int8 (1 )).astype (f32 ) 205 206 207_FP4 = np .frombuffer (T .KVALUES_FP4 ,dtype = np .int8 ) 208_IQ4NL = np .frombuffer (T .KVALUES_IQ4NL ,dtype = np .int8 ) 209 210 211def _e8m0_half (x :np .ndarray )-> np .ndarray : 212x = x .astype (np .uint32 ) 213bits = np .where (x < 2 ,np .uint32 (0x00200000 )<< x , (x - np .uint32 (1 ))<< np .uint32 (23 )).astype (np .uint32 ) 214return bits .view (f32 ) 215 216 217def _mxfp4 (b ): 218d = _e8m0_half (b [:, :1 ]) 219return d * _FP4 [_nib (b [:,1 :])].astype (f32 ) 220 221 222def _ue4m3_half (x :np .ndarray )-> np .ndarray : 223exp = (x >> 3 ).astype (np .int32 )& 0xF 224man = (x & 0x7 ).astype (f32 ) 225raw = np .where (exp == 0 ,man * f32 (2.0 ** - 9 ), (f32 (1.0 )+ man / f32 (8.0 ))* (f32 (2.0 )** (exp .astype (f32 )- f32 (7 )))) 226return np .where ((x == 0 )| (x == 0x7F ),f32 (0.0 ),raw * f32 (0.5 )).astype (f32 ) 227 228 229def _nvfp4 (b ): 230n = b .shape [0 ] 231d = _ue4m3_half (b [:, :4 ]).reshape (n ,4 ,1 ) 232qs = b [:,4 :].reshape (n ,4 ,8 ) 233v = np .concatenate ([qs & 0x0F ,qs >> 4 ],axis = 2 ) 234return (d * _FP4 [v ].astype (f32 )).reshape (n ,64 ) 235 236 237def _iq_signs_k (idx7 :np .ndarray )-> np .ndarray : 238"""7-bit sign indices -> (…, 8) float32 signs through ksigns_iq2xs""" 239ks = np .frombuffer (T .KSIGNS_IQ2XS ,dtype = np .uint8 ) 240return _signs ((ks [idx7 ][...,None ]>> np .arange (8 ,dtype = np .uint8 ))& np .uint8 (1 )) 241 242 243def _iq2_xxs (b ): 244n = b .shape [0 ] 245d = _f16 (b ,0 ) 246w = _u32 (b ,2 ,16 ).reshape (n ,8 ,2 ) 247db = (d * (f32 (0.5 )+ (w [...,1 ]>> 28 ).astype (f32 ))* f32 (0.25 )).reshape (n ,8 ,1 ,1 ) 248sidx = ((w [...,1 ].reshape (n ,8 ,1 )>> np .array ([0 ,7 ,14 ,21 ],dtype = np .uint32 ))& np .uint32 (0x7F )).astype (np .intp ) 249signs = _iq_signs_k (sidx ).reshape (n ,8 ,4 ,8 ) 250gi = np .ascontiguousarray (w [...,0 ]).view (np .uint8 ).reshape (n ,8 ,4 ) 251grid = _grid ("iq2xxs" )[gi ].reshape (n ,8 ,4 ,8 ) 252return (db * grid * signs ).reshape (n ,256 ) 253 254 255def _iq2_xs (b ): 256n = b .shape [0 ] 257d = _f16 (b ,0 ) 258q = _u16 (b ,2 ,32 ) 259sc = b [:,66 :74 ] 260s = ((sc .reshape (n ,8 ,1 )>> np .array ([0 ,4 ],dtype = np .uint8 ))& 0x0F ).reshape (n ,16 ) 261db = (d * (f32 (0.5 )+ s )* f32 (0.25 )).reshape (n ,16 ,1 ,1 ) 262signs = _iq_signs_k ((q >> 9 ).astype (np .intp )).reshape (n ,16 ,2 ,8 ) 263grid = _grid ("iq2xs" )[(q & np .uint16 (511 )).astype (np .intp )].reshape (n ,16 ,2 ,8 ) 264return (db * grid * signs ).reshape (n ,256 ) 265 266 267def _iq2_s (b ): 268n = b .shape [0 ] 269d = _f16 (b ,0 ) 270qs ,sg ,qh ,sc = b [:,2 :34 ],b [:,34 :66 ],b [:,66 :74 ],b [:,74 :82 ] 271s = ((sc .reshape (n ,8 ,1 )>> np .array ([0 ,4 ],dtype = np .uint8 ))& 0x0F ).reshape (n ,16 ) 272db = (d * (f32 (0.5 )+ s )* f32 (0.25 )).reshape (n ,16 ,1 ,1 ) 273signs = _signs (_bits (sg ,8 )).reshape (n ,16 ,2 ,8 ) 274hi = ((qh .reshape (n ,8 ,1 )>> np .array ([0 ,2 ,4 ,6 ],dtype = np .uint8 ))& 3 ).astype (np .uint16 ).reshape (n ,32 )<< np .uint16 (8 ) 275gi = (qs .astype (np .uint16 )| hi ).astype (np .intp ) 276grid = _grid ("iq2s" )[gi ].reshape (n ,16 ,2 ,8 ) 277return (db * grid * signs ).reshape (n ,256 ) 278 279 280def _iq3_xxs (b ): 281n = b .shape [0 ] 282d = _f16 (b ,0 ) 283qs = b [:,2 :66 ] 284w = _u32 (b ,66 ,8 ) 285db = (d * (f32 (0.5 )+ (w >> 28 ).astype (f32 ))* f32 (0.5 )).reshape (n ,8 ,1 ,1 ) 286sidx = ((w .reshape (n ,8 ,1 )>> np .array ([0 ,7 ,14 ,21 ],dtype = np .uint32 ))& np .uint32 (0x7F )).astype (np .intp ) 287signs = _iq_signs_k (sidx ).reshape (n ,8 ,4 ,8 ) 288grid = _grid ("iq3xxs" )[qs .astype (np .intp )].reshape (n ,8 ,4 ,8 ) 289return (db * grid * signs ).reshape (n ,256 ) 290 291 292def _iq3_s (b ): 293n = b .shape [0 ] 294d = _f16 (b ,0 ) 295qs ,qh ,sg ,sc = b [:,2 :66 ],b [:,66 :74 ],b [:,74 :106 ],b [:,106 :110 ] 296s = ((sc .reshape (n ,4 ,1 )>> np .array ([0 ,4 ],dtype = np .uint8 ))& 0x0F ).reshape (n ,8 ) 297db = (d * (1 + 2 * s )).reshape (n ,8 ,1 ,1 ) 298signs = _signs (_bits (sg ,8 )).reshape (n ,8 ,4 ,8 ) 299hi = _bits (qh ,8 ).astype (np .uint16 )<< np .uint16 (8 ) 300gi = (qs .astype (np .uint16 )| hi ).astype (np .intp ) 301grid = _grid ("iq3s" )[gi ].reshape (n ,8 ,4 ,8 ) 302return (db * grid * signs ).reshape (n ,256 ) 303 304 305_DELTA = f32 (0.125 ) 306 307 308def _iq1_s (b ): 309n = b .shape [0 ] 310d = _f16 (b ,0 ) 311qs = b [:,2 :34 ] 312qh = _u16 (b ,34 ,8 ) 313dl = (d * (2 * ((qh >> 12 )& 7 )+ 1 )).reshape (n ,8 ,1 ,1 ) 314delta = np .where ((qh & np .uint16 (0x8000 ))== 0 ,_DELTA ,- _DELTA ).reshape (n ,8 ,1 ,1 ) 315hi = ((qh .reshape (n ,8 ,1 )>> np .array ([0 ,3 ,6 ,9 ],dtype = np .uint16 ))& 7 ).reshape (n ,32 )<< np .uint16 (8 ) 316gi = (qs .astype (np .uint16 )| hi ).astype (np .intp ) 317grid = _grid ("iq1s" )[gi ].reshape (n ,8 ,4 ,8 ) 318return (dl * (grid + delta )).reshape (n ,256 ) 319 320 321def _iq1_m (b ): 322n = b .shape [0 ] 323qs ,qh = b [:, :32 ],b [:,32 :48 ] 324sc = _u16 (b ,48 ,4 ) 325dbits = ((sc & np .uint16 (0xF000 ))>> np .array ([12 ,8 ,4 ,0 ],dtype = np .uint16 )) 326dbits = (dbits [:,0 ]| dbits [:,1 ]| dbits [:,2 ]| dbits [:,3 ]).astype (np .uint16 ) 327d = dbits .view (np .float16 ).astype (f32 ).reshape (n ,1 ) 328s = ((sc .reshape (n ,4 ,1 )>> np .array ([0 ,3 ,6 ,9 ],dtype = np .uint16 ))& 7 ).reshape (n ,16 ) 329dl = (d * (2 * s + 1 )).reshape (n ,8 ,2 ,1 ,1 ) 330nib = (qh .reshape (n ,16 ,1 )>> np .array ([0 ,4 ],dtype = np .uint8 )).reshape (n ,32 ) 331gi = (qs .astype (np .uint16 )| ((nib & 7 ).astype (np .uint16 )<< np .uint16 (8 ))).astype (np .intp ) 332delta = np .where ((nib & 0x08 )== 0 ,_DELTA ,- _DELTA ).reshape (n ,8 ,2 ,2 ,1 ) 333grid = _grid ("iq1s" )[gi ].reshape (n ,8 ,2 ,2 ,8 ) 334return (dl * (grid + delta )).reshape (n ,256 ) 335 336 337def _iq4_nl (b ): 338return _f16 (b ,0 )* _IQ4NL [_nib (b [:,2 :])].astype (f32 ) 339 340 341def _iq4_xs (b ): 342n = b .shape [0 ] 343d = _f16 (b ,0 ) 344sh = _u16 (b ,2 ,1 ).reshape (n ,1 ) 345sl = b [:,4 :8 ] 346lo = ((sl .reshape (n ,4 ,1 )>> np .array ([0 ,4 ],dtype = np .uint8 ))& np .uint8 (0x0F )).reshape (n ,8 ) 347hi = ((sh >> (2 * np .arange (8 ,dtype = np .uint16 )))& np .uint16 (3 )).astype (np .uint8 ) 348s = (lo | (hi << np .uint8 (4 ))).astype (np .int8 )- np .int8 (32 ) 349dl = (d * s .astype (f32 )).reshape (n ,8 ,1 ) 350qs = b [:,8 :].reshape (n ,8 ,16 ) 351v = _IQ4NL [np .concatenate ([qs & 0x0F ,qs >> 4 ],axis = 2 )].astype (f32 ) 352return (dl * v ).reshape (n ,256 ) 353 354 355def _q2_0 (b ): 356d = _f16 (b ,0 ) 357q = ((b [:,2 :,None ]>> np .array ([0 ,2 ,4 ,6 ],dtype = np .uint8 ))& 3 ).reshape (b .shape [0 ],64 ) 358return (q .astype (f32 )- f32 (1.0 ))* d 359 360 361_DEQ = {"BF16" :_bf16 ,"Q4_0" :_q4_0 ,"Q4_1" :_q4_1 ,"Q5_0" :_q5_0 ,"Q5_1" :_q5_1 ,"Q8_0" :_q8_0 ,"Q2_K" :_q2_k ,"Q3_K" :_q3_k , 362"Q4_K" :_q4_k ,"Q5_K" :_q5_k ,"Q6_K" :_q6_k ,"TQ1_0" :_tq1_0 ,"TQ2_0" :_tq2_0 ,"MXFP4" :_mxfp4 ,"NVFP4" :_nvfp4 , 363"IQ2_XXS" :_iq2_xxs ,"IQ2_XS" :_iq2_xs ,"IQ2_S" :_iq2_s ,"IQ3_XXS" :_iq3_xxs ,"IQ3_S" :_iq3_s ,"IQ1_S" :_iq1_s , 364"IQ1_M" :_iq1_m ,"IQ4_NL" :_iq4_nl ,"IQ4_XS" :_iq4_xs ,"Q2_0" :_q2_0 } 365 366 367def dequantize (data :np .ndarray ,qtype )-> np .ndarray : 368name = _name (qtype ) 369if name == "F32" : 370return data .view (np .float32 ) 371if name == "F16" : 372return data .view (np .float16 ).astype (np .float32 ) 373fn = _DEQ .get (name ) 374if fn is None : 375raise NotImplementedError ("Dequantization for %s is not yet implemented" % name ) 376bs ,ts = BLOCK [name ] 377rows = np .asarray (data ).view (np .uint8 ) 378shape = rows .shape 379if shape [- 1 ]% ts : 380raise ValueError ("Quantized tensor bytes per row (%d) is not a multiple of %s type size (%d)" % (shape [- 1 ],name ,ts )) 381out_shape = (* shape [:- 1 ],shape [- 1 ]// ts * bs ) 382blocks = rows .reshape (- 1 ,ts ) 383out = np .empty ((blocks .shape [0 ],bs ),dtype = np .float32 ) 384step = max (1 ,_CHUNK_ELEMS // bs ) 385for i in range (0 ,blocks .shape [0 ],step ): 386out [i :i + step ]= fn (np .ascontiguousarray (blocks [i :i + step ])) 387return out .reshape (out_shape ) 388 389 390# ------------------------------------------------------------------------------------------------------------ quantizers (float32 blocks -> bytes) 391def _roundf (x :np .ndarray )-> np .ndarray : 392"""round half away from zero, in float32 (ggml's roundf)""" 393a = np .abs (x ) 394fl = np .floor (a ) 395return np .sign (x )* (fl + np .floor (f32 (2 )* (a - fl ))) 396 397 398def _inv (d :np .ndarray )-> np .ndarray : 399with np .errstate (divide = "ignore" ): 400return np .where (d == 0 ,f32 (0 ),f32 (1 )/ d ).astype (f32 ) 401 402 403def _qbf16 (x ): 404n = np .ascontiguousarray (x ).view (np .uint32 ) 405n = np .where ((n & np .uint32 (0x7fffffff ))> np .uint32 (0x7f800000 ), (n & np .uint32 (0xffff0000 ))| np .uint32 (64 << 16 ),n )# NaN -> quiet 406n = (n .astype (np .uint64 )+ (np .uint64 (0x7fff )+ ((n >> np .uint32 (16 ))& np .uint32 (1 )).astype (np .uint64 )))>> np .uint64 (16 )# nearest even 407return n .astype (np .uint16 ).view (np .uint8 ) 408 409 410def _qq8_0 (x ): 411d = np .abs (x ).max (axis = 1 ,keepdims = True )/ f32 (127 ) 412q = _roundf (x * _inv (d )) 413return np .concatenate ([d .astype (np .float16 ).view (np .uint8 ),q .astype (np .int8 ).view (np .uint8 )],axis = 1 ) 414 415 416def _pack_nib (q ): 417n = q .shape [0 ] 418q = q .reshape (n ,2 ,16 ) 419return (q [:,0 ]& np .uint8 (0x0F ))| (q [:,1 ]<< np .uint8 (4 )) 420 421 422def _trunc_u8 (v ,hi ): 423return np .trunc (v ).astype (np .uint8 ).clip (0 ,hi ) 424 425 426def _qq4_0 (x ): 427imax = np .abs (x ).argmax (axis = 1 )[:,None ] 428mx = np .take_along_axis (x ,imax ,axis = 1 ) 429d = mx / f32 (- 8 ) 430q = _trunc_u8 (x * _inv (d )+ f32 (8.5 ),15 ) 431return np .concatenate ([d .astype (np .float16 ).view (np .uint8 ),_pack_nib (q )],axis = 1 ) 432 433 434def _qq4_1 (x ): 435mx ,mn = x .max (axis = 1 ,keepdims = True ),x .min (axis = 1 ,keepdims = True ) 436d = (mx - mn )/ f32 (15 ) 437q = _trunc_u8 ((x - mn )* _inv (d )+ f32 (0.5 ),15 ) 438return np .concatenate ([d .astype (np .float16 ).view (np .uint8 ),mn .astype (np .float16 ).view (np .uint8 ),_pack_nib (q )],axis = 1 ) 439 440 441def _qh (q ): 442return np .packbits (q .reshape (q .shape [0 ],1 ,32 )>> np .uint8 (4 ),axis =- 1 ,bitorder = "little" ).reshape (q .shape [0 ],4 ) 443 444 445def _qq5_0 (x ): 446imax = np .abs (x ).argmax (axis = 1 )[:,None ] 447mx = np .take_along_axis (x ,imax ,axis = 1 ) 448d = mx / f32 (- 16 ) 449q = _trunc_u8 (x * _inv (d )+ f32 (16.5 ),31 ) 450return np .concatenate ([d .astype (np .float16 ).view (np .uint8 ),_qh (q ),_pack_nib (q )],axis = 1 ) 451 452 453def _qq5_1 (x ): 454mx ,mn = x .max (axis = 1 ,keepdims = True ),x .min (axis = 1 ,keepdims = True ) 455d = (mx - mn )/ f32 (31 ) 456q = _trunc_u8 ((x - mn )* _inv (d )+ f32 (0.5 ),31 ) 457return np .concatenate ([d .astype (np .float16 ).view (np .uint8 ),mn .astype (np .float16 ).view (np .uint8 ),_qh (q ),_pack_nib (q )],axis = 1 ) 458 459 460_QUANT = {"BF16" :_qbf16 ,"Q8_0" :_qq8_0 ,"Q4_0" :_qq4_0 ,"Q4_1" :_qq4_1 ,"Q5_0" :_qq5_0 ,"Q5_1" :_qq5_1 } 461 462 463def quantize (data :np .ndarray ,qtype )-> np .ndarray : 464name = _name (qtype ) 465if name == "F32" : 466return data .astype (np .float32 ,copy = False ) 467if name == "F16" : 468return data .astype (np .float16 ,copy = False ) 469fn = _QUANT .get (name ) 470if fn is None : 471raise NotImplementedError ("Quantization for %s is not yet implemented" % name ) 472bs ,ts = BLOCK [name ] 473x = np .asarray (data ) 474if x .shape [- 1 ]% bs : 475raise QuantError ("Can't quantize tensor with shape %s to %s" % (x .shape ,name )) 476out_shape = (* x .shape [:- 1 ],x .shape [- 1 ]// bs * ts ) 477blocks = x .astype (np .float32 ,copy = False ).reshape (- 1 ,bs ) 478out = np .empty ((blocks .shape [0 ],ts ),dtype = np .uint8 ) 479step = max (1 ,_CHUNK_ELEMS // bs ) 480for i in range (0 ,blocks .shape [0 ],step ): 481part = fn (np .ascontiguousarray (blocks [i :i + step ])) 482out [i :i + step ]= part .reshape (- 1 ,ts ) 483return out .reshape (out_shape )