okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0f1e5e4cb
main
1"""tools/iq_fixture.py - deterministic i-quant fixtures for src/kernels/iq_parity.cpp (TODO 24). 2 3For each of the ten types iq_parity tests, writes `<out>/<name>.bin` (int32 header: the KERNEL type id, 4rows, cols - then the raw GGUF block bytes) and `<out>/<name>.f32` (rows*cols float32 reference values, 5dequantized by the same library the comparison treats as ground truth): 6 7python tools/iq_fixture.py --out build/iq_fixture 8python tools/iq_fixture.py --out build/iq_fixture --seed 7 --rows 32 --cols 256 9 10Generation is deterministic: an explicit seed and fixed dimensions, and every random choice comes from 11numpy's RandomState under that seed. The blocks are synthetic on purpose: the i-quant formats have no 12published quantizer in gguf-py (it dequantizes only), so each block combines sane half-precision scales 13(written at the layout's scale offsets, see SCALE_OFFSETS below) with seeded index/sub-scale bytes - the 14dequantized reference covers real codebook values either way, which is what the parity compares. 15 16Dependencies: python3 and numpy (the dequantizers are tools/strata_quants.py, proven bit-identical to llama.cpp's gguf-py by 17tools/test_strata_gguf.py; STRATA_GGUF_PY=<gguf-py folder> uses gguf-py's instead). Q2_0 is this repository's own format 18(GGML type 42): its codec comes from tools/gguf_writer.py. 19 20The kernel ids in the .bin headers are the repo's i-quant dispatch table (iq_kernels.cu is_iq / 21iq_row_bytes) and match the vendored gguf-py's enum ids one for one - the layout table below is the 22same GGML_QUANT_SIZES both sides compile in. 23""" 24from __future__import annotations 25 26import argparse 27import struct 28import sys 29from pathlib import Path 30 31import numpy as np 32 33ROOT = Path (__file__ ).resolve ().parents [1 ] 34sys .path .insert (0 ,str (ROOT / "tools" )) 35 36try : 37from _paths import gguf_lib 38gguf = gguf_lib ()# tools/strata_gguf.py (STRATA_GGUF_PY selects llama.cpp's gguf-py) 39gguf_dequantize = gguf .quants .dequantize 40from gguf_writer import dequantize_q2_0 ,quantize_q2_0 41except ImportError as e :# a missing numpy must be explicit, not a traceback 42sys .stderr .write (f"iq_fixture: missing dependency: { e } \nnumpy is required.\n" ) 43sys .exit (3 ) 44 45QT = gguf .GGMLQuantizationType 46# name -> (block values, block bytes, the fp16 scale offsets inside a block). The layouts mirror 47# gguf-py's dequantize_blocks implementations: every one of these formats keeps its half-precision 48# scale(s) at fixed offsets (IQ*_X*: offset 0; Q3_K: after the 32-byte hmask, 64-byte qs and the 49# 12 scale bytes) - the rest of the block is indices and sub-scales, which are seeded random bytes. 50LAYOUT = {# (block values, block bytes) == the vendored gguf-py's GGML_QUANT_SIZES == the kernels' sizes 51"IQ2_XXS" : (256 ,66 ), 52"IQ2_XS" : (256 ,74 ), 53"IQ2_S" : (256 ,82 ), 54"IQ3_XXS" : (256 ,98 ), 55"IQ3_S" : (256 ,110 ), 56"IQ1_M" : (256 ,56 ), 57"IQ4_NL" : (32 ,18 ), 58"IQ4_XS" : (256 ,136 ), 59"Q3_K" : (256 ,110 ), 60} 61HALF_ONE = struct .pack ("<e" ,1.0 )# fp16 1.0 = 0x3c00: a tame, exactly-representable scale 62 63 64def repair_scales (name :str ,raw :np .ndarray )-> None : 65"""Overwrite the fp16 scale bits of every block with a sane value, in place. The index and 66sub-scale bytes stay seeded-random (their values are bounded by construction). Layouts mirror 67gguf-py's dequantize_blocks: IQ*_X* and IQ4_* keep the fp16 scale at block offset 0; Q3_K keeps 68it after the 32-byte hmask, 64-byte qs and 12 scale bytes; IQ1_M is "the only one which stores 69the f16 scale in multiple parts" - the fp16 bits are the HIGH NIBBLES of the four uint16s at 70bytes 48..56, so a 1.0 scale is nibbles 3, C, 0, 0 on bytes 49, 51, 54, 55.""" 71if name == "Q3_K" : 72raw [:,108 :110 ]= np .frombuffer (HALF_ONE ,dtype = np .uint8 ) 73return 74if name == "IQ1_M" : 75raw [:,48 :56 ]&= np .uint8 (0x0F )# clear the four scale nibbles 76for byte ,nib in ((49 ,0x30 ), (51 ,0xC0 ), (54 ,0x00 ), (55 ,0x00 )): 77raw [:,byte ]|= np .uint8 (nib ) 78return 79raw [:,0 :2 ]= np .frombuffer (HALF_ONE ,dtype = np .uint8 ) 80# name -> (the KERNEL type id written into the .bin header, identical to the gguf-py enum id) 81KERNEL_IDS = {"IQ2_XXS" :16 ,"IQ2_XS" :17 ,"IQ2_S" :22 ,"IQ3_XXS" :18 ,"IQ3_S" :21 , 82"IQ1_M" :29 ,"IQ4_NL" :20 ,"IQ4_XS" :23 ,"Q2_0" :42 ,"Q3_K" :11 } 83 84 85def build (name :str ,rows :int ,cols :int ,seed :int ): 86"""The .bin body (header + raw blocks) and the .f32 reference for one type.""" 87kernel_type = KERNEL_IDS [name ] 88n = rows * cols 89rng = np .random .RandomState ((seed ,hash (name )& 0xFFFF )if False else (seed ,KERNEL_IDS [name ])) 90if name == "Q2_0" :# the repository's own codec, gguf-py has no type 42 91w = rng .standard_normal (n ).astype (np .float32 ) 92raw = np .frombuffer (quantize_q2_0 (w ),dtype = np .uint8 ) 93ref = dequantize_q2_0 (raw .tobytes ()).astype (np .float32 ) 94flat = raw 95else : 96block_values ,block_bytes = LAYOUT [name ] 97blocks = n // block_values 98raw = rng .randint (0 ,256 , (blocks ,block_bytes ),dtype = np .uint8 ) 99repair_scales (name ,raw )# sane fp16 scales; indices stay seeded-random 100flat = raw .reshape (- 1 ) 101ref = np .asarray (gguf_dequantize (flat ,getattr (QT ,name )),dtype = np .float32 ) 102if not np .isfinite (ref ).all ()or float (np .abs (ref ).max ())> 1e4 : 103raise RuntimeError (f" { name } : the dequantized reference is not finite/tame - the layout table " 104f"(block bytes, scale offsets) does not match gguf-py's dequantizer" ) 105header = struct .pack ("<3i" ,kernel_type ,rows ,cols ) 106return header + flat .tobytes (),ref 107 108 109def main ()-> int : 110ap = argparse .ArgumentParser (description = __doc__ .split ("\n\n" )[0 ], 111formatter_class = argparse .RawDescriptionHelpFormatter ) 112ap .add_argument ("--out" ,default = "logs/iq_fixture" ,help = "the fixture directory (created; may live in the " 113"build directory - the source tree is not written)" ) 114ap .add_argument ("--seed" ,type = int ,default = 7 ,help = "the fixture RNG seed (deterministic generation)" ) 115ap .add_argument ("--rows" ,type = int ,default = 32 ,help = "weight rows (rows*cols stays a multiple of 256)" ) 116ap .add_argument ("--cols" ,type = int ,default = 256 ,help = "the reduction dimension, a multiple of 256" ) 117args = ap .parse_args () 118if args .cols % 256 or args .rows * args .cols % 256 : 119ap .error ("--cols must be a multiple of 256 and rows*cols a multiple of 256" ) 120out = Path (args .out ) 121out .mkdir (parents = True ,exist_ok = True ) 122for name in KERNEL_IDS : 123blob ,ref = build (name ,args .rows ,args .cols ,args .seed ) 124 (out / f" { name } .bin" ).write_bytes (blob ) 125 (out / f" { name } .f32" ).write_bytes (np .ascontiguousarray (ref ,dtype = "<f4" ).tobytes ()) 126f" { name :<8 } type { KERNEL_IDS [ name ]:>2 } { args . rows } x { args . cols } " 127f" { len ( blob ) - 12 } block bytes, { ref . size } reference floats" ) 128f"iq_fixture: { len ( KERNEL_IDS ) } fixtures in { out } (seed { args . seed } )" ) 129return 0 130 131 132if __name__ == "__main__" : 133sys .exit (main ())