okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
01529aaa8
main
1"""A minimal GGUF v3 WRITER, including `Q2_0`. 2 3Why this exists 4--------------- 5P1.S1 of the plan says the tiny synthetic model is "written as a real GGUF via `gguf-py`" using 6"at least `Q2_0`". That does not work: `gguf-py` has no `GGMLQuantizationType` member for type 42, so 7`GGMLQuantizationType(42)` raises `ValueError`. Verified in round 39 and again here. 8 9`src/artifact/` needs a writer regardless - P1.S2 requires a reader with no ggml dependency, and the 10writer is its companion - so this is that writer in Python, where it can be validated immediately 11against `tools/gguf_reader.py` and against llama.cpp. 12 13Scope: enough to build the P1.S1 tiny model. It is NOT a general-purpose quantizer; the only 14quantizer implemented is `Q2_0`, and its contract is `docs/q2_0-contract.md`: 15block = 64 elements, fp16 scale, 16 bytes of 2-bit codes, LSB-first, 4 codes per byte 16d = amax, code = clamp(round(w/d) + 1, 0, 3), symbol = code - 1 -> {-1, 0, +1, +2} 17 18Self-checking: `python tools/gguf_writer.py` writes a synthetic v3 file, reads it back with 19`gguf_reader.py`, and asserts the tensors and metadata survived byte-exactly. 20""" 21from __future__import annotations 22 23import dataclasses 24import pathlib 25import struct 26import sys 27 28import numpy as np 29 30sys .path .insert (0 ,str (pathlib .Path (__file__ ).resolve ().parent )) 31from gguf_reader import GGUF_MAGIC ,GGUFFile # noqa: E402 32 33# ggml_type ids we can write. Values match GGML_TYPES in gguf_reader.py. 34TYPE_IDS = {"F32" :0 ,"F16" :1 ,"Q2_0" :42 } 35DEFAULT_ALIGNMENT = 32 36 37_META_IDS = {"u8" :0 ,"i8" :1 ,"u16" :2 ,"i16" :3 ,"u32" :4 ,"i32" :5 ,"f32" :6 , 38"bool" :7 ,"string" :8 ,"array" :9 ,"u64" :10 ,"i64" :11 ,"f64" :12 } 39 40 41# ------------------------------------------------------------------ Q2_0, per docs/q2_0-contract.md 42def quantize_q2_0 (w :np .ndarray )-> bytes : 43"""(n,) float32 -> concatenated 18-byte blocks. n must be a multiple of 64.""" 44w = np .asarray (w ,dtype = np .float32 ).reshape (- 1 ) 45if w .size % 64 : 46raise ValueError (f"Q2_0 needs a multiple of 64 elements, got { w . size } " ) 47blocks = w .reshape (- 1 ,64 ) 48out = bytearray () 49for b in blocks : 50amax = float (np .max (np .abs (b ))) 51d = amax 52# d = amax (NOT amax/2) - the grid is asymmetric, symbols land in {-1,0,+1,+2}. 53code = np .zeros (64 ,dtype = np .uint8 )if d == 0 else \ 54np .clip (np .rint (b / d ).astype (np .int32 )+ 1 ,0 ,3 ).astype (np .uint8 ) 55packed = np .zeros (16 ,dtype = np .uint8 ) 56# j -> byte j//4, bit (j%4)*2 ; four codes per byte, least significant first. 57for j in range (64 ): 58packed [j // 4 ]|= np .uint8 (code [j ]<< ((j % 4 )* 2 )) 59out += struct .pack ("<e" ,d )# fp16 scale 60out += packed .tobytes () 61return bytes (out ) 62 63 64def dequantize_q2_0 (raw :bytes )-> np .ndarray : 65"""Inverse of the above, for the round-trip check. Mirrors `dequantize_row_q2_0`.""" 66nblocks = len (raw )// 18 67out = np .empty (nblocks * 64 ,dtype = np .float32 ) 68for i in range (nblocks ): 69d = struct .unpack_from ("<e" ,raw ,i * 18 )[0 ] 70qs = raw [i * 18 + 2 :i * 18 + 18 ] 71for j in range (64 ): 72c = (qs [j // 4 ]>> ((j % 4 )* 2 ))& 0x03 73out [i * 64 + j ]= (c - 1 )* d 74return out 75 76 77# ------------------------------------------------------------------ writer 78@ dataclasses . dataclass 79class _Tensor : 80name :str 81shape :list [int ]# GGUF order: dim 0 varies fastest 82type_name :str 83data :bytes 84 85 86class GGUFWriter : 87def __init__ (self ,alignment :int = DEFAULT_ALIGNMENT ): 88self .alignment = alignment 89self .metadata :dict [str ,tuple [str ,object ]]= {} 90self .tensors :list [_Tensor ]= [] 91 92# ---- metadata 93def add (self ,key :str ,value ,type_name :str | None = None )-> None : 94if type_name is None : 95type_name = {bool :"bool" ,int :"i64" ,float :"f64" ,str :"string" }.get (type (value )) 96if type_name is None : 97if isinstance (value ,list )and value : 98elem = {bool :"bool" ,int :"i32" ,float :"f32" ,str :"string" }.get (type (value [0 ])) 99if elem is None : 100raise TypeError (f"unsupported array element { type ( value [ 0 ]) } for { key } " ) 101type_name = "array:" + elem 102else : 103raise TypeError (f"cannot infer a GGUF type for { key } " ) 104self .metadata [key ]= (type_name ,value ) 105 106# ---- tensors 107def add_f32 (self ,name :str ,arr :np .ndarray )-> None : 108a = np .ascontiguousarray (arr ,dtype = "<f4" ) 109self .tensors .append (_Tensor (name ,list (a .shape ),"F32" ,a .tobytes ())) 110 111def add_q2_0 (self ,name :str ,arr :np .ndarray ,shape :list [int ])-> None : 112"""`arr` is (rows, in_features) row-major with every row `shape[0]` long; `shape` is the FULL 113GGUF shape. The shape must be passed explicitly, not inferred as [in, rows]: a fused expert 114tensor is [in, out, experts], and inferring 2-D produced `[64, 4096]` where llama.cpp expects 115`[64, 256, 16]`. Q2_0 blocks run along dim 0 only, so the extra axes are just a layout. 116""" 117a = np .asarray (arr ,dtype = np .float32 ) 118in_features = shape [0 ] 119if a .ndim != 2 or a .shape [1 ]!= in_features : 120raise ValueError (f" { name } : expected (rows, { in_features } ), got { a . shape } " ) 121if a .shape [0 ]* in_features != int (np .prod (shape )): 122raise ValueError (f" { name } : { a . shape } does not cover shape { shape } " ) 123per_row = quantize_q2_0 (a .reshape (- 1 ))# row-major: row 0 first 124self .tensors .append (_Tensor (name ,list (shape ),"Q2_0" ,per_row )) 125 126# ---- serialisation 127def _kv_bytes (self ,key :str ,type_name :str ,value )-> bytes : 128out = bytearray () 129out += struct .pack ("<Q" ,len (key ))+ key .encode ("utf-8" ) 130if type_name .startswith ("array:" ): 131elem = type_name .split (":" ,1 )[1 ] 132out += struct .pack ("<I" ,_META_IDS ["array" ]) 133out += struct .pack ("<I" ,_META_IDS [elem ]) 134out += struct .pack ("<Q" ,len (value )) 135for v in value : 136out += self ._scalar (elem ,v ) 137return bytes (out ) 138out += struct .pack ("<I" ,_META_IDS [type_name ]) 139out += self ._scalar (type_name ,value ) 140return bytes (out ) 141 142@staticmethod 143def _scalar (type_name :str ,v )-> bytes : 144if type_name == "string" : 145b = v .encode ("utf-8" ) 146return struct .pack ("<Q" ,len (b ))+ b 147fmt = {"u8" :"<B" ,"i8" :"<b" ,"u16" :"<H" ,"i16" :"<h" ,"u32" :"<I" ,"i32" :"<i" , 148"f32" :"<f" ,"bool" :"<?" ,"u64" :"<Q" ,"i64" :"<q" ,"f64" :"<d" }[type_name ] 149return struct .pack (fmt ,v ) 150 151def write (self ,path )-> pathlib .Path : 152path = pathlib .Path (path ) 153body = bytearray () 154body += struct .pack ("<I" ,GGUF_MAGIC ) 155body += struct .pack ("<I" ,3 )# GGUF v3 156body += struct .pack ("<Q" ,len (self .tensors )) 157body += struct .pack ("<Q" ,len (self .metadata )) 158for k , (t ,v )in self .metadata .items (): 159body += self ._kv_bytes (k ,t ,v ) 160 161# Tensor directory: offsets are relative to the start of the data section. 162offset = 0 163infos = bytearray () 164for t in self .tensors : 165infos += struct .pack ("<Q" ,len (t .name ))+ t .name .encode ("utf-8" ) 166infos += struct .pack ("<I" ,len (t .shape )) 167infos += struct .pack (f"< { len ( t . shape ) } Q" ,* t .shape ) 168infos += struct .pack ("<I" ,TYPE_IDS [t .type_name ]) 169infos += struct .pack ("<Q" ,offset ) 170offset += len (t .data ) 171offset = (offset + self .alignment - 1 )// self .alignment * self .alignment 172body += infos 173 174pad = (- len (body ))% self .alignment 175body += b"\0" * pad 176for t in self .tensors : 177body += t .data 178pad = (- len (t .data ))% self .alignment 179body += b"\0" * pad 180 181path .write_bytes (bytes (body )) 182return path 183 184 185# ------------------------------------------------------------------ self-check 186def _selfcheck ()-> int : 187rng = np .random .default_rng (7 ) 188w = GGUFWriter () 189w .add ("general.architecture" ,"qwen4exp" ) 190w .add ("qwen4exp.block_count" ,8 ,"u32" ) 191w .add ("qwen4exp.test.array" , [1 ,2 ,3 ,4 ],"array:i32" ) 192w .add ("general.name" ,"strata tiny" ) 193 194A = rng .standard_normal ((16 ,64 )).astype (np .float32 ) 195B = rng .standard_normal ((4 ,8 )).astype (np .float32 ) 196w .add_q2_0 ("blk.0.ffn_gate_exps.weight" ,A ,64 ) 197w .add_f32 ("blk.0.ssm_a" ,B ) 198 199p = pathlib .Path (__file__ ).resolve ().parent .parent / "bench" / "tiny-selftest.gguf" 200w .write (p ) 201f"wrote { p . name } ( { p . stat (). st_size } B)" ) 202 203g = GGUFFile (p ) 204ok = True 205f" version { g . version } tensors { len ( g . tensors ) } metadata { len ( g . metadata ) } " ) 206if g .metadata .get ("general.architecture" )!= "qwen4exp" :" FAIL arch" );ok = False 207if g .metadata .get ("qwen4exp.block_count" )!= 8 :" FAIL u32" );ok = False 208if g .metadata .get ("qwen4exp.test.array" )!= [1 ,2 ,3 ,4 ]:" FAIL array" );ok = False 209 210by = {t .name :t for t in g .tensors } 211t = by .get ("blk.0.ffn_gate_exps.weight" ) 212if t is None or t .type_name != "Q2_0" or t .shape != [64 ,16 ]: 213f" FAIL tensor dir: { t } " );ok = False 214else : 215with p .open ("rb" )as fh : 216fh .seek (g .data_start + t .offset ) 217raw = fh .read (16 * 18 ) 218back = dequantize_q2_0 (raw ) 219err = np .abs (back - A .reshape (- 1 )).max () 220rel = float (np .abs (back - A .reshape (- 1 )).mean ()/ np .abs (A ).mean ()) 221f" Q2_0 round trip: max abs { err :.4f } mean rel { rel * 100 :.2f } % " 222f"(quantization error, not a write bug)" ) 223# The real check: re-quantizing the DEQUANTIZED values must be a fixed point. 224again = dequantize_q2_0 (quantize_q2_0 (back )) 225if not np .array_equal (again ,back ): 226" FAIL Q2_0 is not a fixed point under requantization" );ok = False 227else : 228" Q2_0 fixed point: PASS (requantizing the dequantized values is exact)" ) 229"SELF-CHECK " + ("PASS" if ok else "FAIL" )) 230return 0 if ok else 1 231 232 233if __name__ == "__main__" : 234raise SystemExit (_selfcheck ())