okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
11c8c701a
main
1"""tools/image/gate/te_ref.py - TEST-ONLY (OWN-5 gate harness): a numpy reference of Qwen-Image-2.1's text encoder as 2stable-diffusion.cpp 2988060 runs it for one prompt (src/conditioning/conditioner.hpp LLMEmbedder, VERSION_QWEN_IMAGE_2_1; 3src/model/te/llm.hpp, LLMArch::QWEN3_VL, text only). 4 5It is the oracle for our own GPU text encoder (step 3): the tokens, the per-layer activation ranges (what must fit the 6f16 operands of the GEMMs), and the f32 condition our encoder is measured against besides sd.cpp's own (cond.bin of 7run_set.py --dump). 8 9What sd.cpp computes (read from the pinned tree, 11-11): 10prompt = "<|im_start|>system\\nComprehend and analyze the provided prompt.<|im_end|>\\n" + "<|im_start|>user\\n" 11+ (text or " ") + "<|im_end|>\\n<|im_start|>assistant\\n" 12tokens = Qwen2 byte-level BPE (sd.cpp's own vocab: 256 bytes + merges in order + 31 special literals), the prompt 13split into [prefix | parse_prompt_attention(text) pieces | suffix], each piece encoded on its own; 14a piece's weight is its attention weight ("(word:1.2)" syntax), 1.0 for plain text 15model = Qwen3-VL-8B text model: 36 layers, hidden 4096, 32 query heads / 8 KV heads of 128, FFN 12288 (SwiGLU), 16RMSNorm eps 1e-6 before attention and FFN, per-head RMSNorm on q and k (q_norm / k_norm), rope on q and k 17after the norms (ggml IMROPE, sections 24/20/20, base 5e6; with text-only positions t = h = w = i it is the 18plain NEOX rotation of halves), causal attention, scale 1/sqrt(128), no bias anywhere 19output = the residual stream after layer 36 WITHOUT the final norm (out_layers = {36}), times the token weights 20(apply_token_weights; identity for plain text), minus the system tokens (prompt_template_encode_start_idx 21= the system prefix's token count) 22cond = float32 [n_tokens - n_system, 4096] 23 24Two arithmetic modes: 25"f32" weights dequantized exactly to f32 (the GGUF block formats, f32 maths in ggml's order), every GEMM and the 26attention in float64 rounded to float32, the rest float32. The "ideal" condition. 27"f16op" what our GPU encoder computes: weights f32 -> f16 (round to nearest even), GEMM inputs rounded to f16, 28the products accumulated exactly (float64; the GPU accumulates in f32), Q / K / V rounded to f16, scores f32, 29probabilities rounded to f16 before P.V; the rest float32. 30 31python -I -B te_ref.py <te.gguf> --out-dir D [--prompts 0-7 | --prompt-file F] [--mode f32,f16op] 32[--cmp NAME=/path/dump_p{p}_s42/cond.bin ...] [--stats] 33writes D/cond_p<p>_<mode>.npy (float32 [n, 4096]), D/tokens_p<p>.json, D/te_ref.json (comparisons, ranges) 34python -I -B te_ref.py <te.gguf> --tokens "some text" the token ids sd.cpp would build, and n_system 35--tokens-from /path/dump_p{p}_s42 compare the ids with sd.cpp's own (stage_hooks.py tokens.bin / tokens.start)""" 36from __future__import annotations 37 38import argparse 39import json 40import math 41import re 42import sys 43import time 44from pathlib import Path 45 46import numpy as np 47 48_HERE = Path (__file__ ).resolve ().parent 49for _p in (_HERE ,_HERE .parents [1 ]):# tools/image/gate, tools (gguf_reader.py) 50if str (_p )not in sys .path : 51sys .path .insert (0 ,str (_p )) 52from gguf_reader import GGUFFile # noqa: E402 53 54SYSTEM = "<|im_start|>system\nComprehend and analyze the provided prompt.<|im_end|>\n" 55USER = "<|im_start|>user\n" 56SUFFIX = "<|im_end|>\n<|im_start|>assistant\n" 57# sd.cpp tokenizers/qwen2_tokenizer.cpp qwen2_special_tokens(): ids 151643 + index (after 256 bytes + 151387 merges) 58SPECIALS = ["<|endoftext|>" ,"<|im_start|>" ,"<|im_end|>" ,"<|object_ref_start|>" ,"<|object_ref_end|>" ,"<|box_start|>" , 59"<|box_end|>" ,"<|quad_start|>" ,"<|quad_end|>" ,"<|vision_start|>" ,"<|vision_end|>" ,"<|vision_pad|>" , 60"<|image_pad|>" ,"<|video_pad|>" ,"<tool_call>" ,"</tool_call>" ,"<|fim_prefix|>" ,"<|fim_middle|>" , 61"<|fim_suffix|>" ,"<|fim_pad|>" ,"<|repo_name|>" ,"<|file_sep|>" ,"<tool_response>" ,"</tool_response>" , 62"<think>" ,"</think>" ,"<|boi_token|>" ,"<|bor_token|>" ,"<|eor_token|>" ,"<|bot_token|>" ,"<|tms_token|>" ] 63QWEN2_SPLIT = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+""" 64F16_MAX = 65504.0 65F16_MIN_NORMAL = 6.103515625e-05 66KV_IQ4NL = np .array ([- 127 ,- 104 ,- 83 ,- 65 ,- 49 ,- 35 ,- 22 ,- 10 ,1 ,13 ,25 ,38 ,53 ,69 ,89 ,113 ],dtype = np .float32 ) 67 68 69# ------------------------------------------------------------------ GGUF block formats -> f32 (ggml-quants.c order of operations) 70def _f16 (b :np .ndarray )-> np .ndarray : 71return np .ascontiguousarray (b ).view ("<f2" ).astype (np .float32 ).reshape (b .shape [0 ]) 72 73 74def _scale_min_k4 (s :np .ndarray ): 75"""get_scale_min_k4 for j = 0..7 over [nb, 12] scale bytes -> (sc [nb, 8], m [nb, 8]) as float32.""" 76s = s .astype (np .int32 ) 77sc = np .empty ((s .shape [0 ],8 ),np .int32 ) 78mn = np .empty ((s .shape [0 ],8 ),np .int32 ) 79sc [:, :4 ]= s [:,0 :4 ]& 63 80mn [:, :4 ]= s [:,4 :8 ]& 63 81sc [:,4 :]= (s [:,8 :12 ]& 0x0F )| ((s [:,0 :4 ]>> 6 )<< 4 ) 82mn [:,4 :]= (s [:,8 :12 ]>> 4 )| ((s [:,4 :8 ]>> 6 )<< 4 ) 83return sc .astype (np .float32 ),mn .astype (np .float32 ) 84 85 86def deq_q4_k (raw :np .ndarray )-> np .ndarray : 87b = raw .reshape (- 1 ,144 ) 88d ,dmin = _f16 (b [:,0 :2 ]),_f16 (b [:,2 :4 ]) 89sc ,mn = _scale_min_k4 (b [:,4 :16 ]) 90qs = b [:,16 :144 ].reshape (- 1 ,4 ,32 ) 91dl = d [:,None ]* sc # d1 = d * sc (f32) 92ml = dmin [:,None ]* mn # m1 = dmin * m 93lo = (qs & 0x0F ).astype (np .float32 ) 94hi = (qs >> 4 ).astype (np .float32 ) 95y = np .empty ((b .shape [0 ],4 ,2 ,32 ),np .float32 ) 96y [:, :,0 ]= dl [:,0 ::2 ,None ]* lo - ml [:,0 ::2 ,None ] 97y [:, :,1 ]= dl [:,1 ::2 ,None ]* hi - ml [:,1 ::2 ,None ] 98return y .reshape (- 1 ) 99 100 101def deq_q5_k (raw :np .ndarray )-> np .ndarray : 102b = raw .reshape (- 1 ,176 ) 103d ,dmin = _f16 (b [:,0 :2 ]),_f16 (b [:,2 :4 ]) 104sc ,mn = _scale_min_k4 (b [:,4 :16 ]) 105qh = b [:,16 :48 ]# [nb, 32] 106ql = b [:,48 :176 ].reshape (- 1 ,4 ,32 ) 107dl = d [:,None ]* sc 108ml = dmin [:,None ]* mn 109y = np .empty ((b .shape [0 ],4 ,2 ,32 ),np .float32 ) 110for g in range (4 ): 111u1 ,u2 = 1 << (2 * g ),2 << (2 * g ) 112lo = ((ql [:,g ]& 0x0F )+ np .where (qh & u1 ,16 ,0 )).astype (np .float32 ) 113hi = ((ql [:,g ]>> 4 )+ np .where (qh & u2 ,16 ,0 )).astype (np .float32 ) 114y [:,g ,0 ]= dl [:,2 * g ,None ]* lo - ml [:,2 * g ,None ] 115y [:,g ,1 ]= dl [:,2 * g + 1 ,None ]* hi - ml [:,2 * g + 1 ,None ] 116return y .reshape (- 1 ) 117 118 119def deq_q6_k (raw :np .ndarray )-> np .ndarray : 120b = raw .reshape (- 1 ,210 ) 121ql ,qh = b [:,0 :128 ].astype (np .int32 ),b [:,128 :192 ].astype (np .int32 ) 122sc = b [:,192 :208 ].view (np .int8 ).astype (np .float32 ) 123d = _f16 (b [:,208 :210 ]) 124y = np .empty ((b .shape [0 ],2 ,4 ,32 ),np .float32 ) 125for h in range (2 ): 126L ,H = ql [:,64 * h :64 * h + 64 ],qh [:,32 * h :32 * h + 32 ] 127q = [((L [:,0 :32 ]& 0xF )| (((H >> 0 )& 3 )<< 4 ))- 32 , ((L [:,32 :64 ]& 0xF )| (((H >> 2 )& 3 )<< 4 ))- 32 , 128 ((L [:,0 :32 ]>> 4 )| (((H >> 4 )& 3 )<< 4 ))- 32 , ((L [:,32 :64 ]>> 4 )| (((H >> 6 )& 3 )<< 4 ))- 32 ] 129for k in range (4 ): 130# y = d * (float)sc[is + 2k] * (float)q, is = l / 16 131s = np .repeat (sc [:,8 * h + 2 * k :8 * h + 2 * k + 2 ],16 ,axis = 1 )# [nb, 32] 132y [:,h ,k ]= (d [:,None ]* s )* q [k ].astype (np .float32 ) 133return y .reshape (- 1 ) 134 135 136def deq_iq4_xs (raw :np .ndarray )-> np .ndarray : 137b = raw .reshape (- 1 ,136 ) 138d = _f16 (b [:,0 :2 ]) 139sh = b [:,2 :4 ].copy ().view ("<u2" ).astype (np .int32 ).reshape (- 1 ) 140sl = b [:,4 :8 ].astype (np .int32 ) 141qs = b [:,8 :136 ].reshape (- 1 ,8 ,16 ) 142y = np .empty ((b .shape [0 ],8 ,2 ,16 ),np .float32 ) 143for ib in range (8 ): 144ls = ((sl [:,ib // 2 ]>> (4 * (ib % 2 )))& 0x0F )| (((sh >> (2 * ib ))& 3 )<< 4 ) 145dl = d * (ls - 32 ).astype (np .float32 ) 146y [:,ib ,0 ]= dl [:,None ]* KV_IQ4NL [qs [:,ib ]& 0x0F ] 147y [:,ib ,1 ]= dl [:,None ]* KV_IQ4NL [qs [:,ib ]>> 4 ] 148return y .reshape (- 1 ) 149 150 151def deq_q8_0 (raw :np .ndarray )-> np .ndarray : 152b = raw .reshape (- 1 ,34 ) 153return (_f16 (b [:,0 :2 ])[:,None ]* b [:,2 :34 ].view (np .int8 ).astype (np .float32 )).reshape (- 1 ) 154 155 156DEQ = {"Q4_K" :deq_q4_k ,"Q5_K" :deq_q5_k ,"Q6_K" :deq_q6_k ,"IQ4_XS" :deq_iq4_xs ,"Q8_0" :deq_q8_0 , 157"F32" :lambda r :r .view ("<f4" ).astype (np .float32 ),"F16" :lambda r :r .view ("<f2" ).astype (np .float32 ), 158"BF16" :lambda r : (r .view ("<u2" ).astype (np .uint32 )<< 16 ).view (np .float32 )} 159 160 161class Weights : 162def __init__ (self ,path :Path ): 163self .g = GGUFFile (path ) 164self .t = {t .name :t for t in self .g .tensors } 165self .mm = np .memmap (path ,dtype = np .uint8 ,mode = "r" ) 166md = self .g .metadata 167self .n_layer = int (md ["qwen3vl.block_count" ]) 168self .n_embd = int (md ["qwen3vl.embedding_length" ]) 169self .n_ff = int (md ["qwen3vl.feed_forward_length" ]) 170self .n_head = int (md ["qwen3vl.attention.head_count" ]) 171self .n_kv = int (md ["qwen3vl.attention.head_count_kv" ]) 172self .hd = int (md ["qwen3vl.attention.key_length" ]) 173self .theta = float (md ["qwen3vl.rope.freq_base" ]) 174self .eps = 1e-6 # llm.hpp config.rms_norm_eps for QWEN3_VL (f32 1e-6f) 175 176def raw (self ,name :str ,row0 :int = 0 ,rows :int | None = None )-> tuple [np .ndarray ,list [int ],str ]: 177t = self .t [name ] 178ne0 = t .shape [0 ] 179nrow = t .elements // ne0 180rb = t .expected_bytes ()// nrow 181rows = nrow - row0 if rows is None else rows 182a = self .g .data_start + t .offset + row0 * rb 183return np .asarray (self .mm [a :a + rows * rb ]), [ne0 ,rows ],t .type_name 184 185def mat (self ,name :str ,row0 :int = 0 ,rows :int | None = None )-> np .ndarray : 186"""float32 [rows, ne0] (the GGUF's ne1 = output features, ne0 = input features).""" 187r , (ne0 ,n ),ty = self .raw (name ,row0 ,rows ) 188return DEQ [ty ](r ).reshape (n ,ne0 ) 189 190 191# ------------------------------------------------------------------ tokens (sd.cpp's Qwen2Tokenizer + parse_prompt_attention) 192def bytes_to_unicode ()-> dict [int ,str ]: 193bs = list (range (0x21 ,0x7F ))+ list (range (0xA1 ,0xAD ))+ list (range (0xAE ,0x100 )) 194cs = bs [:] 195n = 0 196for b in range (256 ): 197if b not in bs : 198bs .append (b ) 199cs .append (256 + n ) 200n += 1 201return {b :chr (c )for b ,c in zip (bs ,cs )} 202 203 204class Qwen2Tok : 205def __init__ (self ,merges :list [str ]): 206import regex 207bu = bytes_to_unicode () 208self .byte_enc = bu 209# sd.cpp load_from_merges: tokens = the 256 byte characters in bytes_to_unicode() ORDER, then merges, then specials 210order = list (range (0x21 ,0x7F ))+ list (range (0xA1 ,0xAD ))+ list (range (0xAE ,0x100 )) 211order += [b for b in range (256 )if b not in order ] 212vocab = [bu [b ]for b in order ] 213pairs = [tuple (m .split (" " ,1 ))for m in merges ] 214vocab += [a + b for a ,b in pairs ] 215self .vocab = vocab 216self .enc = {} 217for i ,tok in enumerate (vocab ): 218self .enc [tok ]= i # std::map assignment: a later duplicate wins 219for i ,s in enumerate (SPECIALS ): 220self .enc [s ]= len (vocab )+ i 221self .ranks = {p :r for r ,p in enumerate (pairs )} 222self .pat = regex .compile (QWEN2_SPLIT ) 223 224def bpe (self ,word :str )-> list [str ]: 225w = list (word ) 226if len (w )< 2 : 227return w 228while True : 229best ,br = None ,None 230for i in range (len (w )- 1 ): 231r = self .ranks .get ((w [i ],w [i + 1 ])) 232if r is not None and (br is None or r < br ): 233best ,br = (w [i ],w [i + 1 ]),r 234if best is None : 235break 236a ,b = best 237nw ,i = [],0 238while i < len (w ): 239if i < len (w )- 1 and w [i ]== a and w [i + 1 ]== b : 240nw .append (a + b ) 241i += 2 242else : 243nw .append (w [i ]) 244i += 1 245w = nw 246if len (w )== 1 : 247break 248return w 249 250def encode (self ,text :str )-> list [int ]: 251out = [] 252for piece in split_with_special_tokens (text ,SPECIALS ): 253if piece in SPECIALS : 254out .append (self .enc [piece ]) 255continue 256for m in self .pat .findall (piece ): 257if not m : 258continue 259u = "" .join (self .byte_enc [b ]for b in m .encode ("utf-8" )) 260out += [self .enc .get (s ,151643 )for s in self .bpe (u )] 261return out 262 263 264def split_with_special_tokens (text :str ,specials :list [str ])-> list [str ]: 265res ,pos = [],0 266while pos < len (text ): 267nxt ,tok = len (text ),"" 268for s in specials : 269p = text .find (s ,pos ) 270if p != - 1 and (p < nxt or (p == nxt and len (s )> len (tok ))): 271nxt ,tok = p ,s 272if nxt > pos : 273res .append (text [pos :nxt ]) 274if tok : 275res .append (tok ) 276pos = nxt + len (tok ) 277else : 278break 279return res 280 281 282_RE_ATT = re .compile (r"\\\(|\\\)|\\\[|\\\]|\\\\|\\|\(|\[|\)|\]|\bBREAK\b|[^\\()\[\]:B]{1,1024}|:|\bB" ,re .ASCII ) 283_RE_BREAK = re .compile (r"\s*\bBREAK\b\s*" ,re .ASCII ) 284SQ = np .float32 (1 )/ np .float32 (1.1 )# square_bracket_multiplier = 1 / 1.1f (float division) 285 286 287def parse_prompt_attention (text :str )-> list [list ]: 288"""core/util.cpp parse_prompt_attention (the A1111 syntax), weights as float32 products.""" 289res ,rb ,sb = [], [], [] 290f32 = np .float32 291 292def mul (start ,m ): 293for p in range (start ,len (res )): 294res [p ][1 ]= f32 (res [p ][1 ]* f32 (m )) 295 296rest = text 297while True : 298m = _RE_ATT .search (rest ) 299if not m : 300break 301tok ,suffix = m .group (0 ),rest [m .end ():] 302if tok == ":" : 303mw = re .match (r"([+-]?[0-9.]*)\)" ,suffix ) 304if mw and mw .group (1 )not in ("" ,"+" ,"-" ): 305try : 306v = float (mw .group (1 )) 307if math .isfinite (v )and mw .group (1 ).count ("." )<= 1 and mw .group (1 )not in ("." ,"+." ,"-." ): 308if rb : 309mul (rb .pop (),v ) 310rest = suffix [mw .end ():] 311continue 312except ValueError : 313pass 314if tok == "(" : 315rb .append (len (res )) 316elif tok == "[" : 317sb .append (len (res )) 318elif tok == ")" and rb : 319mul (rb .pop (),1.1 ) 320elif tok == "]" and sb : 321mul (sb .pop (),SQ ) 322elif tok == "\\(" : 323res .append ([tok [1 :],f32 (1.0 )]) 324elif _RE_BREAK .search (tok ): 325res .append (["BREAK" ,f32 (- 1.0 )]) 326else : 327res .append ([tok ,f32 (1.0 )]) 328rest = suffix 329for p in rb : 330mul (p ,1.1 ) 331for p in sb : 332mul (p ,SQ ) 333if not res : 334res .append (["" ,f32 (1.0 )]) 335i = 0 336while i + 1 < len (res ): 337if res [i ][1 ]== res [i + 1 ][1 ]: 338res [i ][0 ]+= res [i + 1 ][0 ] 339del res [i + 1 ] 340else : 341i += 1 342return res 343 344 345def build_tokens (tok :Qwen2Tok ,text :str )-> tuple [list [int ],list [float ],int ]: 346"""LLMEmbedder::get_learned_condition (VERSION_QWEN_IMAGE_2_1, no reference images) + tokenize(): ids, weights, 347n_system (prompt_template_encode_start_idx).""" 348n_sys = len (tok .encode (SYSTEM )) 349body = text if text else " " 350pieces = [[SYSTEM + USER ,np .float32 (1.0 )]]+ parse_prompt_attention (body )+ [[SUFFIX ,np .float32 (1.0 )]] 351ids ,w = [], [] 352for s ,wt in pieces : 353t = tok .encode (s ) 354ids += t 355w += [float (wt )]* len (t ) 356return ids ,w ,n_sys 357 358 359# ------------------------------------------------------------------ the model 360def f16r (x :np .ndarray )-> np .ndarray : 361return x .astype (np .float16 ).astype (np .float32 ) 362 363 364def rmsnorm (x :np .ndarray ,w :np .ndarray ,eps :float )-> np .ndarray : 365ms = (x .astype (np .float64 )** 2 ).mean (- 1 ,keepdims = True ) 366return ((x .astype (np .float64 )/ np .sqrt (ms + np .float64 (np .float32 (eps )))).astype (np .float32 )* w ).astype (np .float32 ) 367 368 369def rope_neox (x :np .ndarray ,theta :float )-> np .ndarray : 370"""x [T, H, D]; NEOX: pairs (i, i + D/2), angle pos * theta^(-2i/D).""" 371T ,H ,D = x .shape 372i = np .arange (D // 2 ,dtype = np .float64 ) 373ang = np .arange (T ,dtype = np .float64 )[:,None ]* theta ** (- 2.0 * i / D )[None , :] 374c ,s = np .cos (ang )[:,None , :],np .sin (ang )[:,None , :] 375a ,b = x [..., :D // 2 ].astype (np .float64 ),x [...,D // 2 :].astype (np .float64 ) 376return np .concatenate ([a * c - b * s ,a * s + b * c ],- 1 ).astype (np .float32 ) 377 378 379def gemm (x :np .ndarray ,W64 :np .ndarray ,f16 :bool )-> np .ndarray : 380xi = f16r (x )if f16 else x 381return (xi .astype (np .float64 ) @W64 .T ).astype (np .float32 ) 382 383 384def _rng (stats ,key ,x ): 385if stats is None : 386return 387a = np .abs (x ) 388s = stats .setdefault (key , {"max" :0.0 ,"n" :0 ,"over_f16" :0 ,"subnormal" :0 }) 389s ["max" ]= max (s ["max" ],float (a .max ())) 390s ["n" ]+= int (a .size ) 391s ["over_f16" ]+= int ((a > F16_MAX ).sum ()) 392s ["subnormal" ]+= int (((a > 0 )& (a < F16_MIN_NORMAL )).sum ()) 393 394 395class Layer : 396def __init__ (self ,W :Weights ,i :int ,f16 :bool ): 397p = f"blk. { i } ." 398conv = (lambda a :f16r (a ).astype (np .float64 ))if f16 else (lambda a :a .astype (np .float64 )) 399self .attn_norm = W .mat (p + "attn_norm.weight" ).reshape (- 1 ) 400self .ffn_norm = W .mat (p + "ffn_norm.weight" ).reshape (- 1 ) 401self .qn = W .mat (p + "attn_q_norm.weight" ).reshape (- 1 ) 402self .kn = W .mat (p + "attn_k_norm.weight" ).reshape (- 1 ) 403self .q ,self .k ,self .v = (conv (W .mat (p + f"attn_ { n } .weight" ))for n in "qkv" ) 404self .o = conv (W .mat (p + "attn_output.weight" )) 405self .g ,self .u ,self .d = (conv (W .mat (p + f"ffn_ { n } .weight" ))for n in ("gate" ,"up" ,"down" )) 406 407 408def layer_forward (W :Weights ,L :Layer ,x :np .ndarray ,f16 :bool ,stats :dict | None ,li :int )-> np .ndarray : 409T = x .shape [0 ] 410H ,KV ,D = W .n_head ,W .n_kv ,W .hd 411h = rmsnorm (x ,L .attn_norm ,W .eps ) 412_rng (stats ,f" { li } .attn_in" ,h ) 413q = gemm (h ,L .q ,f16 ).reshape (T ,H ,D ) 414k = gemm (h ,L .k ,f16 ).reshape (T ,KV ,D ) 415v = gemm (h ,L .v ,f16 ).reshape (T ,KV ,D ) 416q = rope_neox (rmsnorm (q ,L .qn ,W .eps ),W .theta ) 417k = rope_neox (rmsnorm (k ,L .kn ,W .eps ),W .theta ) 418_rng (stats ,f" { li } .q" ,q ) 419_rng (stats ,f" { li } .k" ,k ) 420_rng (stats ,f" { li } .v" ,v ) 421if f16 : 422q ,k ,v = f16r (q ),f16r (k ),f16r (v ) 423scale = 1.0 / math .sqrt (D ) 424mask = np .triu (np .full ((T ,T ),- np .inf ),1 ) 425out = np .empty ((T ,H ,D ),np .float32 ) 426rep = H // KV 427for hh in range (H ): 428kv = hh // rep # ggml broadcast: q head i uses kv head i / (H / KV) 429s = (q [:,hh ].astype (np .float64 ) @k [:,kv ].astype (np .float64 ).T ) 430s = (s .astype (np .float32 )* np .float32 (scale )).astype (np .float64 )if f16 else s * scale 431s = s + mask 432s = s - s .max (- 1 ,keepdims = True ) 433p = np .exp (s ) 434p = p / p .sum (- 1 ,keepdims = True ) 435if f16 : 436p = f16r (p .astype (np .float32 )).astype (np .float64 ) 437out [:,hh ]= (p @v [:,kv ].astype (np .float64 )).astype (np .float32 ) 438a = out .reshape (T ,H * D ) 439_rng (stats ,f" { li } .o_in" ,a ) 440x = (x + gemm (a ,L .o ,f16 )).astype (np .float32 ) 441h = rmsnorm (x ,L .ffn_norm ,W .eps ) 442_rng (stats ,f" { li } .ffn_in" ,h ) 443g = gemm (h ,L .g ,f16 ) 444u = gemm (h ,L .u ,f16 ) 445a = ((g / (1.0 + np .exp (- g .astype (np .float64 )))).astype (np .float32 )* u ).astype (np .float32 ) 446_rng (stats ,f" { li } .down_in" ,a ) 447x = (x + gemm (a ,L .d ,f16 )).astype (np .float32 ) 448_rng (stats ,f" { li } .resid" ,x ) 449return x 450 451 452def embed (W :Weights ,ids :list [int ])-> np .ndarray : 453return np .stack ([W .mat ("token_embd.weight" ,i ,1 )[0 ]for i in ids ]).astype (np .float32 ) 454 455 456def apply_token_weights (h :np .ndarray ,w :list [float ])-> np .ndarray : 457wa = np .asarray (w ,np .float32 ) 458if np .all (wa == 1.0 ): 459return h 460m0 = np .float32 (h .astype (np .float64 ).mean ()) 461h = (h * wa [:,None ]).astype (np .float32 ) 462m1 = np .float32 (h .astype (np .float64 ).mean ()) 463return (h * np .float32 (m0 / m1 )).astype (np .float32 ) 464 465 466# ------------------------------------------------------------------ comparison 467def compare (a :np .ndarray ,b :np .ndarray )-> dict : 468a64 ,b64 = a .astype (np .float64 ).reshape (- 1 ),b .astype (np .float64 ).reshape (- 1 ) 469ma ,mb = a .astype (np .float64 ),b .astype (np .float64 ) 470tc = (ma * mb ).sum (1 )/ np .maximum (np .linalg .norm (ma ,axis = 1 )* np .linalg .norm (mb ,axis = 1 ),1e-30 ) 471return {"identical" :bool (np .array_equal (a ,b )),"max_abs" :float (np .abs (a64 - b64 ).max ()), 472"rel_l2" :float (np .linalg .norm (a64 - b64 )/ max (np .linalg .norm (b64 ),1e-30 )), 473"cos" :float (a64 @b64 / max (np .linalg .norm (a64 )* np .linalg .norm (b64 ),1e-30 )), 474"token_cos_min" :float (tc .min ()),"token_cos_mean" :float (tc .mean ())} 475 476 477def load_cond (path :str )-> np .ndarray : 478p = Path (path ) 479shape = [int (x )for x in p .with_suffix (".shape" ).read_text ().split ()] 480return np .fromfile (p ,dtype = "<f4" ).reshape (shape [1 ],shape [0 ]) 481 482 483def prompt_list (spec :str )-> list [int ]: 484out = [] 485for part in spec .split ("," ): 486if "-" in part : 487a ,b = part .split ("-" ) 488out += list (range (int (a ),int (b )+ 1 )) 489else : 490out .append (int (part )) 491return out 492 493 494def main (argv = None )-> int : 495ap = argparse .ArgumentParser () 496ap .add_argument ("gguf" ) 497ap .add_argument ("--out-dir" ) 498ap .add_argument ("--prompts" ,default = "0-7" ) 499ap .add_argument ("--prompt-file" ,action = "append" ,default = []) 500ap .add_argument ("--mode" ,default = "f32,f16op" ) 501ap .add_argument ("--cmp" ,action = "append" ,default = [],help = "NAME=path with {p} for the prompt index" ) 502ap .add_argument ("--tokens" ) 503ap .add_argument ("--tokens-from" ,help = "sd.cpp's stage dump dir with {p} (tokens.bin, tokens.start): ids must match" ) 504ap .add_argument ("--stats" ,action = "store_true" ) 505ap .add_argument ("--layers" ,type = int ,default = 0 ,help = "debug: stop after this many layers" ) 506a = ap .parse_args (argv ) 507W = Weights (Path (a .gguf )) 508tok = Qwen2Tok (W .g .metadata ["tokenizer.ggml.merges" ]) 509gv = W .g .metadata ["tokenizer.ggml.tokens" ] 510diff = sum (1 for x ,y in zip (tok .vocab ,gv )if x != y ) 511spec = sum (1 for i ,s in enumerate (SPECIALS )if len (gv )> len (tok .vocab )+ i and gv [len (tok .vocab )+ i ]!= s ) 512f"vocab: sd.cpp construction { len ( tok . vocab ) } + { len ( SPECIALS ) } specials; differs from the GGUF's list at " 513f" { diff } regular and { spec } special ids" ,file = sys .stderr ) 514if a .tokens is not None : 515ids ,w ,n_sys = build_tokens (tok ,a .tokens ) 516json .dumps ({"ids" :ids ,"weights" :w ,"n_system" :n_sys })) 517return 0 518from run_set import PROMPTS 519texts = {} 520if a .prompt_file : 521for i ,f in enumerate (a .prompt_file ): 522texts [i ]= Path (f ).read_text (encoding = "utf-8" ) 523else : 524for i in prompt_list (a .prompts ): 525texts [i ]= PROMPTS [i ] 526out = Path (a .out_dir ) 527out .mkdir (parents = True ,exist_ok = True ) 528modes = a .mode .split ("," ) 529toks = {} 530for i ,t in texts .items (): 531ids ,w ,n_sys = build_tokens (tok ,t ) 532toks [i ]= (ids ,w ,n_sys ) 533if a .tokens_from : 534d = Path (a .tokens_from .replace ("{p}" ,str (i ))) 535sd_ids = np .fromfile (d / "tokens.bin" ,dtype = "<i4" ).tolist () 536sd_start = int ((d / "tokens.start" ).read_text ().split ()[0 ]) 537same = sd_ids == ids and sd_start == n_sys 538f"p { i } : TOKENS { 'IDENTICAL' if same else 'DIFFER' } to sd.cpp ( { len ( sd_ids ) } ids, start { sd_start } )" ) 539if not same : 540return 3 541 (out / f"tokens_p { i } .json" ).write_text (json .dumps ({"text" :t ,"ids" :ids ,"weights" :w ,"n_system" :n_sys })) 542f"p { i } : { len ( ids ) } tokens, n_system { n_sys } , cond rows { len ( ids ) - n_sys } " ,flush = True ) 543xs = {(i ,m ):embed (W ,toks [i ][0 ])for i in texts for m in modes } 544stats = {m : {}for m in modes }if a .stats else None 545nl = a .layers or W .n_layer 546t0 = time .time () 547for li in range (nl ): 548for m in modes : 549L = Layer (W ,li ,m == "f16op" ) 550for i in texts : 551xs [(i ,m )]= layer_forward (W ,L ,xs [(i ,m )],m == "f16op" ,stats [m ]if stats else None ,li ) 552del L 553f"layer { li } done { time . time () - t0 :.0f } s" ,flush = True ) 554res = {"prompts" : {},"modes" :modes ,"layers" :nl } 555conds = {} 556for i in texts : 557ids ,w ,n_sys = toks [i ] 558r = {"n_tokens" :len (ids ),"n_system" :n_sys } 559for m in modes : 560c = apply_token_weights (xs [(i ,m )],w )[n_sys :] 561conds [(i ,m )]= c 562np .save (out / f"cond_p { i } _ { m } .npy" ,c ) 563if "f32" in modes and "f16op" in modes : 564r ["f16op_vs_f32" ]= compare (conds [(i ,"f16op" )],conds [(i ,"f32" )]) 565for spec in a .cmp : 566name ,path = spec .split ("=" ,1 ) 567pth = path .replace ("{p}" ,str (i )) 568if not Path (pth ).is_file (): 569continue 570ref = load_cond (pth ) 571if ref .shape != conds [(i ,modes [0 ])].shape : 572r [f" { name } _shape" ]= [list (ref .shape ),list (conds [(i ,modes [0 ])].shape )] 573continue 574for m in modes : 575r [f" { name } _vs_ { m } " ]= compare (ref ,conds [(i ,m )]) 576res ["prompts" ][str (i )]= r 577f"p { i } : " + json .dumps ({k : (v if not isinstance (v ,dict )else {kk :round (vv ,6 )if isinstance (vv ,float )else vv for kk ,vv in v .items ()})for k ,v in r .items ()}),flush = True ) 578# summaries per comparison 579keys = sorted ({k for r in res ["prompts" ].values ()for k ,v in r .items ()if isinstance (v ,dict )}) 580summ = {} 581for k in keys : 582rows = [r [k ]for r in res ["prompts" ].values ()if k in r ] 583summ [k ]= {"n" :len (rows ),"rel_l2_mean" :float (np .mean ([x ["rel_l2" ]for x in rows ])), 584"rel_l2_max" :max (x ["rel_l2" ]for x in rows ),"cos_min" :min (x ["cos" ]for x in rows ), 585"token_cos_min" :min (x ["token_cos_min" ]for x in rows ),"max_abs" :max (x ["max_abs" ]for x in rows ), 586"identical" :sum (x ["identical" ]for x in rows )} 587f"SUMMARY { k } : { json . dumps ( summ [ k ]) } " ) 588res ["summary" ]= summ 589if stats : 590res ["ranges" ]= stats 591for m in modes : 592kinds = sorted ({k .split ("." ,1 )[1 ]for k in stats [m ]}) 593for kd in kinds : 594vals = [(int (k .split ("." )[0 ]),v )for k ,v in stats [m ].items ()if k .split ("." ,1 )[1 ]== kd ] 595top = max (vals ,key = lambda t :t [1 ]["max" ]) 596sub = sum (v ["subnormal" ]for _ ,v in vals )/ max (sum (v ["n" ]for _ ,v in vals ),1 ) 597over = sum (v ["over_f16" ]for _ ,v in vals ) 598f"RANGE { m } { kd } : max { top [ 1 ][ 'max' ]:.4g } at layer { top [ 0 ] } , over f16 { over } , subnormal share { sub :.2e } " ) 599 (out / "te_ref.json" ).write_text (json .dumps (res ,indent = 1 )) 600return 0 601 602 603if __name__ == "__main__" : 604sys .exit (main ())