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
39.9 KiB799 linesraw
1"""tools/canonical_xcheck.py - P1.T3 in prototype: does the canonical form round-trip BIT-EXACTLY?
2
3P1.S6's release-blocking test is `dequant(canonical) == dequant_ggml(original)` bit for bit, for every tensor
4of the real GGUF. This is that test in Python, before the C++ exists - the same order that worked for `ref/`
5(the oracle before the engine), and faster to iterate.
6
7It starts with `Q2_0 -> S2`, which is both the largest mapping (31.64 GiB, the 202 routed-expert tensors) and
8the one whose codebook has a non-obvious feature:
9
10    dequantize_row_q2_0:   value[j] = (code[j] - 1) * d        code in {0,1,2,3}
11
12**The `- 1` is an offset in the codebook** - the representable values are {-d, 0, d, 2d}, not {0, d, 2d, 3d}.
13A canonical form that stored the codes as unsigned 0..3 and decoded `code * d` would look right on most values
14and be wrong on all of them by one step. That is why the source expression is transcribed rather than
15re-derived, and why this test exists.
16
17`docs/pack-format.md` §2.1 says Q2_0 -> S2 splits codes and scales into separate planes with NO value change.
18This checks exactly that claim.
19
20Run: python tools/canonical_xcheck.py [--tensors 4] [--gguf PATH]
21"""
22from __future__ import annotations
23
24import argparse
25import collections
26import mmap
27import os
28import pathlib
29import sys
30import time
31
32import numpy as np
33
34HERE = os.path.dirname(os.path.abspath(__file__))
35REPO = os.path.dirname(HERE)
36sys.path.insert(0, REPO)
37sys.path.insert(0, HERE)
38sys.path.insert(0, os.path.join(REPO, "ref"))
39
40import gguf_reader as G                                    # noqa: E402
41from gguf_writer import dequantize_q2_0                    # noqa: E402,F401  (kept: the packaged Control's bundle list follows this import)
42from load import _dequant_flat                             # noqa: E402
43
44# default: $STRATA_SHARD1, else the development layout (<Strata>/Q2_0 beside <Strata>/Public/Engine)
45SHARD1 = os.environ.get("STRATA_SHARD1") or os.path.join(os.path.dirname(os.path.dirname(REPO)), "Q2_0",
46                                                          "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf")
47
48QK = 64          # Q2_0 block: 64 elements
49BLOCK_BYTES = 18  # 2-byte fp16 scale + 16 bytes of 2-bit codes
50
51
52# ---------------------------------------------------------------- mappings
53#
54# Each mapping is (encode, decode, block_bytes, block_elems).  The DECODE is transcribed from
55# `ggml-quants.c` expression by expression - the plan's rule, and the thing that decides P1.T3.
56
57def to_s8_q8_0(raw: bytes):
58    """`Q8_0` -> S8: codes + an fp16 scale per 32 elements, `codebook` the affine `code - 128`.
59
60    `dequantize_row_q8_0`: `y[j] = x[i].qs[j] * d` with `d = GGML_FP16_TO_FP32(x[i].d)`.
61
62    The code plane is UNSIGNED (0..255) like every other form here, so the source's `int8_t` code is stored
63    `+128` and the decode subtracts 128 - the same integer-bias mechanism as Q2_0's `-1` and Q4_0's `-8`, and
64    bit-exact for the same reason.  It used to be stored signed instead, which is the natural reading of
65    `int8_t qs[32]` and was self-consistent with its own decoder; the pack is what showed the ambiguity,
66    because the two Q8_0 tensors then decoded 128 codes away from where they belonged while all 12 other
67    types were fine.  ONE code-plane contract, not two.
68    """
69    n = len(raw) // 34
70    a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 34)
71    # `.reshape(-1)` matters: the fp16 view of an (n,2) byte column is (n,1), and a decode doing
72    # `scales[:, None]` then broadcasts it to (n,1,1) - silently producing n TIMES too many elements instead
73    # of raising.  All the encoders return 1-D scales for that reason.
74    scales = np.ascontiguousarray(a[:, 0:2]).view(np.float16).astype(np.float32).reshape(-1)
75    codes = np.ascontiguousarray(a[:, 2:34]).view(np.int8).astype(np.int16) + 128
76    return codes.astype(np.uint8), scales
77
78
79def from_s8_q8_0(parts):
80    codes, scales = parts
81    v = (codes.astype(np.int32) - 128).astype(np.float32)      # the +128 is undone inside the integer
82    return (v * scales[:, None]).reshape(-1)
83
84
85def to_s4_q4_0(raw: bytes):
86    """`Q4_0` -> S4: 4-bit codes + one fp16 scale per 32 elements. No separate offset.
87
88    `dequantize_row_q4_0`:
89        x0 = (qs[j] & 0x0F) - 8 ;  y[j +  0] = x0*d
90        x1 = (qs[j] >>   4) - 8 ;  y[j + 16] = x1*d
91
92    TWO things here are easy to get wrong and both would still produce plausible numbers: the low nibbles
93    fill the FIRST HALF of the block and the high nibbles the SECOND (they are NOT interleaved), and the
94    `- 8` is applied to the integer BEFORE the multiply, i.e. the codebook is -8..7 rather than 0..15.
95    """
96    n = len(raw) // 18
97    a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 18)
98    scales = np.ascontiguousarray(a[:, 0:2]).view(np.float16).astype(np.float32).reshape(-1)
99    qs = np.ascontiguousarray(a[:, 2:18])                      # (n, 16)
100    codes = np.empty((n, 32), dtype=np.uint8)
101    codes[:, 0:16] = qs & 0x0F                                 # low nibbles -> first half
102    codes[:, 16:32] = qs >> 4                                  # high nibbles -> second half
103    return codes, scales
104
105
106def from_s4_q4_0(parts):
107    codes, scales = parts
108    v = (codes.astype(np.int32) - 8).astype(np.float32)        # the -8 is inside the integer
109    return (v * scales[:, None]).reshape(-1)
110
111
112def get_scale_min_k4(scales, j):
113    """`get_scale_min_k4`, ggml-quants.c L880, transcribed.
114
115    The 6-bit scale and min of group `j` (0..7) live packed in the block's 12 scale bytes: the low four
116    groups keep their 6 bits in a byte, and the high four borrow the top two bits of the LOW groups' bytes.
117    Reading only `q[j]` gives the right answer for the first half of the groups and silently wrong ones for
118    the second - which is why this is transcribed rather than inferred from the layout.
119    """
120    if j < 4:
121        return int(scales[j]) & 63, int(scales[j + 4]) & 63
122    return ((int(scales[j + 4]) & 0xF) | ((int(scales[j - 4]) >> 6) << 4),
123            (int(scales[j + 4]) >> 4) | ((int(scales[j]) >> 6) << 4))
124
125
126def to_s4_q4_k(raw: bytes):
127    """`Q4_K` -> S4: 8 groups of 32 per 256-element block, each with `scale = d*sc` and `offset = -(min*m)`.
128
129    `dequantize_row_q4_K` (L1529):
130        d = fp16(x.d) ; min = fp16(x.dmin)
131        for j in 0..256 step 64:
132            (sc,m) = get_scale_min_k4(is+0) ; d1 = d*sc ; m1 = min*m
133            (sc,m) = get_scale_min_k4(is+1) ; d2 = d*sc ; m2 = min*m
134            y[l]      = d1 * (q[l] & 0xF) - m1
135            y[l + 32] = d2 * (q[l] >>   4) - m2
136
137    TWO groups per 64-element step, taking the low and high nibbles of the SAME 32 scale bytes - so the
138    canonical group size is 32, not 64, and there are 8 groups per block.
139    """
140    n = len(raw) // 144
141    a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 144)
142    d = np.ascontiguousarray(a[:, 0:2]).view(np.float16).astype(np.float32).reshape(-1)
143    dmin = np.ascontiguousarray(a[:, 2:4]).view(np.float16).astype(np.float32).reshape(-1)
144    scb = a[:, 4:16]                                   # (n, 12) the packed 6-bit scales and mins
145    qs = a[:, 16:144]                                  # (n, 128)
146
147    scales = np.empty((n, 8), dtype=np.float32)
148    offsets = np.empty((n, 8), dtype=np.float32)
149    for g in range(8):
150        sc = np.array([get_scale_min_k4(scb[i], g)[0] for i in range(n)], dtype=np.float32)
151        m = np.array([get_scale_min_k4(scb[i], g)[1] for i in range(n)], dtype=np.float32)
152        scales[:, g] = d * sc                          # f32 product of the same two factors ggml uses
153        offsets[:, g] = -(dmin * m)                    # negation is exact, so adding it is bit-identical
154
155    codes = np.empty((n, 256), dtype=np.uint8)
156    for j in range(4):
157        blk = qs[:, j * 32:(j + 1) * 32]
158        codes[:, j * 64:j * 64 + 32] = blk & 0x0F      # group is+0: LOW nibbles
159        codes[:, j * 64 + 32:j * 64 + 64] = blk >> 4   # group is+1: HIGH nibbles
160    return codes, scales, offsets
161
162
163def from_s4_q4_k(parts):
164    codes, scales, offsets = parts
165    v = codes.astype(np.float32).reshape(codes.shape[0], 8, 32)
166    return (v * scales[:, :, None] + offsets[:, :, None]).reshape(-1)
167
168
169def unpack_q3_k_scales(sb):
170    """The 12 scale bytes of a `Q3_K` block -> 16 six-bit scales, in group order.
171
172    `dequantize_row_q3_K` L1323-1328, transcribed.  As bytes, with `s` the 12 scale bytes:
173        group  j (0..3)  = (s[j]   & 0x0F) | ((s[8+j] & 0x03) << 4)
174        group  4+j       = (s[4+j] & 0x0F) | (((s[8+j] >> 2) & 0x03) << 4)
175        group  8+j       = (s[j]   >> 4)   | (((s[8+j] >> 4) & 0x03) << 4)
176        group 12+j       = (s[4+j] >> 4)   | (((s[8+j] >> 6) & 0x03) << 4)
177
178    The trap is the same shape as `get_scale_min_k4`'s and just as quiet: the first EIGHT groups take the
179    low nibbles of `s[0..7]`, the last eight the HIGH nibbles of those SAME bytes, and `s[8..11]` supply two
180    high bits each in that same order.  A reader who assumes "12 bytes = 12 groups, one nibble each" gets
181    half the groups right.
182    """
183    n = sb.shape[0]
184    out = np.empty((n, 16), dtype=np.int32)
185    for j in range(4):
186        t = sb[:, 8 + j].astype(np.int32)
187        lo, hi = sb[:, j].astype(np.int32), sb[:, 4 + j].astype(np.int32)
188        out[:, j] = (lo & 0x0F) | ((t & 0x03) << 4)
189        out[:, 4 + j] = (hi & 0x0F) | (((t >> 2) & 0x03) << 4)
190        out[:, 8 + j] = ((lo >> 4) & 0x0F) | (((t >> 4) & 0x03) << 4)
191        out[:, 12 + j] = ((hi >> 4) & 0x0F) | (((t >> 6) & 0x03) << 4)
192    return out
193
194
195def to_s4_q3_k(raw: bytes):
196    """`Q3_K` -> S4: 16 groups of 16 per 256-element block, codebook 0..7 of the 0..15 a 4-bit plane holds.
197
198    `dequantize_row_q3_K` (L1305):
199        d_all = fp16(x.d)
200        for half in {0, 128}:                     # `q` advances by 32 per half; `hm` does NOT advance
201            for j in 0..3:                        # shift = 2j, mask m = 1 << j
202                dl = d_all * (scales[is++] - 32)
203                for l in 0..15: y = dl * ((qs[l +  0] >> shift) & 3) - ((hm[l +  0] & m) ? 0 : 4)
204                dl = d_all * (scales[is++] - 32)
205                for l in 0..15: y = dl * ((qs[l + 16] >> shift) & 3) - ((hm[l + 16] & m) ? 0 : 4)
206
207    Three things here are each independently easy to get wrong, and each would still yield plausible values:
208
209      * **`hm` is indexed 0..31 in BOTH halves, but the BIT moves.**  `q += 32` sits at the end of the `n`
210        loop, while the hmask is only ever read as `hm[l+0]`/`hm[l+16]` - so the second half re-reads the
211        SAME 32 mask bytes.  What distinguishes the halves is `m`: it is declared outside the `n` loop and
212        only ever shifted, so it never resets, and the second half uses bits 4..7 where the first used
213        0..3.  `shift` DOES reset per half.  Both facts are needed and they point opposite ways; getting
214        `m` wrong flips the sign of roughly half the elements of the second half, which is what the first
215        run of this mapping did.
216      * **the group size is 16, not 32** - 16 scales per half, hence 16 groups per 256-element block.
217      * **the `- 4` is an INTEGER bias on the code, not an offset in the value.**  So the stored code is
218        `(2 bits) + (hm bit ? 4 : 0)`, which stays in 0..7, and the decode subtracts 4 before the multiply.
219        Folding it into a value-space offset instead, as `(c+4)*dl - 4*dl`, is NOT bit-exact: `fl(5a) - 4a`
220        is exact by Sterbenz but equals `a + 5ae`, not `a`.  Q2_0's `- 1` and Q4_0's `- 8` are the same
221        integer-bias mechanism, which is why this is expressed the same way.
222
223    The element order is `128*half + 32*j + 16*sub + l`, matching the sequential `*y++`.
224    """
225    n = len(raw) // 110
226    a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 110)
227    hmask = a[:, 0:32]                                     # hmask[QK_K/8]
228    qs = a[:, 32:96]                                       # qs[QK_K/4]
229    sb = a[:, 96:108]                                      # scales[12]
230    d = np.ascontiguousarray(a[:, 108:110]).view(np.float16).astype(np.float32).reshape(-1)
231
232    sc6 = unpack_q3_k_scales(sb)
233    scales = d[:, None] * (sc6 - 32).astype(np.float32)    # integer bias, then ONE f32 multiply
234    codes = np.empty((n, 256), dtype=np.uint8)
235    for half in range(2):
236        for j in range(4):
237            for sub in range(2):
238                g = 8 * half + 2 * j + sub
239                base = half * 32 + sub * 16
240                c2 = (qs[:, base:base + 16] >> (2 * j)) & 0x03
241                # `m` does NOT reset between halves: it is `1 << (4*half + j)`, not `1 << j`.
242                m = (hmask[:, sub * 16:sub * 16 + 16] >> (4 * half + j)) & 0x01
243                codes[:, g * 16:(g + 1) * 16] = c2 + 4 * m
244    return codes, scales
245
246
247def from_s4_q3_k(parts):
248    codes, scales = parts
249    v = (codes.astype(np.int32) - 4).astype(np.float32)
250    return (v.reshape(-1, 16, 16) * scales[:, :, None]).reshape(-1)
251
252
253# ---------------------------------------------------------------- the IQ4 codebook
254# `kvalues_iq4nl`.  `ggml-common.h` heads the IQ4 block definitions "Non-linear quants", and the name is
255# load-bearing: this codebook is NOT affine, so unlike Q2_0's `-1`, Q3_K's `-4` and Q4_0's `-8` it cannot be
256# expressed as a bias on the code.  It is a 16-entry table lookup, and the canonical decode has to say so.
257# Checked against two independent files before use, because a codebook is exactly the kind of constant that
258# has silent variants: ggml-cpu/llamafile/sgemm.cpp L1361 and ggml-opencl/kernels/mul_mv_iq4_nl_f32.cl L30.
259KV_IQ4NL = np.array([-127, -104, -83, -65, -49, -35, -22, -10,
260                        1,   13,  25,  38,  53,  69,  89, 113], dtype=np.float32)
261
262
263def to_s4_iq4_nl(raw: bytes):
264    """`IQ4_NL` -> S4 with the IQ4 codebook: 32 codes, one fp16 scale, no offset.
265
266    `dequantize_row_iq4_nl` (L2725):
267        d = fp16(x.d)
268        for j in 0..15:
269            y[j +  0] = d * kvalues_iq4nl[qs[j] & 0xf]
270            y[j + 16] = d * kvalues_iq4nl[qs[j] >>  4]
271
272    Same nibble split as `Q4_0` - low nibbles fill the first half, high the second - but the code is an index
273    into the table rather than a value, so the whole `- 8` business has no analogue here.
274    """
275    n = len(raw) // 18
276    a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 18)
277    scales = np.ascontiguousarray(a[:, 0:2]).view(np.float16).astype(np.float32).reshape(-1)
278    qs = np.ascontiguousarray(a[:, 2:18])                  # (n, 16) = QK4_NL/2
279    codes = np.empty((n, 32), dtype=np.uint8)
280    codes[:, 0:16] = qs & 0x0F
281    codes[:, 16:32] = qs >> 4
282    return codes, scales
283
284
285def from_s4_iq4_nl(parts):
286    codes, scales = parts
287    return (KV_IQ4NL[codes] * scales[:, None]).reshape(-1)
288
289
290def to_s4_iq4_xs(raw: bytes):
291    """`IQ4_XS` -> S4 with the IQ4 codebook: 8 groups of 32, each with `scale = d*(ls - 32)`.
292
293    `dequantize_row_iq4_xs` (L2743):
294        d = fp16(x.d)
295        for ib in 0..7:                                   # QK_K/32 groups
296            ls = ((scales_l[ib/2] >> 4*(ib%2)) & 0xf) | (((scales_h >> 2*ib) & 3) << 4)
297            dl = d * (ls - 32)
298            for j in 0..15:
299                y[j +  0] = dl * kvalues_iq4nl[qs[j] & 0xf]
300                y[j + 16] = dl * kvalues_iq4nl[qs[j] >>  4]
301            qs += 16
302
303    The 6-bit scale `ls` is split across TWO parallel arrays by element index: `scales_l` holds one nibble
304    per 32-element group (two groups per byte, low nibble first) and the `uint16_t scales_h` holds the top
305    two bits of each group's scale at bit offset `2*ib`.  Reading a group's scale out of `scales_l` alone is
306    right for values under 16 and silently wrong above it.
307    """
308    n = len(raw) // 136
309    a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 136)
310    d = np.ascontiguousarray(a[:, 0:2]).view(np.float16).astype(np.float32).reshape(-1)
311    sh = np.ascontiguousarray(a[:, 2:4]).view(np.uint16).astype(np.int32).reshape(-1)   # uint16 scales_h
312    sl = a[:, 4:8].astype(np.int32)                          # scales_l[QK_K/64] = 4 bytes
313    qs = a[:, 8:136]                                         # qs[QK_K/2] = 128 bytes
314
315    ls = np.empty((n, 8), dtype=np.int32)
316    for ib in range(8):
317        ls[:, ib] = ((sl[:, ib // 2] >> (4 * (ib % 2))) & 0xF) | (((sh >> (2 * ib)) & 3) << 4)
318    scales = d[:, None] * (ls - 32).astype(np.float32)       # integer bias, then ONE f32 multiply
319
320    codes = np.empty((n, 256), dtype=np.uint8)
321    for ib in range(8):
322        blk = qs[:, ib * 16:(ib + 1) * 16]
323        codes[:, ib * 32:ib * 32 + 16] = blk & 0x0F          # low nibbles -> first 16 of the group
324        codes[:, ib * 32 + 16:ib * 32 + 32] = blk >> 4        # high nibbles -> second 16
325    return codes, scales
326
327
328def from_s4_iq4_xs(parts):
329    codes, scales = parts
330    return (KV_IQ4NL[codes].reshape(-1, 8, 32) * scales[:, :, None]).reshape(-1)
331
332
333def to_s8_q5_0(raw: bytes):
334    """`Q5_0` -> S8: 5-bit codes, one fp16 scale per 32 elements, codebook bias `-16`.
335
336    `dequantize_row_q5_0` (L500):
337        qh = the 4 bytes of x.qh read as a native uint32
338        for j in 0..15:
339            xh_0 = ((qh >> (j +  0)) << 4) & 0x10
340            xh_1 = ((qh >> (j + 12))     ) & 0x10
341            x0 = ((qs[j] & 0x0F) | xh_0) - 16 ;  y[j +  0] = x0*d
342            x1 = ((qs[j] >>   4) | xh_1) - 16 ;  y[j + 16] = x1*d
343
344    The 5th bit of element `j` is bit `j` of the 32-bit `qh`, and of element `j+16` is bit `j+16`: one bit per
345    element, taken from a field that is read as a single integer rather than as 4 bytes.  `x1`'s shift of
346    `j + 12` plus the `& 0x10` is how the source reaches bit `j+16`; writing `j + 16` directly gives the same
347    answer, which is worth knowing before "fixing" it.
348    """
349    n = len(raw) // 22
350    a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 22)
351    scales = np.ascontiguousarray(a[:, 0:2]).view(np.float16).astype(np.float32).reshape(-1)
352    qh = np.ascontiguousarray(a[:, 2:6]).view("<u4").reshape(-1)       # little-endian native read
353    qs = a[:, 6:22]                                                    # (n, 16)
354    j = np.arange(16)
355    xh0 = (((qh[:, None] >> j[None, :]) & 1) << 4).astype(np.uint8)
356    xh1 = (((qh[:, None] >> (j[None, :] + 16)) & 1) << 4).astype(np.uint8)
357    codes = np.empty((n, 32), dtype=np.uint8)
358    codes[:, 0:16] = (qs & 0x0F) | xh0                                 # low nibbles -> first half
359    codes[:, 16:32] = (qs >> 4) | xh1                                  # high nibbles -> second half
360    return codes, scales
361
362
363def from_s8_q5_0(parts):
364    codes, scales = parts
365    v = (codes.astype(np.int32) - 16).astype(np.float32)               # the -16 is inside the integer
366    return (v * scales[:, None]).reshape(-1)
367
368
369def to_s8_q5_k(raw: bytes):
370    """`Q5_K` -> S8: 8 groups of 32, `scale = d*sc`, `offset = -(dmin*m)`; codes are 5-bit.
371
372    `dequantize_row_q5_K` (L1731):
373        d = fp16(x.d) ; min = fp16(x.dmin)
374        is = 0 ; u1 = 1 ; u2 = 2
375        for j in 0..256 step 64:
376            (sc,m) = get_scale_min_k4(is+0) ; d1 = d*sc ; m1 = min*m
377            (sc,m) = get_scale_min_k4(is+1) ; d2 = d*sc ; m2 = min*m
378            for l in 0..31: y++ = d1 * ((ql[l] & 0xF) + (qh[l] & u1 ? 16 : 0)) - m1
379            for l in 0..31: y++ = d2 * ((ql[l] >>  4) + (qh[l] & u2 ? 16 : 0)) - m2
380            ql += 32 ; is += 2 ; u1 <<= 2 ; u2 <<= 2
381
382    Identical in shape to `Q4_K` - same `get_scale_min_k4`, same 8 groups of 32, same low-nibbles-then-high
383    order - with a 5th bit added.  `qh` does NOT advance inside the loop: the same 32 bytes are re-read by
384    all four 64-element steps, and what selects a distinct bit each time is `u1`/`u2` walking 1,4,16,64 and
385    2,8,32,128.  This is the Q3_K hmask trap again, and it is why the masks are written out rather than the
386    high bit being folded into `ql` once.
387    """
388    n = len(raw) // 176
389    a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 176)
390    d = np.ascontiguousarray(a[:, 0:2]).view(np.float16).astype(np.float32).reshape(-1)
391    dmin = np.ascontiguousarray(a[:, 2:4]).view(np.float16).astype(np.float32).reshape(-1)
392    scb = a[:, 4:16]                                   # scales[K_SCALE_SIZE] - the same packed 6-bit pairs
393    qh = a[:, 16:48]                                   # qh[QK_K/8]
394    qs = a[:, 48:176]                                  # qs[QK_K/2]
395
396    scales = np.empty((n, 8), dtype=np.float32)
397    offsets = np.empty((n, 8), dtype=np.float32)
398    for g in range(8):
399        sc = np.array([get_scale_min_k4(scb[i], g)[0] for i in range(n)], dtype=np.float32)
400        m = np.array([get_scale_min_k4(scb[i], g)[1] for i in range(n)], dtype=np.float32)
401        scales[:, g] = d * sc
402        offsets[:, g] = -(dmin * m)
403
404    codes = np.empty((n, 256), dtype=np.uint8)
405    for j in range(4):
406        blk = qs[:, j * 32:(j + 1) * 32]
407        u1, u2 = 1 << (2 * j), 2 << (2 * j)
408        lo = (blk & 0x0F) + np.where(qh & u1, 16, 0).astype(np.uint8)
409        hi = (blk >> 4) + np.where(qh & u2, 16, 0).astype(np.uint8)
410        codes[:, j * 64:j * 64 + 32] = lo              # group is+0: LOW nibbles
411        codes[:, j * 64 + 32:j * 64 + 64] = hi         # group is+1: HIGH nibbles
412    return codes, scales, offsets
413
414
415def from_s8_q5_k(parts):
416    codes, scales, offsets = parts
417    v = codes.astype(np.float32).reshape(codes.shape[0], 8, 32)
418    return (v * scales[:, :, None] + offsets[:, :, None]).reshape(-1)
419
420
421def to_s8_q6_K(raw: bytes):
422    """`Q6_K` -> S8: 16 groups of 16, `scale = d*sc` with an int8 `sc`, codebook bias `-32`.
423
424    `dequantize_row_q6_K` (L1939):
425        d = fp16(x.d)
426        for n in {0, 128}:                                 # ql += 64, qh += 32, sc += 8 per half
427            for l in 0..31:
428                is = l/16
429                q1 = ((ql[l +  0] & 0xF) | (((qh[l] >> 0) & 3) << 4)) - 32
430                q2 = ((ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4)) - 32
431                q3 = ((ql[l +  0]  >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32
432                q4 = ((ql[l + 32]  >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32
433                y[l +  0] = d * sc[is + 0] * q1
434                y[l + 32] = d * sc[is + 2] * q2
435                y[l + 64] = d * sc[is + 4] * q3
436                y[l + 96] = d * sc[is + 6] * q4
437
438    Four quads are built from ONE `qh[l]`, two bits each, while the low nibbles come from `ql[l]` and
439    `ql[l+32]` - and then the quads land at STRIDES of 32, not contiguously: q1 fills `l+0`, q2 fills `l+32`,
440    q3 fills `l+64`, q4 fills `l+96`.  So the scale index is not `l/16` in any simple reading of the quads;
441    what it works out to is `(element / 16) % 8` within the half, i.e. plain consecutive 16-element groups.
442
443    Two arithmetic details decide bit-exactness.  `d * sc[is] * q` associates LEFT, so the group scale is
444    `fl(d * float(sc))` and the value is one further multiply - not `fl(d * fl(sc*q))`.  And `sc` is `int8_t`,
445    so a negative scale is a sign flip and must be preserved, which is why the scale plane is read signed.
446    """
447    n = len(raw) // 210
448    a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 210)
449    ql = a[:, 0:128]                                   # ql[QK_K/2]
450    qh = a[:, 128:192]                                 # qh[QK_K/4]
451    sc = a[:, 192:208].view(np.int8)                   # scales[QK_K/16], SIGNED
452    d = np.ascontiguousarray(a[:, 208:210]).view(np.float16).astype(np.float32).reshape(-1)
453
454    scales = d[:, None] * sc.astype(np.float32)        # `d * sc` first, the leftmost multiply
455
456    codes = np.empty((n, 256), dtype=np.uint8)
457    for half in range(2):
458        qlb = ql[:, half * 64:(half + 1) * 64]
459        qhb = qh[:, half * 32:(half + 1) * 32]
460        # (nibble source, qh bit offset) for quads 1..4; nibble 0..31 then 32..63, low then high
461        quads = [(qlb[:, 0:32] & 0x0F, 0), (qlb[:, 32:64] & 0x0F, 2),
462                 (qlb[:, 0:32] >> 4, 4), (qlb[:, 32:64] >> 4, 6)]
463        for qidx, (nib, sh) in enumerate(quads):
464            seg = nib | (((qhb >> sh) & 0x03) << 4)
465            codes[:, half * 128 + qidx * 32: half * 128 + qidx * 32 + 32] = seg
466    return codes, scales
467
468
469def from_s8_q6_K(parts):
470    codes, scales = parts
471    v = (codes.astype(np.int32) - 32).astype(np.float32)
472    return (v.reshape(-1, 16, 16) * scales[:, :, None]).reshape(-1)
473
474
475MAPPINGS_HEADER = None   # the registry is built after the functions, at the end of the mappings section
476
477
478# ---------------------------------------------------------------- the float types (P-forms)
479def to_p32_f32(raw: bytes):
480    """`F32` -> P32: the identity.  Every other mapping is measured against this one's triviality."""
481    v = np.frombuffer(raw, dtype="<f4")
482    return v, np.ones(len(v), dtype=np.float32)
483
484
485def from_p32_f32(parts):
486    return parts[0]
487
488
489def to_p32_bf16(raw: bytes):
490    """`BF16` -> P32: a bf16 is the top 16 bits of an f32, so widening shifts left and is exact.
491
492    P32 and not P16: bf16 has the f32 exponent range and fp16 does not, so an fp16 container would send
493    large-magnitude weights to infinity.  This is the one case where the wider container is the SAFE one.
494    """
495    v = np.frombuffer(raw, dtype="<u2").astype(np.uint32) << 16
496    return v.view(np.float32), np.ones(len(v), dtype=np.float32)
497
498
499def from_p32_bf16(parts):
500    return parts[0]
501
502
503def to_p16_f16(raw: bytes):
504    """`F16` -> P16: keep the fp16, widen only to decode.  fp16 -> fp32 is always exact."""
505    return np.frombuffer(raw, dtype="<f2"), np.ones(len(raw) // 2, dtype=np.float32)
506
507
508def from_p16_f16(parts):
509    return parts[0].astype(np.float32)
510
511
512# The registry lives AFTER the functions it names.  It has to: a module-level dict referencing `to_s2`
513# before `to_s2` exists raises NameError at import, which is a mistake worth not repeating.
514#
515# Field meanings, because the C++ packer mirrors this table and a wrong field is a wrong artifact:
516#   form        the canonical form the pack stores this type in
517#   group_elems elements sharing one scale/offset entry (== block_elems where there is one per block)
518#   codebook    how a stored code becomes a NUMBER, before `* scale + offset`; `codebook` values are
519#               non-affine and need a table lookup, `None` means the affine `code + code_bias`
520#   code_bias   the integer subtracted from the code BEFORE the multiply
521#   has_offset  whether the decode adds a per-group offset after the multiply
522Mapping = collections.namedtuple(
523    "Mapping", "enc dec block_bytes block_elems group_elems form codebook code_bias has_offset")
524
525def to_s2(raw: bytes):
526    """Canonicalise `Q2_0` to S2: codes and scales in SEPARATE PLANES, values unchanged.
527
528    Returns (codes, scales) with codes `(nblocks, 64)` uint8 holding ONE 2-bit code per element - the same
529    contract every other mapping in this file honours - and scales `(nblocks,)` float32, the fp16 `d` widened
530    exactly.  Source byte j//4 holds elements 4b..4b+3 at bits 0, 2, 4, 6, so unpacking is
531    `codes[:, t::4] = (byte >> 2t) & 3`.
532
533    This used to return the 16 PACKED bytes per block instead.  It passed every check it was given, because
534    `from_s2` unpacked them again, and it was still wrong: `codes.size` is what the pack reads as a tensor's
535    element count, and for Q2_0 that came out at 1/4 of the truth.  A representation that is only correct
536    when read back by its own decoder is not a canonical form - a pack has to be able to state the element
537    count on its own.
538    """
539    n = len(raw) // BLOCK_BYTES
540    a = np.frombuffer(raw, dtype=np.uint8).reshape(n, BLOCK_BYTES)
541    scales = np.ascontiguousarray(a[:, 0:2]).view(np.float16).astype(np.float32).reshape(-1)
542    qb = a[:, 2:BLOCK_BYTES]                                  # (n, 16) packed 2-bit codes
543    codes = np.empty((n, QK), dtype=np.uint8)
544    for t in range(4):
545        codes[:, t::4] = (qb >> (2 * t)) & 0x03
546    return np.ascontiguousarray(codes), scales
547
548
549def from_s2(parts):
550    """The decode a kernel would do.  Transcribed from `dequantize_row_q2_0`, including the `- 1`.
551
552    One integer subtract then ONE f32 multiply, in that order, for the reason docs/pack-format.md §3.1 gives:
553    folding the bias into the value domain is not bit-exact.
554    """
555    codes, scales = parts
556    v = (codes.astype(np.int32) - 1).astype(np.float32)
557    return (v.reshape(-1, QK) * scales[:, None]).reshape(-1)
558
559
560# The registry lives AFTER the functions it names.  It has to: a module-level dict referencing `to_s2`
561# before `to_s2` exists raises NameError at import, which is a mistake worth not repeating.
562MAPPINGS = {
563    "Q2_0":   Mapping(to_s2,         from_s2,         18,  64,  64, "S2",  None,     -1, False),
564    "Q3_K":   Mapping(to_s4_q3_k,    from_s4_q3_k,    110, 256, 16, "S4",  None,     -4, False),
565    "Q4_0":   Mapping(to_s4_q4_0,    from_s4_q4_0,    18,  32,  32, "S4",  None,     -8, False),
566    "Q4_K":   Mapping(to_s4_q4_k,    from_s4_q4_k,    144, 256, 32, "S4",  None,      0, True),
567    "Q5_0":   Mapping(to_s8_q5_0,    from_s8_q5_0,    22,  32,  32, "S8",  None,    -16, False),
568    "Q5_K":   Mapping(to_s8_q5_k,    from_s8_q5_k,    176, 256, 32, "S8",  None,      0, True),
569    "Q6_K":   Mapping(to_s8_q6_K,    from_s8_q6_K,    210, 256, 16, "S8",  None,    -32, False),
570    "Q8_0":   Mapping(to_s8_q8_0,    from_s8_q8_0,    34,  32,  32, "S8",  None,   -128, False),
571    "IQ4_NL": Mapping(to_s4_iq4_nl,  from_s4_iq4_nl,  18,  32,  32, "S4",  "IQ4NL",   0, False),
572    "IQ4_XS": Mapping(to_s4_iq4_xs,  from_s4_iq4_xs,  136, 256, 32, "S4",  "IQ4NL",   0, False),
573    "F32":    Mapping(to_p32_f32,    from_p32_f32,     4,   1,   1, "P32", None,      0, False),
574    "BF16":   Mapping(to_p32_bf16,   from_p32_bf16,    2,   1,   1, "P32", None,      0, False),
575    "F16":    Mapping(to_p16_f16,    from_p16_f16,     2,   1,   1, "P16", None,      0, False),
576}
577
578
579def reference_values(tname: str, raw: bytes):
580    """The value this block MUST decode to - from an implementation other than the one under test.
581
582    Q2_0 goes through `gguf_writer.dequantize_q2_0` and everything else through gguf-py, both reached via
583    `_dequant_flat`.  The three float types are the exception and have to bypass it: `_dequant_flat` handles
584    them with this project's OWN `_bf16_to_f32` and numpy views, so for those the project's reference would
585    be checking itself.  tools/strata_quants.py (or gguf-py, with STRATA_GGUF_PY) implements all three independently of ref/load.py, so it is used directly here.
586    """
587    buf = np.frombuffer(raw, dtype=np.uint8)
588    if tname in ("F32", "F16", "BF16"):
589        from _paths import gguf_lib
590        g = gguf_lib()
591        return np.asarray(g.quants.dequantize(buf, g.GGMLQuantizationType[tname]), dtype=np.float32)
592    return np.asarray(_dequant_flat(tname, buf), dtype=np.float32)
593
594
595def reference_name(tname: str) -> str:
596    """Which implementation the comparison is against - printed, because these are NOT equally strong.
597
598    `gguf-py` is an independent implementation of the same C source.  `project` is this project's own
599    decoder, so a pass there is a self-consistency result: it cannot detect a misreading of the format that
600    the decoder and the canonicaliser share.  Q2_0 is the only `project` row and it is 31.64 GiB of the
601    artifact, so the distinction matters and is therefore never left implicit.
602    """
603    return "project (Q2_0 decoder) - SELF-CONSISTENCY, oracle-backed by dequant_xcheck" \
604        if tname == "Q2_0" else "gguf-py"
605
606
607def open_shard(path):
608    """mmap the shard read-only.  Slices of an mmap are ordinary bytes, which is all the reference needs.
609
610    This replaced `fh.read()`, which loaded all 37.6 GB of shard 1 into RAM.  It worked, which is exactly why
611    it was worth removing: a tool that only survives because the machine has 64 GB is not a tool that reports
612    its own limits, and it would have gone unnoticed until a machine with less memory ran it.
613    """
614    fh = open(path, "rb")
615    mm = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
616    return mm, mm.size()
617
618
619def data_section_offset(f, filelen: int) -> int:
620    """Byte offset of the tensor data, from the tensor table alone.
621
622    `filelen - max(offset + expected_bytes)` needs no header parsing and no dependency on ref/load.py's
623    private accessors.
624    """
625    return filelen - max(x.offset + (x.expected_bytes() or 0) for x in f.tensors)
626
627
628def run_full(args) -> int:
629    """P1.T3 over the WHOLE artifact: every block of every tensor, streamed.
630
631    P1.T3 is stated as "for every tensor of the real GGUF, dequant(canonical) == dequant_ggml(original) bit
632    for bit".  A per-block identity is a pure function of that block's bytes, so a sample of blocks can only
633    ever be evidence ABOUT a subset; this mode removes the qualifier.  It also reports the DATA-DEPENDENT
634    branches each type actually exercised, because those are the paths a sample can miss entirely: a scale
635    that never reaches 16 never tests the high bits of `IQ4_XS`'s `ls`, and an hmask whose top nibble is never
636    set never tests `Q3_K`'s second-half mask.
637    """
638    f = G.GGUFFile(pathlib.Path(args.gguf))
639    head, filelen = open_shard(args.gguf)
640    data_off = data_section_offset(f, filelen)
641    print("shard %s: %d tensors, data at byte %d" % (args.gguf, len(f.tensors), data_off))
642
643    by_type = collections.defaultdict(list)
644    want = {s.strip() for s in args.types.split(",")}
645    si, sn = (int(x) for x in args.split.split("/"))
646    if not 0 <= si < sn:
647        print("--split %s: need 0 <= I < N" % args.split)
648        return 2
649    # One index over ALL tensors, not per type: a per-type split would put the whole of a 202-tensor type
650    # in one process and leave the others idle.
651    for idx, t in enumerate(f.tensors):
652        if idx % sn == si:
653            by_type[t.type_name].append(t)
654    if sn > 1:
655        print("split %d/%d: %d of %d tensors in this process"
656              % (si, sn, sum(len(v) for v in by_type.values()), len(f.tensors)))
657    for tn in sorted(by_type):
658        if tn not in MAPPINGS:
659            print("  %-8s %5d tensors  NO MAPPING - not covered" % (tn, len(by_type[tn])))
660        elif tn not in want:
661            print("  %-8s %5d tensors  EXCLUDED by --types" % (tn, len(by_type[tn])))
662
663    total_t = total_b = total_bad = 0
664    ok = True
665    for tname in sorted(by_type):
666        if tname not in MAPPINGS or tname not in want:
667            continue
668        m = MAPPINGS[tname]
669        nblocks_sec = max(1, args.chunk // m.block_bytes)          # WHOLE blocks per chunk
670        n_t = n_b = n_bad = 0
671        t0 = time.time()
672        seen = collections.Counter()
673        for t in by_type[tname]:
674            if t.elements % m.block_elems:
675                print("  %-34s %d elements not a multiple of %d - SKIPPED" % (t.name, t.elements, m.block_elems))
676                ok = False
677                continue
678            nb = t.elements // m.block_elems
679            base = data_off + t.offset
680            first_bad = None
681            for s in range(0, nb, nblocks_sec):
682                cnt = min(nblocks_sec, nb - s)
683                raw = head[base + s * m.block_bytes: base + (s + cnt) * m.block_bytes]
684                if len(raw) != cnt * m.block_bytes:
685                    print("  %-34s SHORT READ at block %d - instrument error" % (t.name, s))
686                    ok = False
687                    break
688                ref = reference_values(tname, raw)
689                got = m.dec(m.enc(raw))
690                if ref.shape != got.shape:
691                    print("  %-34s SHAPE %s vs %s - instrument error" % (t.name, ref.shape, got.shape))
692                    ok = False
693                    break
694                ne = np.nonzero(ref != got)[0]
695                n_b += cnt
696                if ne.size:
697                    n_bad += ne.size
698                    if first_bad is None:
699                        first_bad = (s + int(ne[0]) // m.block_elems, int(ne[0]))
700                if args.branches:
701                    codes = m.enc(raw)[0]
702                    seen["code_hi=%d" % int(codes.max())] += 1
703                    seen["code_lo=%d" % int(codes.min())] += 1
704            n_t += 1
705            if first_bad is not None:
706                print("  %-34s FIRST MISMATCH at block %d element %d" % (t.name, first_bad[0], first_bad[1]))
707                ok = False
708        dt = time.time() - t0
709        total_t += n_t
710        total_b += n_b
711        total_bad += n_bad
712        print("  %-8s %5d tensors %9d blocks  %s  %6.1fs  ref=%s"
713              % (tname, n_t, n_b, "BIT-EXACT" if not n_bad else "*** %d BAD ***" % n_bad, dt,
714                 reference_name(tname)))
715        if args.branches and seen:
716            print("           branch reach: %s" % "  ".join("%s x%d" % kv for kv in sorted(seen.items())))
717    print()
718    print("P1.T3 full: %d tensors, %d blocks, %d mismatched elements" % (total_t, total_b, total_bad))
719    print("tools/canonical_xcheck.py --full " + ("PASS" if ok else "FAIL"))
720    return 0 if ok else 1
721
722
723def main() -> int:
724    ap = argparse.ArgumentParser()
725    ap.add_argument("--gguf", default=SHARD1)
726    ap.add_argument("--types", default=",".join(MAPPINGS),
727                    help="source types to test, one mapping each; default is every mapped type")
728    ap.add_argument("--tensors", type=int, default=2, help="tensors per type")
729    ap.add_argument("--blocks", type=int, default=2048, help="blocks per tensor")
730    ap.add_argument("--full", action="store_true",
731                    help="P1.T3 over every block of every tensor (overrides --tensors/--blocks)")
732    ap.add_argument("--chunk", type=int, default=64 << 20, help="bytes of source per streaming step")
733    ap.add_argument("--branches", action="store_true", help="report code range reached per type")
734    ap.add_argument("--split", default="0/1",
735                    help="I/N: process only tensors whose index %% N == I, so N processes can share the "
736                         "work.  Q2_0's reference is a pure-Python loop at ~1.7 MB/s and Q2_0 is 34 GB of "
737                         "the shard, so the full run is single-core-bound and worth splitting.")
738    args = ap.parse_args()
739    if args.full:
740        return run_full(args)
741
742    f = G.GGUFFile(pathlib.Path(args.gguf))
743    print("shard: %d tensors" % len(f.tensors))
744    head, filelen = open_shard(args.gguf)
745    data_off = data_section_offset(f, filelen)
746    print("data section starts at byte %d (file %d bytes)" % (data_off, filelen))
747
748    ok = True
749    covered = 0
750    for tname in args.types.split(","):
751        tname = tname.strip()
752        if tname not in MAPPINGS:
753            print("  %s: NO MAPPING in this tool yet" % tname)
754            continue
755        m = MAPPINGS[tname]
756        tensors = [t for t in f.tensors if t.type_name == tname]
757        covered += len(tensors)
758        print()
759        print("--- %s -> %s  codebook=%s bias=%d offset=%s  group=%d  (%d tensors in the shard) ---"
760              % (tname, m.form, m.codebook or "affine", m.code_bias, m.has_offset,
761                 m.group_elems, len(tensors)))
762        for t in tensors[: args.tensors]:
763            if t.elements % m.block_elems:
764                print("  %-34s %d elements is not a whole number of %d-element blocks - SKIPPED"
765                      % (t.name, t.elements, m.block_elems))
766                continue
767            want = min(args.blocks, t.elements // m.block_elems) * m.block_bytes
768            byte_off = data_off + t.offset
769            raw = head[byte_off: byte_off + want]
770            if len(raw) < want:
771                print("  %-34s SHORT READ (%d of %d) - instrument error" % (t.name, len(raw), want))
772                ok = False
773                continue
774            ref = reference_values(tname, raw)
775            parts = m.enc(raw)
776            got = m.dec(parts)
777            if ref.shape != got.shape:
778                print("  %-34s SHAPE %s ref vs %s got - instrument error" % (t.name, ref.shape, got.shape))
779                ok = False
780                continue
781            same = np.array_equal(ref, got)
782            d = np.abs(ref.astype(np.float64) - got.astype(np.float64))
783            print("  %-34s %6d blocks  %s   max|d| %.3e"
784                  % (t.name, want // m.block_bytes, "BIT-EXACT" if same else "*** MISMATCH ***", d.max()))
785            if not same:
786                bad = np.nonzero(ref != got)[0]
787                print("      first differing element %d: ref %r got %r" % (bad[0], ref[bad[0]], got[bad[0]]))
788                ok = False
789            if m.block_elems <= 256:      # a value set is informative for a quantized block, noise for f32
790                vals = np.unique(got[: m.block_elems])
791                print("      first block's value set: %s" % np.array2string(vals, precision=6))
792    print()
793    print("mapped types cover %d of %d tensors in this shard" % (covered, len(f.tensors)))
794    print("tools/canonical_xcheck.py " + ("PASS" if ok else "FAIL"))
795    return 0 if ok else 1
796
797
798if __name__ == "__main__":
799    raise SystemExit(main())