okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-2b (cc8c29f31) into f-own-int: our own GGUF reader/writer and quantizers (gguf-py out of the pack tools)0f1e5e4cb

main
19.5 KiB483 linesraw
1"""tools/strata_quants.py - Strata's own numpy dequantizers and the few quantizers the pack tools need (replaces gguf-py's `quants`).
2
3    dequantize(data, qtype) -> float32     data: uint8 array whose last axis holds whole rows of blocks (gguf-py's byte shape);
4                                           F32 / F16 / BF16 are views and conversions of the raw values
5    quantize(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):
33    pass
34
35
36def _name(qtype) -> str:
37    return 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)"""
43    return 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)"""
48    return 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"""
53    return ((b[:, :, None] >> np.arange(8, dtype=np.uint8)) & 1).reshape(b.shape[0], -1)
54
55
56def _signs(bits: np.ndarray) -> np.ndarray:
57    return np.where(bits == 0, f32(1), f32(-1))
58
59
60def _u32(b: np.ndarray, a: int, n: int) -> np.ndarray:
61    return np.ascontiguousarray(b[:, a:a + 4 * n]).view("<u4")
62
63
64def _u16(b: np.ndarray, a: int, n: int) -> np.ndarray:
65    return 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)"""
73    if name not in _GRID:
74        if name == "iq1s":
75            g = np.frombuffer(T.IQ1S_GRID, dtype=np.int8).reshape(-1, 8).astype(f32)
76        elif name in ("iq2xxs", "iq2xs", "iq2s"):
77            g = np.frombuffer(getattr(T, name.upper() + "_GRID"), dtype=np.uint8).reshape(-1, 8).astype(f32)
78        else:
79            g = np.frombuffer(getattr(T, name.upper() + "_GRID"), dtype=np.uint8).reshape(-1, 4).astype(f32)
80        _GRID[name] = g
81    return _GRID[name]
82
83
84# ------------------------------------------------------------------------------------------------------------ dequantizers (blocks -> float32)
85def _bf16(b):
86    return (np.ascontiguousarray(b).view("<i2").astype(np.int32) << 16).view(f32)
87
88
89def _q4_0(b):
90    d = _f16(b, 0)
91    q = _nib(b[:, 2:]).astype(np.int8) - np.int8(8)
92    return d * q.astype(f32)
93
94
95def _q4_1(b):
96    d, m = _f16(b, 0), _f16(b, 2)
97    return (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)"""
102    qh = _u32(b, a, 1)
103    return (((qh >> np.arange(32, dtype=np.uint32)) & np.uint32(1)).astype(np.uint8)) << np.uint8(4)
104
105
106def _q5_0(b):
107    d = _f16(b, 0)
108    q = (_nib(b[:, 6:]) | _q5_hi(b, 2)).astype(np.int8) - np.int8(16)
109    return d * q.astype(f32)
110
111
112def _q5_1(b):
113    d, m = _f16(b, 0), _f16(b, 2)
114    return (d * (_nib(b[:, 8:]) | _q5_hi(b, 4)).astype(f32)) + m
115
116
117def _q8_0(b):
118    return np.ascontiguousarray(b[:, 2:]).view(np.int8).astype(f32) * _f16(b, 0)
119
120
121def _q2_k(b):
122    n = b.shape[0]
123    scales, qs = b[:, :16], b[:, 16:80]
124    d, dmin = _f16(b, 80), _f16(b, 82)
125    dl = (d * (scales & 0xF).astype(f32)).reshape(n, 16, 1)
126    ml = (dmin * (scales >> 4).astype(f32)).reshape(n, 16, 1)
127    q = ((qs.reshape(n, 2, 1, 32) >> np.array([0, 2, 4, 6], dtype=np.uint8).reshape(1, 1, 4, 1)) & np.uint8(3))
128    return (dl * q.reshape(n, 16, 16).astype(f32) - ml).reshape(n, 256)
129
130
131def _q3_k(b):
132    n = b.shape[0]
133    hmask, qs, sc = b[:, :32], b[:, 32:96], b[:, 96:108]
134    d = _f16(b, 108)
135    lo = (sc[:, :8].reshape(n, 1, 8) >> np.array([0, 4], dtype=np.uint8).reshape(1, 2, 1)).reshape(n, 16)
136    hi = (sc[:, 8:].reshape(n, 1, 4) >> np.array([0, 2, 4, 6], dtype=np.uint8).reshape(1, 4, 1)).reshape(n, 16)
137    s = ((lo & np.uint8(0x0F)) | ((hi & np.uint8(3)) << np.uint8(4))).astype(np.int8) - np.int8(32)
138    dl = (d * s.astype(f32)).reshape(n, 16, 1)
139    ql = (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)
140    qh = ((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)
141    q = (ql.astype(np.int8) - (qh << np.uint8(2)).astype(np.int8)).astype(f32)
142    return (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)"""
147    n = sc.shape[0]
148    d, m, md = sc[:, 0:4], sc[:, 4:8], sc[:, 8:12]
149    s = np.concatenate([d & 0x3F, (md & 0x0F) | ((d >> 2) & 0x30)], axis=1)
150    mn = np.concatenate([m & 0x3F, (md >> 4) | ((m >> 2) & 0x30)], axis=1)
151    return s.reshape(n, 8), mn.reshape(n, 8)
152
153
154def _q4_k(b):
155    n = b.shape[0]
156    d, dmin = _f16(b, 0), _f16(b, 2)
157    s, m = _scale_min_k4(b[:, 4:16])
158    dd = (d * s.astype(f32)).reshape(n, 8, 1)
159    dm = (dmin * m.astype(f32)).reshape(n, 8, 1)
160    q = ((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)
161    return (dd * q.astype(f32) - dm).reshape(n, 256)
162
163
164def _q5_k(b):
165    n = b.shape[0]
166    d, dmin = _f16(b, 0), _f16(b, 2)
167    s, m = _scale_min_k4(b[:, 4:16])
168    dd = (d * s.astype(f32)).reshape(n, 8, 1)
169    dm = (dmin * m.astype(f32)).reshape(n, 8, 1)
170    qh, qs = b[:, 16:48], b[:, 48:]
171    ql = ((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)
172    hb = ((qh.reshape(n, 1, 1, 32) >> np.arange(8, dtype=np.uint8).reshape(1, 1, 8, 1)) & np.uint8(1)).reshape(n, 8, 32)
173    return (dd * (ql | (hb << np.uint8(4))).astype(f32) - dm).reshape(n, 256)
174
175
176def _q6_k(b):
177    n = b.shape[0]
178    ql, qh, sc, d = b[:, :128], b[:, 128:192], b[:, 192:208], _f16(b, 208)
179    dl = (d * np.ascontiguousarray(sc).view(np.int8).astype(f32)).reshape(n, 16, 1)
180    lo = ((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)
181    hi = ((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)
182    q = (lo | (hi << np.uint8(4))).astype(np.int8) - np.int8(32)
183    return (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):
190    n = b.shape[0]
191    qs, qh, d = b[:, :48], b[:, 48:52], _f16(b, 52)
192    a = (qs[:, :32].reshape(n, 1, 32) * _P3.reshape(1, 5, 1)).reshape(n, 160)           # uint8 wraps, as in the C code
193    c = (qs[:, 32:].reshape(n, 1, 16) * _P3.reshape(1, 5, 1)).reshape(n, 80)
194    e = (qh.reshape(n, 1, 4) * _P3[:4].reshape(1, 4, 1)).reshape(n, 16)
195    q = np.concatenate([a, c, e], axis=1)
196    q = ((q.astype(np.uint16) * 3) >> 8).astype(np.int8) - np.int8(1)
197    return d * q.astype(f32)
198
199
200def _tq2_0(b):
201    n = b.shape[0]
202    d = _f16(b, 64)
203    q = ((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)
204    return 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:
212    x = x.astype(np.uint32)
213    bits = np.where(x < 2, np.uint32(0x00200000) << x, (x - np.uint32(1)) << np.uint32(23)).astype(np.uint32)
214    return bits.view(f32)
215
216
217def _mxfp4(b):
218    d = _e8m0_half(b[:, :1])
219    return d * _FP4[_nib(b[:, 1:])].astype(f32)
220
221
222def _ue4m3_half(x: np.ndarray) -> np.ndarray:
223    exp = (x >> 3).astype(np.int32) & 0xF
224    man = (x & 0x7).astype(f32)
225    raw = np.where(exp == 0, man * f32(2.0 ** -9), (f32(1.0) + man / f32(8.0)) * (f32(2.0) ** (exp.astype(f32) - f32(7))))
226    return np.where((x == 0) | (x == 0x7F), f32(0.0), raw * f32(0.5)).astype(f32)
227
228
229def _nvfp4(b):
230    n = b.shape[0]
231    d = _ue4m3_half(b[:, :4]).reshape(n, 4, 1)
232    qs = b[:, 4:].reshape(n, 4, 8)
233    v = np.concatenate([qs & 0x0F, qs >> 4], axis=2)
234    return (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"""
239    ks = np.frombuffer(T.KSIGNS_IQ2XS, dtype=np.uint8)
240    return _signs((ks[idx7][..., None] >> np.arange(8, dtype=np.uint8)) & np.uint8(1))
241
242
243def _iq2_xxs(b):
244    n = b.shape[0]
245    d = _f16(b, 0)
246    w = _u32(b, 2, 16).reshape(n, 8, 2)
247    db = (d * (f32(0.5) + (w[..., 1] >> 28).astype(f32)) * f32(0.25)).reshape(n, 8, 1, 1)
248    sidx = ((w[..., 1].reshape(n, 8, 1) >> np.array([0, 7, 14, 21], dtype=np.uint32)) & np.uint32(0x7F)).astype(np.intp)
249    signs = _iq_signs_k(sidx).reshape(n, 8, 4, 8)
250    gi = np.ascontiguousarray(w[..., 0]).view(np.uint8).reshape(n, 8, 4)
251    grid = _grid("iq2xxs")[gi].reshape(n, 8, 4, 8)
252    return (db * grid * signs).reshape(n, 256)
253
254
255def _iq2_xs(b):
256    n = b.shape[0]
257    d = _f16(b, 0)
258    q = _u16(b, 2, 32)
259    sc = b[:, 66:74]
260    s = ((sc.reshape(n, 8, 1) >> np.array([0, 4], dtype=np.uint8)) & 0x0F).reshape(n, 16)
261    db = (d * (f32(0.5) + s) * f32(0.25)).reshape(n, 16, 1, 1)
262    signs = _iq_signs_k((q >> 9).astype(np.intp)).reshape(n, 16, 2, 8)
263    grid = _grid("iq2xs")[(q & np.uint16(511)).astype(np.intp)].reshape(n, 16, 2, 8)
264    return (db * grid * signs).reshape(n, 256)
265
266
267def _iq2_s(b):
268    n = b.shape[0]
269    d = _f16(b, 0)
270    qs, sg, qh, sc = b[:, 2:34], b[:, 34:66], b[:, 66:74], b[:, 74:82]
271    s = ((sc.reshape(n, 8, 1) >> np.array([0, 4], dtype=np.uint8)) & 0x0F).reshape(n, 16)
272    db = (d * (f32(0.5) + s) * f32(0.25)).reshape(n, 16, 1, 1)
273    signs = _signs(_bits(sg, 8)).reshape(n, 16, 2, 8)
274    hi = ((qh.reshape(n, 8, 1) >> np.array([0, 2, 4, 6], dtype=np.uint8)) & 3).astype(np.uint16).reshape(n, 32) << np.uint16(8)
275    gi = (qs.astype(np.uint16) | hi).astype(np.intp)
276    grid = _grid("iq2s")[gi].reshape(n, 16, 2, 8)
277    return (db * grid * signs).reshape(n, 256)
278
279
280def _iq3_xxs(b):
281    n = b.shape[0]
282    d = _f16(b, 0)
283    qs = b[:, 2:66]
284    w = _u32(b, 66, 8)
285    db = (d * (f32(0.5) + (w >> 28).astype(f32)) * f32(0.5)).reshape(n, 8, 1, 1)
286    sidx = ((w.reshape(n, 8, 1) >> np.array([0, 7, 14, 21], dtype=np.uint32)) & np.uint32(0x7F)).astype(np.intp)
287    signs = _iq_signs_k(sidx).reshape(n, 8, 4, 8)
288    grid = _grid("iq3xxs")[qs.astype(np.intp)].reshape(n, 8, 4, 8)
289    return (db * grid * signs).reshape(n, 256)
290
291
292def _iq3_s(b):
293    n = b.shape[0]
294    d = _f16(b, 0)
295    qs, qh, sg, sc = b[:, 2:66], b[:, 66:74], b[:, 74:106], b[:, 106:110]
296    s = ((sc.reshape(n, 4, 1) >> np.array([0, 4], dtype=np.uint8)) & 0x0F).reshape(n, 8)
297    db = (d * (1 + 2 * s)).reshape(n, 8, 1, 1)
298    signs = _signs(_bits(sg, 8)).reshape(n, 8, 4, 8)
299    hi = _bits(qh, 8).astype(np.uint16) << np.uint16(8)
300    gi = (qs.astype(np.uint16) | hi).astype(np.intp)
301    grid = _grid("iq3s")[gi].reshape(n, 8, 4, 8)
302    return (db * grid * signs).reshape(n, 256)
303
304
305_DELTA = f32(0.125)
306
307
308def _iq1_s(b):
309    n = b.shape[0]
310    d = _f16(b, 0)
311    qs = b[:, 2:34]
312    qh = _u16(b, 34, 8)
313    dl = (d * (2 * ((qh >> 12) & 7) + 1)).reshape(n, 8, 1, 1)
314    delta = np.where((qh & np.uint16(0x8000)) == 0, _DELTA, -_DELTA).reshape(n, 8, 1, 1)
315    hi = ((qh.reshape(n, 8, 1) >> np.array([0, 3, 6, 9], dtype=np.uint16)) & 7).reshape(n, 32) << np.uint16(8)
316    gi = (qs.astype(np.uint16) | hi).astype(np.intp)
317    grid = _grid("iq1s")[gi].reshape(n, 8, 4, 8)
318    return (dl * (grid + delta)).reshape(n, 256)
319
320
321def _iq1_m(b):
322    n = b.shape[0]
323    qs, qh = b[:, :32], b[:, 32:48]
324    sc = _u16(b, 48, 4)
325    dbits = ((sc & np.uint16(0xF000)) >> np.array([12, 8, 4, 0], dtype=np.uint16))
326    dbits = (dbits[:, 0] | dbits[:, 1] | dbits[:, 2] | dbits[:, 3]).astype(np.uint16)
327    d = dbits.view(np.float16).astype(f32).reshape(n, 1)
328    s = ((sc.reshape(n, 4, 1) >> np.array([0, 3, 6, 9], dtype=np.uint16)) & 7).reshape(n, 16)
329    dl = (d * (2 * s + 1)).reshape(n, 8, 2, 1, 1)
330    nib = (qh.reshape(n, 16, 1) >> np.array([0, 4], dtype=np.uint8)).reshape(n, 32)
331    gi = (qs.astype(np.uint16) | ((nib & 7).astype(np.uint16) << np.uint16(8))).astype(np.intp)
332    delta = np.where((nib & 0x08) == 0, _DELTA, -_DELTA).reshape(n, 8, 2, 2, 1)
333    grid = _grid("iq1s")[gi].reshape(n, 8, 2, 2, 8)
334    return (dl * (grid + delta)).reshape(n, 256)
335
336
337def _iq4_nl(b):
338    return _f16(b, 0) * _IQ4NL[_nib(b[:, 2:])].astype(f32)
339
340
341def _iq4_xs(b):
342    n = b.shape[0]
343    d = _f16(b, 0)
344    sh = _u16(b, 2, 1).reshape(n, 1)
345    sl = b[:, 4:8]
346    lo = ((sl.reshape(n, 4, 1) >> np.array([0, 4], dtype=np.uint8)) & np.uint8(0x0F)).reshape(n, 8)
347    hi = ((sh >> (2 * np.arange(8, dtype=np.uint16))) & np.uint16(3)).astype(np.uint8)
348    s = (lo | (hi << np.uint8(4))).astype(np.int8) - np.int8(32)
349    dl = (d * s.astype(f32)).reshape(n, 8, 1)
350    qs = b[:, 8:].reshape(n, 8, 16)
351    v = _IQ4NL[np.concatenate([qs & 0x0F, qs >> 4], axis=2)].astype(f32)
352    return (dl * v).reshape(n, 256)
353
354
355def _q2_0(b):
356    d = _f16(b, 0)
357    q = ((b[:, 2:, None] >> np.array([0, 2, 4, 6], dtype=np.uint8)) & 3).reshape(b.shape[0], 64)
358    return (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:
368    name = _name(qtype)
369    if name == "F32":
370        return data.view(np.float32)
371    if name == "F16":
372        return data.view(np.float16).astype(np.float32)
373    fn = _DEQ.get(name)
374    if fn is None:
375        raise NotImplementedError("Dequantization for %s is not yet implemented" % name)
376    bs, ts = BLOCK[name]
377    rows = np.asarray(data).view(np.uint8)
378    shape = rows.shape
379    if shape[-1] % ts:
380        raise ValueError("Quantized tensor bytes per row (%d) is not a multiple of %s type size (%d)" % (shape[-1], name, ts))
381    out_shape = (*shape[:-1], shape[-1] // ts * bs)
382    blocks = rows.reshape(-1, ts)
383    out = np.empty((blocks.shape[0], bs), dtype=np.float32)
384    step = max(1, _CHUNK_ELEMS // bs)
385    for i in range(0, blocks.shape[0], step):
386        out[i:i + step] = fn(np.ascontiguousarray(blocks[i:i + step]))
387    return 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)"""
393    a = np.abs(x)
394    fl = np.floor(a)
395    return np.sign(x) * (fl + np.floor(f32(2) * (a - fl)))
396
397
398def _inv(d: np.ndarray) -> np.ndarray:
399    with np.errstate(divide="ignore"):
400        return np.where(d == 0, f32(0), f32(1) / d).astype(f32)
401
402
403def _qbf16(x):
404    n = np.ascontiguousarray(x).view(np.uint32)
405    n = np.where((n & np.uint32(0x7fffffff)) > np.uint32(0x7f800000), (n & np.uint32(0xffff0000)) | np.uint32(64 << 16), n)   # NaN -> quiet
406    n = (n.astype(np.uint64) + (np.uint64(0x7fff) + ((n >> np.uint32(16)) & np.uint32(1)).astype(np.uint64))) >> np.uint64(16)  # nearest even
407    return n.astype(np.uint16).view(np.uint8)
408
409
410def _qq8_0(x):
411    d = np.abs(x).max(axis=1, keepdims=True) / f32(127)
412    q = _roundf(x * _inv(d))
413    return np.concatenate([d.astype(np.float16).view(np.uint8), q.astype(np.int8).view(np.uint8)], axis=1)
414
415
416def _pack_nib(q):
417    n = q.shape[0]
418    q = q.reshape(n, 2, 16)
419    return (q[:, 0] & np.uint8(0x0F)) | (q[:, 1] << np.uint8(4))
420
421
422def _trunc_u8(v, hi):
423    return np.trunc(v).astype(np.uint8).clip(0, hi)
424
425
426def _qq4_0(x):
427    imax = np.abs(x).argmax(axis=1)[:, None]
428    mx = np.take_along_axis(x, imax, axis=1)
429    d = mx / f32(-8)
430    q = _trunc_u8(x * _inv(d) + f32(8.5), 15)
431    return np.concatenate([d.astype(np.float16).view(np.uint8), _pack_nib(q)], axis=1)
432
433
434def _qq4_1(x):
435    mx, mn = x.max(axis=1, keepdims=True), x.min(axis=1, keepdims=True)
436    d = (mx - mn) / f32(15)
437    q = _trunc_u8((x - mn) * _inv(d) + f32(0.5), 15)
438    return 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):
442    return 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):
446    imax = np.abs(x).argmax(axis=1)[:, None]
447    mx = np.take_along_axis(x, imax, axis=1)
448    d = mx / f32(-16)
449    q = _trunc_u8(x * _inv(d) + f32(16.5), 31)
450    return np.concatenate([d.astype(np.float16).view(np.uint8), _qh(q), _pack_nib(q)], axis=1)
451
452
453def _qq5_1(x):
454    mx, mn = x.max(axis=1, keepdims=True), x.min(axis=1, keepdims=True)
455    d = (mx - mn) / f32(31)
456    q = _trunc_u8((x - mn) * _inv(d) + f32(0.5), 31)
457    return 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:
464    name = _name(qtype)
465    if name == "F32":
466        return data.astype(np.float32, copy=False)
467    if name == "F16":
468        return data.astype(np.float16, copy=False)
469    fn = _QUANT.get(name)
470    if fn is None:
471        raise NotImplementedError("Quantization for %s is not yet implemented" % name)
472    bs, ts = BLOCK[name]
473    x = np.asarray(data)
474    if x.shape[-1] % bs:
475        raise QuantError("Can't quantize tensor with shape %s to %s" % (x.shape, name))
476    out_shape = (*x.shape[:-1], x.shape[-1] // bs * ts)
477    blocks = x.astype(np.float32, copy=False).reshape(-1, bs)
478    out = np.empty((blocks.shape[0], ts), dtype=np.uint8)
479    step = max(1, _CHUNK_ELEMS // bs)
480    for i in range(0, blocks.shape[0], step):
481        part = fn(np.ascontiguousarray(blocks[i:i + step]))
482        out[i:i + step] = part.reshape(-1, ts)
483    return out.reshape(out_shape)