okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0f1e5e4cb
main
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 10dequantize_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 62The 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 64bit-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, 66because the two Q8_0 tensors then decoded 128 codes away from where they belonged while all 12 other 67types were fine. ONE code-plane contract, not two. 68""" 69n = len (raw )// 34 70a = 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. 74scales = np .ascontiguousarray (a [:,0 :2 ]).view (np .float16 ).astype (np .float32 ).reshape (- 1 ) 75codes = np .ascontiguousarray (a [:,2 :34 ]).view (np .int8 ).astype (np .int16 )+ 128 76return codes .astype (np .uint8 ),scales 77 78 79def from_s8_q8_0 (parts ): 80codes ,scales = parts 81v = (codes .astype (np .int32 )- 128 ).astype (np .float32 )# the +128 is undone inside the integer 82return (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`: 89x0 = (qs[j] & 0x0F) - 8 ; y[j + 0] = x0*d 90x1 = (qs[j] >> 4) - 8 ; y[j + 16] = x1*d 91 92TWO things here are easy to get wrong and both would still produce plausible numbers: the low nibbles 93fill 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""" 96n = len (raw )// 18 97a = np .frombuffer (raw ,dtype = np .uint8 ).reshape (n ,18 ) 98scales = np .ascontiguousarray (a [:,0 :2 ]).view (np .float16 ).astype (np .float32 ).reshape (- 1 ) 99qs = np .ascontiguousarray (a [:,2 :18 ])# (n, 16) 100codes = np .empty ((n ,32 ),dtype = np .uint8 ) 101codes [:,0 :16 ]= qs & 0x0F # low nibbles -> first half 102codes [:,16 :32 ]= qs >> 4 # high nibbles -> second half 103return codes ,scales 104 105 106def from_s4_q4_0 (parts ): 107codes ,scales = parts 108v = (codes .astype (np .int32 )- 8 ).astype (np .float32 )# the -8 is inside the integer 109return (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 115The 6-bit scale and min of group `j` (0..7) live packed in the block's 12 scale bytes: the low four 116groups keep their 6 bits in a byte, and the high four borrow the top two bits of the LOW groups' bytes. 117Reading only `q[j]` gives the right answer for the first half of the groups and silently wrong ones for 118the second - which is why this is transcribed rather than inferred from the layout. 119""" 120if j < 4 : 121return int (scales [j ])& 63 ,int (scales [j + 4 ])& 63 122return ((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): 130d = fp16(x.d) ; min = fp16(x.dmin) 131for 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 134y[l] = d1 * (q[l] & 0xF) - m1 135y[l + 32] = d2 * (q[l] >> 4) - m2 136 137TWO groups per 64-element step, taking the low and high nibbles of the SAME 32 scale bytes - so the 138canonical group size is 32, not 64, and there are 8 groups per block. 139""" 140n = len (raw )// 144 141a = np .frombuffer (raw ,dtype = np .uint8 ).reshape (n ,144 ) 142d = np .ascontiguousarray (a [:,0 :2 ]).view (np .float16 ).astype (np .float32 ).reshape (- 1 ) 143dmin = np .ascontiguousarray (a [:,2 :4 ]).view (np .float16 ).astype (np .float32 ).reshape (- 1 ) 144scb = a [:,4 :16 ]# (n, 12) the packed 6-bit scales and mins 145qs = a [:,16 :144 ]# (n, 128) 146 147scales = np .empty ((n ,8 ),dtype = np .float32 ) 148offsets = np .empty ((n ,8 ),dtype = np .float32 ) 149for g in range (8 ): 150sc = np .array ([get_scale_min_k4 (scb [i ],g )[0 ]for i in range (n )],dtype = np .float32 ) 151m = np .array ([get_scale_min_k4 (scb [i ],g )[1 ]for i in range (n )],dtype = np .float32 ) 152scales [:,g ]= d * sc # f32 product of the same two factors ggml uses 153offsets [:,g ]= - (dmin * m )# negation is exact, so adding it is bit-identical 154 155codes = np .empty ((n ,256 ),dtype = np .uint8 ) 156for j in range (4 ): 157blk = qs [:,j * 32 :(j + 1 )* 32 ] 158codes [:,j * 64 :j * 64 + 32 ]= blk & 0x0F # group is+0: LOW nibbles 159codes [:,j * 64 + 32 :j * 64 + 64 ]= blk >> 4 # group is+1: HIGH nibbles 160return codes ,scales ,offsets 161 162 163def from_s4_q4_k (parts ): 164codes ,scales ,offsets = parts 165v = codes .astype (np .float32 ).reshape (codes .shape [0 ],8 ,32 ) 166return (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: 173group j (0..3) = (s[j] & 0x0F) | ((s[8+j] & 0x03) << 4) 174group 4+j = (s[4+j] & 0x0F) | (((s[8+j] >> 2) & 0x03) << 4) 175group 8+j = (s[j] >> 4) | (((s[8+j] >> 4) & 0x03) << 4) 176group 12+j = (s[4+j] >> 4) | (((s[8+j] >> 6) & 0x03) << 4) 177 178The trap is the same shape as `get_scale_min_k4`'s and just as quiet: the first EIGHT groups take the 179low nibbles of `s[0..7]`, the last eight the HIGH nibbles of those SAME bytes, and `s[8..11]` supply two 180high bits each in that same order. A reader who assumes "12 bytes = 12 groups, one nibble each" gets 181half the groups right. 182""" 183n = sb .shape [0 ] 184out = np .empty ((n ,16 ),dtype = np .int32 ) 185for j in range (4 ): 186t = sb [:,8 + j ].astype (np .int32 ) 187lo ,hi = sb [:,j ].astype (np .int32 ),sb [:,4 + j ].astype (np .int32 ) 188out [:,j ]= (lo & 0x0F )| ((t & 0x03 )<< 4 ) 189out [:,4 + j ]= (hi & 0x0F )| (((t >> 2 )& 0x03 )<< 4 ) 190out [:,8 + j ]= ((lo >> 4 )& 0x0F )| (((t >> 4 )& 0x03 )<< 4 ) 191out [:,12 + j ]= ((hi >> 4 )& 0x0F )| (((t >> 6 )& 0x03 )<< 4 ) 192return 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): 199d_all = fp16(x.d) 200for half in {0, 128}: # `q` advances by 32 per half; `hm` does NOT advance 201for j in 0..3: # shift = 2j, mask m = 1 << j 202dl = d_all * (scales[is++] - 32) 203for l in 0..15: y = dl * ((qs[l + 0] >> shift) & 3) - ((hm[l + 0] & m) ? 0 : 4) 204dl = d_all * (scales[is++] - 32) 205for l in 0..15: y = dl * ((qs[l + 16] >> shift) & 3) - ((hm[l + 16] & m) ? 0 : 4) 206 207Three 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` 210loop, while the hmask is only ever read as `hm[l+0]`/`hm[l+16]` - so the second half re-reads the 211SAME 32 mask bytes. What distinguishes the halves is `m`: it is declared outside the `n` loop and 212only ever shifted, so it never resets, and the second half uses bits 4..7 where the first used 2130..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 215run 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. 219Folding it into a value-space offset instead, as `(c+4)*dl - 4*dl`, is NOT bit-exact: `fl(5a) - 4a` 220is exact by Sterbenz but equals `a + 5ae`, not `a`. Q2_0's `- 1` and Q4_0's `- 8` are the same 221integer-bias mechanism, which is why this is expressed the same way. 222 223The element order is `128*half + 32*j + 16*sub + l`, matching the sequential `*y++`. 224""" 225n = len (raw )// 110 226a = np .frombuffer (raw ,dtype = np .uint8 ).reshape (n ,110 ) 227hmask = a [:,0 :32 ]# hmask[QK_K/8] 228qs = a [:,32 :96 ]# qs[QK_K/4] 229sb = a [:,96 :108 ]# scales[12] 230d = np .ascontiguousarray (a [:,108 :110 ]).view (np .float16 ).astype (np .float32 ).reshape (- 1 ) 231 232sc6 = unpack_q3_k_scales (sb ) 233scales = d [:,None ]* (sc6 - 32 ).astype (np .float32 )# integer bias, then ONE f32 multiply 234codes = np .empty ((n ,256 ),dtype = np .uint8 ) 235for half in range (2 ): 236for j in range (4 ): 237for sub in range (2 ): 238g = 8 * half + 2 * j + sub 239base = half * 32 + sub * 16 240c2 = (qs [:,base :base + 16 ]>> (2 * j ))& 0x03 241# `m` does NOT reset between halves: it is `1 << (4*half + j)`, not `1 << j`. 242m = (hmask [:,sub * 16 :sub * 16 + 16 ]>> (4 * half + j ))& 0x01 243codes [:,g * 16 :(g + 1 )* 16 ]= c2 + 4 * m 244return codes ,scales 245 246 247def from_s4_q3_k (parts ): 248codes ,scales = parts 249v = (codes .astype (np .int32 )- 4 ).astype (np .float32 ) 250return (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 , 2601 ,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): 267d = fp16(x.d) 268for j in 0..15: 269y[j + 0] = d * kvalues_iq4nl[qs[j] & 0xf] 270y[j + 16] = d * kvalues_iq4nl[qs[j] >> 4] 271 272Same nibble split as `Q4_0` - low nibbles fill the first half, high the second - but the code is an index 273into the table rather than a value, so the whole `- 8` business has no analogue here. 274""" 275n = len (raw )// 18 276a = np .frombuffer (raw ,dtype = np .uint8 ).reshape (n ,18 ) 277scales = np .ascontiguousarray (a [:,0 :2 ]).view (np .float16 ).astype (np .float32 ).reshape (- 1 ) 278qs = np .ascontiguousarray (a [:,2 :18 ])# (n, 16) = QK4_NL/2 279codes = np .empty ((n ,32 ),dtype = np .uint8 ) 280codes [:,0 :16 ]= qs & 0x0F 281codes [:,16 :32 ]= qs >> 4 282return codes ,scales 283 284 285def from_s4_iq4_nl (parts ): 286codes ,scales = parts 287return (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): 294d = fp16(x.d) 295for ib in 0..7: # QK_K/32 groups 296ls = ((scales_l[ib/2] >> 4*(ib%2)) & 0xf) | (((scales_h >> 2*ib) & 3) << 4) 297dl = d * (ls - 32) 298for j in 0..15: 299y[j + 0] = dl * kvalues_iq4nl[qs[j] & 0xf] 300y[j + 16] = dl * kvalues_iq4nl[qs[j] >> 4] 301qs += 16 302 303The 6-bit scale `ls` is split across TWO parallel arrays by element index: `scales_l` holds one nibble 304per 32-element group (two groups per byte, low nibble first) and the `uint16_t scales_h` holds the top 305two bits of each group's scale at bit offset `2*ib`. Reading a group's scale out of `scales_l` alone is 306right for values under 16 and silently wrong above it. 307""" 308n = len (raw )// 136 309a = np .frombuffer (raw ,dtype = np .uint8 ).reshape (n ,136 ) 310d = np .ascontiguousarray (a [:,0 :2 ]).view (np .float16 ).astype (np .float32 ).reshape (- 1 ) 311sh = np .ascontiguousarray (a [:,2 :4 ]).view (np .uint16 ).astype (np .int32 ).reshape (- 1 )# uint16 scales_h 312sl = a [:,4 :8 ].astype (np .int32 )# scales_l[QK_K/64] = 4 bytes 313qs = a [:,8 :136 ]# qs[QK_K/2] = 128 bytes 314 315ls = np .empty ((n ,8 ),dtype = np .int32 ) 316for ib in range (8 ): 317ls [:,ib ]= ((sl [:,ib // 2 ]>> (4 * (ib % 2 )))& 0xF )| (((sh >> (2 * ib ))& 3 )<< 4 ) 318scales = d [:,None ]* (ls - 32 ).astype (np .float32 )# integer bias, then ONE f32 multiply 319 320codes = np .empty ((n ,256 ),dtype = np .uint8 ) 321for ib in range (8 ): 322blk = qs [:,ib * 16 :(ib + 1 )* 16 ] 323codes [:,ib * 32 :ib * 32 + 16 ]= blk & 0x0F # low nibbles -> first 16 of the group 324codes [:,ib * 32 + 16 :ib * 32 + 32 ]= blk >> 4 # high nibbles -> second 16 325return codes ,scales 326 327 328def from_s4_iq4_xs (parts ): 329codes ,scales = parts 330return (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): 337qh = the 4 bytes of x.qh read as a native uint32 338for j in 0..15: 339xh_0 = ((qh >> (j + 0)) << 4) & 0x10 340xh_1 = ((qh >> (j + 12)) ) & 0x10 341x0 = ((qs[j] & 0x0F) | xh_0) - 16 ; y[j + 0] = x0*d 342x1 = ((qs[j] >> 4) | xh_1) - 16 ; y[j + 16] = x1*d 343 344The 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 345element, 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 347answer, which is worth knowing before "fixing" it. 348""" 349n = len (raw )// 22 350a = np .frombuffer (raw ,dtype = np .uint8 ).reshape (n ,22 ) 351scales = np .ascontiguousarray (a [:,0 :2 ]).view (np .float16 ).astype (np .float32 ).reshape (- 1 ) 352qh = np .ascontiguousarray (a [:,2 :6 ]).view ("<u4" ).reshape (- 1 )# little-endian native read 353qs = a [:,6 :22 ]# (n, 16) 354j = np .arange (16 ) 355xh0 = (((qh [:,None ]>> j [None , :])& 1 )<< 4 ).astype (np .uint8 ) 356xh1 = (((qh [:,None ]>> (j [None , :]+ 16 ))& 1 )<< 4 ).astype (np .uint8 ) 357codes = np .empty ((n ,32 ),dtype = np .uint8 ) 358codes [:,0 :16 ]= (qs & 0x0F )| xh0 # low nibbles -> first half 359codes [:,16 :32 ]= (qs >> 4 )| xh1 # high nibbles -> second half 360return codes ,scales 361 362 363def from_s8_q5_0 (parts ): 364codes ,scales = parts 365v = (codes .astype (np .int32 )- 16 ).astype (np .float32 )# the -16 is inside the integer 366return (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): 373d = fp16(x.d) ; min = fp16(x.dmin) 374is = 0 ; u1 = 1 ; u2 = 2 375for 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 378for l in 0..31: y++ = d1 * ((ql[l] & 0xF) + (qh[l] & u1 ? 16 : 0)) - m1 379for l in 0..31: y++ = d2 * ((ql[l] >> 4) + (qh[l] & u2 ? 16 : 0)) - m2 380ql += 32 ; is += 2 ; u1 <<= 2 ; u2 <<= 2 381 382Identical in shape to `Q4_K` - same `get_scale_min_k4`, same 8 groups of 32, same low-nibbles-then-high 383order - with a 5th bit added. `qh` does NOT advance inside the loop: the same 32 bytes are re-read by 384all four 64-element steps, and what selects a distinct bit each time is `u1`/`u2` walking 1,4,16,64 and 3852,8,32,128. This is the Q3_K hmask trap again, and it is why the masks are written out rather than the 386high bit being folded into `ql` once. 387""" 388n = len (raw )// 176 389a = np .frombuffer (raw ,dtype = np .uint8 ).reshape (n ,176 ) 390d = np .ascontiguousarray (a [:,0 :2 ]).view (np .float16 ).astype (np .float32 ).reshape (- 1 ) 391dmin = np .ascontiguousarray (a [:,2 :4 ]).view (np .float16 ).astype (np .float32 ).reshape (- 1 ) 392scb = a [:,4 :16 ]# scales[K_SCALE_SIZE] - the same packed 6-bit pairs 393qh = a [:,16 :48 ]# qh[QK_K/8] 394qs = a [:,48 :176 ]# qs[QK_K/2] 395 396scales = np .empty ((n ,8 ),dtype = np .float32 ) 397offsets = np .empty ((n ,8 ),dtype = np .float32 ) 398for g in range (8 ): 399sc = np .array ([get_scale_min_k4 (scb [i ],g )[0 ]for i in range (n )],dtype = np .float32 ) 400m = np .array ([get_scale_min_k4 (scb [i ],g )[1 ]for i in range (n )],dtype = np .float32 ) 401scales [:,g ]= d * sc 402offsets [:,g ]= - (dmin * m ) 403 404codes = np .empty ((n ,256 ),dtype = np .uint8 ) 405for j in range (4 ): 406blk = qs [:,j * 32 :(j + 1 )* 32 ] 407u1 ,u2 = 1 << (2 * j ),2 << (2 * j ) 408lo = (blk & 0x0F )+ np .where (qh & u1 ,16 ,0 ).astype (np .uint8 ) 409hi = (blk >> 4 )+ np .where (qh & u2 ,16 ,0 ).astype (np .uint8 ) 410codes [:,j * 64 :j * 64 + 32 ]= lo # group is+0: LOW nibbles 411codes [:,j * 64 + 32 :j * 64 + 64 ]= hi # group is+1: HIGH nibbles 412return codes ,scales ,offsets 413 414 415def from_s8_q5_k (parts ): 416codes ,scales ,offsets = parts 417v = codes .astype (np .float32 ).reshape (codes .shape [0 ],8 ,32 ) 418return (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): 425d = fp16(x.d) 426for n in {0, 128}: # ql += 64, qh += 32, sc += 8 per half 427for l in 0..31: 428is = l/16 429q1 = ((ql[l + 0] & 0xF) | (((qh[l] >> 0) & 3) << 4)) - 32 430q2 = ((ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4)) - 32 431q3 = ((ql[l + 0] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32 432q4 = ((ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32 433y[l + 0] = d * sc[is + 0] * q1 434y[l + 32] = d * sc[is + 2] * q2 435y[l + 64] = d * sc[is + 4] * q3 436y[l + 96] = d * sc[is + 6] * q4 437 438Four 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`, 440q3 fills `l+64`, q4 fills `l+96`. So the scale index is not `l/16` in any simple reading of the quads; 441what it works out to is `(element / 16) % 8` within the half, i.e. plain consecutive 16-element groups. 442 443Two 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`, 445so a negative scale is a sign flip and must be preserved, which is why the scale plane is read signed. 446""" 447n = len (raw )// 210 448a = np .frombuffer (raw ,dtype = np .uint8 ).reshape (n ,210 ) 449ql = a [:,0 :128 ]# ql[QK_K/2] 450qh = a [:,128 :192 ]# qh[QK_K/4] 451sc = a [:,192 :208 ].view (np .int8 )# scales[QK_K/16], SIGNED 452d = np .ascontiguousarray (a [:,208 :210 ]).view (np .float16 ).astype (np .float32 ).reshape (- 1 ) 453 454scales = d [:,None ]* sc .astype (np .float32 )# `d * sc` first, the leftmost multiply 455 456codes = np .empty ((n ,256 ),dtype = np .uint8 ) 457for half in range (2 ): 458qlb = ql [:,half * 64 :(half + 1 )* 64 ] 459qhb = 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 461quads = [(qlb [:,0 :32 ]& 0x0F ,0 ), (qlb [:,32 :64 ]& 0x0F ,2 ), 462 (qlb [:,0 :32 ]>> 4 ,4 ), (qlb [:,32 :64 ]>> 4 ,6 )] 463for qidx , (nib ,sh )in enumerate (quads ): 464seg = nib | (((qhb >> sh )& 0x03 )<< 4 ) 465codes [:,half * 128 + qidx * 32 :half * 128 + qidx * 32 + 32 ]= seg 466return codes ,scales 467 468 469def from_s8_q6_K (parts ): 470codes ,scales = parts 471v = (codes .astype (np .int32 )- 32 ).astype (np .float32 ) 472return (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.""" 481v = np .frombuffer (raw ,dtype = "<f4" ) 482return v ,np .ones (len (v ),dtype = np .float32 ) 483 484 485def from_p32_f32 (parts ): 486return 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 492P32 and not P16: bf16 has the f32 exponent range and fp16 does not, so an fp16 container would send 493large-magnitude weights to infinity. This is the one case where the wider container is the SAFE one. 494""" 495v = np .frombuffer (raw ,dtype = "<u2" ).astype (np .uint32 )<< 16 496return v .view (np .float32 ),np .ones (len (v ),dtype = np .float32 ) 497 498 499def from_p32_bf16 (parts ): 500return 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.""" 505return np .frombuffer (raw ,dtype = "<f2" ),np .ones (len (raw )// 2 ,dtype = np .float32 ) 506 507 508def from_p16_f16 (parts ): 509return 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 528Returns (codes, scales) with codes `(nblocks, 64)` uint8 holding ONE 2-bit code per element - the same 529contract every other mapping in this file honours - and scales `(nblocks,)` float32, the fp16 `d` widened 530exactly. 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 533This 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 535element count, and for Q2_0 that came out at 1/4 of the truth. A representation that is only correct 536when read back by its own decoder is not a canonical form - a pack has to be able to state the element 537count on its own. 538""" 539n = len (raw )// BLOCK_BYTES 540a = np .frombuffer (raw ,dtype = np .uint8 ).reshape (n ,BLOCK_BYTES ) 541scales = np .ascontiguousarray (a [:,0 :2 ]).view (np .float16 ).astype (np .float32 ).reshape (- 1 ) 542qb = a [:,2 :BLOCK_BYTES ]# (n, 16) packed 2-bit codes 543codes = np .empty ((n ,QK ),dtype = np .uint8 ) 544for t in range (4 ): 545codes [:,t ::4 ]= (qb >> (2 * t ))& 0x03 546return 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 552One integer subtract then ONE f32 multiply, in that order, for the reason docs/pack-format.md §3.1 gives: 553folding the bias into the value domain is not bit-exact. 554""" 555codes ,scales = parts 556v = (codes .astype (np .int32 )- 1 ).astype (np .float32 ) 557return (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 582Q2_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 584them with this project's OWN `_bf16_to_f32` and numpy views, so for those the project's reference would 585be 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""" 587buf = np .frombuffer (raw ,dtype = np .uint8 ) 588if tname in ("F32" ,"F16" ,"BF16" ): 589from _paths import gguf_lib 590g = gguf_lib () 591return np .asarray (g .quants .dequantize (buf ,g .GGMLQuantizationType [tname ]),dtype = np .float32 ) 592return 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 599decoder, so a pass there is a self-consistency result: it cannot detect a misreading of the format that 600the decoder and the canonicaliser share. Q2_0 is the only `project` row and it is 31.64 GiB of the 601artifact, so the distinction matters and is therefore never left implicit. 602""" 603return "project (Q2_0 decoder) - SELF-CONSISTENCY, oracle-backed by dequant_xcheck" \ 604if 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 610This replaced `fh.read()`, which loaded all 37.6 GB of shard 1 into RAM. It worked, which is exactly why 611it was worth removing: a tool that only survives because the machine has 64 GB is not a tool that reports 612its own limits, and it would have gone unnoticed until a machine with less memory ran it. 613""" 614fh = open (path ,"rb" ) 615mm = mmap .mmap (fh .fileno (),0 ,access = mmap .ACCESS_READ ) 616return 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 623private accessors. 624""" 625return 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 631P1.T3 is stated as "for every tensor of the real GGUF, dequant(canonical) == dequant_ggml(original) bit 632for bit". A per-block identity is a pure function of that block's bytes, so a sample of blocks can only 633ever be evidence ABOUT a subset; this mode removes the qualifier. It also reports the DATA-DEPENDENT 634branches each type actually exercised, because those are the paths a sample can miss entirely: a scale 635that never reaches 16 never tests the high bits of `IQ4_XS`'s `ls`, and an hmask whose top nibble is never 636set never tests `Q3_K`'s second-half mask. 637""" 638f = G .GGUFFile (pathlib .Path (args .gguf )) 639head ,filelen = open_shard (args .gguf ) 640data_off = data_section_offset (f ,filelen ) 641"shard %s: %d tensors, data at byte %d" % (args .gguf ,len (f .tensors ),data_off )) 642 643by_type = collections .defaultdict (list ) 644want = {s .strip ()for s in args .types .split ("," )} 645si ,sn = (int (x )for x in args .split .split ("/" )) 646if not 0 <= si < sn : 647"--split %s: need 0 <= I < N" % args .split ) 648return 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. 651for idx ,t in enumerate (f .tensors ): 652if idx % sn == si : 653by_type [t .type_name ].append (t ) 654if sn > 1 : 655"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 ))) 657for tn in sorted (by_type ): 658if tn not in MAPPINGS : 659" %-8s %5d tensors NO MAPPING - not covered" % (tn ,len (by_type [tn ]))) 660elif tn not in want : 661" %-8s %5d tensors EXCLUDED by --types" % (tn ,len (by_type [tn ]))) 662 663total_t = total_b = total_bad = 0 664ok = True 665for tname in sorted (by_type ): 666if tname not in MAPPINGS or tname not in want : 667continue 668m = MAPPINGS [tname ] 669nblocks_sec = max (1 ,args .chunk // m .block_bytes )# WHOLE blocks per chunk 670n_t = n_b = n_bad = 0 671t0 = time .time () 672seen = collections .Counter () 673for t in by_type [tname ]: 674if t .elements % m .block_elems : 675" %-34s %d elements not a multiple of %d - SKIPPED" % (t .name ,t .elements ,m .block_elems )) 676ok = False 677continue 678nb = t .elements // m .block_elems 679base = data_off + t .offset 680first_bad = None 681for s in range (0 ,nb ,nblocks_sec ): 682cnt = min (nblocks_sec ,nb - s ) 683raw = head [base + s * m .block_bytes :base + (s + cnt )* m .block_bytes ] 684if len (raw )!= cnt * m .block_bytes : 685" %-34s SHORT READ at block %d - instrument error" % (t .name ,s )) 686ok = False 687break 688ref = reference_values (tname ,raw ) 689got = m .dec (m .enc (raw )) 690if ref .shape != got .shape : 691" %-34s SHAPE %s vs %s - instrument error" % (t .name ,ref .shape ,got .shape )) 692ok = False 693break 694ne = np .nonzero (ref != got )[0 ] 695n_b += cnt 696if ne .size : 697n_bad += ne .size 698if first_bad is None : 699first_bad = (s + int (ne [0 ])// m .block_elems ,int (ne [0 ])) 700if args .branches : 701codes = m .enc (raw )[0 ] 702seen ["code_hi=%d" % int (codes .max ())]+= 1 703seen ["code_lo=%d" % int (codes .min ())]+= 1 704n_t += 1 705if first_bad is not None : 706" %-34s FIRST MISMATCH at block %d element %d" % (t .name ,first_bad [0 ],first_bad [1 ])) 707ok = False 708dt = time .time ()- t0 709total_t += n_t 710total_b += n_b 711total_bad += n_bad 712" %-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 , 714reference_name (tname ))) 715if args .branches and seen : 716" branch reach: %s" % " " .join ("%s x%d" % kv for kv in sorted (seen .items ()))) 717"P1.T3 full: %d tensors, %d blocks, %d mismatched elements" % (total_t ,total_b ,total_bad )) 719"tools/canonical_xcheck.py --full " + ("PASS" if ok else "FAIL" )) 720return 0 if ok else 1 721 722 723def main ()-> int : 724ap = argparse .ArgumentParser () 725ap .add_argument ("--gguf" ,default = SHARD1 ) 726ap .add_argument ("--types" ,default = "," .join (MAPPINGS ), 727help = "source types to test, one mapping each; default is every mapped type" ) 728ap .add_argument ("--tensors" ,type = int ,default = 2 ,help = "tensors per type" ) 729ap .add_argument ("--blocks" ,type = int ,default = 2048 ,help = "blocks per tensor" ) 730ap .add_argument ("--full" ,action = "store_true" , 731help = "P1.T3 over every block of every tensor (overrides --tensors/--blocks)" ) 732ap .add_argument ("--chunk" ,type = int ,default = 64 << 20 ,help = "bytes of source per streaming step" ) 733ap .add_argument ("--branches" ,action = "store_true" ,help = "report code range reached per type" ) 734ap .add_argument ("--split" ,default = "0/1" , 735help = "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." ) 738args = ap .parse_args () 739if args .full : 740return run_full (args ) 741 742f = G .GGUFFile (pathlib .Path (args .gguf )) 743"shard: %d tensors" % len (f .tensors )) 744head ,filelen = open_shard (args .gguf ) 745data_off = data_section_offset (f ,filelen ) 746"data section starts at byte %d (file %d bytes)" % (data_off ,filelen )) 747 748ok = True 749covered = 0 750for tname in args .types .split ("," ): 751tname = tname .strip () 752if tname not in MAPPINGS : 753" %s: NO MAPPING in this tool yet" % tname ) 754continue 755m = MAPPINGS [tname ] 756tensors = [t for t in f .tensors if t .type_name == tname ] 757covered += len (tensors ) 758"--- %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 , 761m .group_elems ,len (tensors ))) 762for t in tensors [:args .tensors ]: 763if t .elements % m .block_elems : 764" %-34s %d elements is not a whole number of %d-element blocks - SKIPPED" 765% (t .name ,t .elements ,m .block_elems )) 766continue 767want = min (args .blocks ,t .elements // m .block_elems )* m .block_bytes 768byte_off = data_off + t .offset 769raw = head [byte_off :byte_off + want ] 770if len (raw )< want : 771" %-34s SHORT READ (%d of %d) - instrument error" % (t .name ,len (raw ),want )) 772ok = False 773continue 774ref = reference_values (tname ,raw ) 775parts = m .enc (raw ) 776got = m .dec (parts ) 777if ref .shape != got .shape : 778" %-34s SHAPE %s ref vs %s got - instrument error" % (t .name ,ref .shape ,got .shape )) 779ok = False 780continue 781same = np .array_equal (ref ,got ) 782d = np .abs (ref .astype (np .float64 )- got .astype (np .float64 )) 783" %-34s %6d blocks %s max|d| %.3e" 784% (t .name ,want // m .block_bytes ,"BIT-EXACT" if same else "*** MISMATCH ***" ,d .max ())) 785if not same : 786bad = np .nonzero (ref != got )[0 ] 787" first differing element %d: ref %r got %r" % (bad [0 ],ref [bad [0 ]],got [bad [0 ]])) 788ok = False 789if m .block_elems <= 256 :# a value set is informative for a quantized block, noise for f32 790vals = np .unique (got [:m .block_elems ]) 791" first block's value set: %s" % np .array2string (vals ,precision = 6 )) 792"mapped types cover %d of %d tensors in this shard" % (covered ,len (f .tensors ))) 794"tools/canonical_xcheck.py " + ("PASS" if ok else "FAIL" )) 795return 0 if ok else 1 796 797 798if __name__ == "__main__" : 799raise SystemExit (main ())