okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
11c8c701a
main
1"""tools/image/gate/test_te_ref.py - TEST-ONLY: te_ref.py's pieces against independent scalar forms of the same maths 2(the GGUF block formats as include/strata/artifact/dequant.hpp writes them, the prompt-weight parser's documented cases), 3and the encoder on a tiny random model (no model file needed). 4 5python -m pytest tools/image/gate/test_te_ref.py""" 6import math 7import struct 8import sys 9import unittest 10from pathlib import Path 11 12import numpy as np 13 14sys .path .insert (0 ,str (Path (__file__ ).resolve ().parent )) 15import te_ref as T # noqa: E402 16 17F = np .float32 18 19 20def h2f (u ): 21return F (np .frombuffer (struct .pack ("<H" ,u ),"<f2" )[0 ]) 22 23 24def scale_min_k4 (j ,q ): 25if j < 4 : 26return q [j ]& 63 ,q [j + 4 ]& 63 27return (q [j + 4 ]& 0x0F )| ((q [j - 4 ]>> 6 )<< 4 ), (q [j + 4 ]>> 4 )| ((q [j ]>> 6 )<< 4 ) 28 29 30def scalar_q4_k (b ): 31d ,mn = h2f (b [0 ]| b [1 ]<< 8 ),h2f (b [2 ]| b [3 ]<< 8 ) 32sc ,q ,y ,is_ = b [4 :16 ],b [16 :144 ], [],0 33for j in range (0 ,256 ,64 ): 34s ,m = scale_min_k4 (is_ ,sc ) 35d1 ,m1 = F (d * F (s )),F (mn * F (m )) 36s ,m = scale_min_k4 (is_ + 1 ,sc ) 37d2 ,m2 = F (d * F (s )),F (mn * F (m )) 38= q [j // 2 :j // 2 + 32 ] 39y += [F (F (d1 * F (x & 0xF ))- m1 )for x in y += [F (F (d2 * F (x >> 4 ))- m2 )for x in is_ += 2 42return np .array (y ,F ) 43 44 45def scalar_q5_k (b ): 46d ,mn = h2f (b [0 ]| b [1 ]<< 8 ),h2f (b [2 ]| b [3 ]<< 8 ) 47sc ,qh ,ql ,y ,is_ ,u1 ,u2 = b [4 :16 ],b [16 :48 ],b [48 :176 ], [],0 ,1 ,2 48for j in range (0 ,256 ,64 ): 49s ,m = scale_min_k4 (is_ ,sc ) 50d1 ,m1 = F (d * F (s )),F (mn * F (m )) 51s ,m = scale_min_k4 (is_ + 1 ,sc ) 52d2 ,m2 = F (d * F (s )),F (mn * F (m )) 53= ql [j // 2 :j // 2 + 32 ] 54y += [F (F (d1 * F ((l ]& 0xF )+ (16 if qh [l ]& u1 else 0 )))- m1 )for l in range (32 )] 55y += [F (F (d2 * F ((l ]>> 4 )+ (16 if qh [l ]& u2 else 0 )))- m2 )for l in range (32 )] 56is_ += 2 57u1 ,u2 = (u1 << 2 )& 0xFF , (u2 << 2 )& 0xFF 58return np .array (y ,F ) 59 60 61def scalar_q6_k (b ): 62ql ,qh = b [0 :128 ],b [128 :192 ] 63sc = np .frombuffer (bytes (b [192 :208 ]),np .int8 ) 64d = h2f (b [208 ]| b [209 ]<< 8 ) 65y = [F (0 )]* 256 66for n in range (2 ): 67L ,H ,S ,o = ql [64 * n :],qh [32 * n :],sc [8 * n :],128 * n 68for l in range (32 ): 69is_ = l // 16 70q1 = ((L [l ]& 0xF )| (((H [l ]>> 0 )& 3 )<< 4 ))- 32 71q2 = ((L [l + 32 ]& 0xF )| (((H [l ]>> 2 )& 3 )<< 4 ))- 32 72q3 = ((L [l ]>> 4 )| (((H [l ]>> 4 )& 3 )<< 4 ))- 32 73q4 = ((L [l + 32 ]>> 4 )| (((H [l ]>> 6 )& 3 )<< 4 ))- 32 74y [o + l ]= F (F (d * F (S [is_ ]))* F (q1 )) 75y [o + l + 32 ]= F (F (d * F (S [is_ + 2 ]))* F (q2 )) 76y [o + l + 64 ]= F (F (d * F (S [is_ + 4 ]))* F (q3 )) 77y [o + l + 96 ]= F (F (d * F (S [is_ + 6 ]))* F (q4 )) 78return np .array (y ,F ) 79 80 81def scalar_iq4_xs (b ): 82d = h2f (b [0 ]| b [1 ]<< 8 ) 83sh ,sl ,qs ,y = b [2 ]| b [3 ]<< 8 ,b [4 :8 ],b [8 :136 ], [] 84for ib in range (8 ): 85ls = ((sl [ib // 2 ]>> (4 * (ib % 2 )))& 0xF )| (((sh >> (2 * ib ))& 3 )<< 4 ) 86dl = F (d * F (ls - 32 )) 87lo = [F (dl * T .KV_IQ4NL [qs [16 * ib + j ]& 0xF ])for j in range (16 )] 88hi = [F (dl * T .KV_IQ4NL [qs [16 * ib + j ]>> 4 ])for j in range (16 )] 89y += lo + hi 90return np .array (y ,F ) 91 92 93def random_blocks (rng ,n ,size ,f16_at ): 94b = rng .integers (0 ,256 ,size = (n ,size ),dtype = np .uint8 ) 95for off in f16_at :# finite, modest scales 96v = rng .uniform (- 0.02 ,0.02 ,n ).astype (np .float16 ).view (np .uint8 ).reshape (n ,2 ) 97b [:,off :off + 2 ]= v 98return b 99 100 101class Dequant (unittest .TestCase ): 102def check (self ,fn ,scalar ,size ,f16_at ): 103rng = np .random .default_rng (7 ) 104b = random_blocks (rng ,6 ,size ,f16_at ) 105got = fn (b .reshape (- 1 )) 106want = np .concatenate ([scalar (list (map (int ,row )))for row in b ]) 107self .assertTrue (np .array_equal (got .view (np .uint32 ),want .view (np .uint32 ))) 108 109def test_q4_k (self ): 110self .check (T .deq_q4_k ,scalar_q4_k ,144 , (0 ,2 )) 111 112def test_q5_k (self ): 113self .check (T .deq_q5_k ,scalar_q5_k ,176 , (0 ,2 )) 114 115def test_q6_k (self ): 116self .check (T .deq_q6_k ,scalar_q6_k ,210 , (208 ,)) 117 118def test_iq4_xs (self ): 119self .check (T .deq_iq4_xs ,scalar_iq4_xs ,136 , (0 ,)) 120 121 122class PromptWeights (unittest .TestCase ): 123"""The cases documented above sd.cpp's core/util.cpp parse_prompt_attention, as its code (not its comment) runs them.""" 124 125def same (self ,text ,want ): 126got = T .parse_prompt_attention (text ) 127self .assertEqual ([g [0 ]for g in got ], [w [0 ]for w in want ]) 128for g ,w in zip (got ,want ): 129self .assertAlmostEqual (float (g [1 ]),w [1 ],places = 5 ) 130 131def test_cases (self ): 132self .same ("normal text" , [["normal text" ,1.0 ]]) 133self .same ("an (important) word" , [["an " ,1.0 ], ["important" ,1.1 ], [" word" ,1.0 ]]) 134self .same ("(unbalanced" , [["unbalanced" ,1.1 ]]) 135# the comment above sd.cpp's function says "(literal]"; its code unescapes only "\(" and keeps "\]" as text 136self .same ("\\(literal\\]" , [["(literal\\]" ,1.0 ]]) 137self .same ("(unnecessary)(parens)" , [["unnecessaryparens" ,1.1 ]]) 138self .same ("a (((house:1.3)) [on] a (hill:0.5), sun, (((sky)))." , 139 [["a " ,1.0 ], ["house" ,1.573 ], [" " ,1.1 ], ["on" ,1.0 ], [" a " ,1.1 ], ["hill" ,0.55 ], 140 [", sun, " ,1.1 ], ["sky" ,1.4641 ], ["." ,1.1 ]]) 141 142def test_gate_prompts_are_plain (self ): 143from run_set import PROMPTS 144for p in PROMPTS : 145self .assertEqual (T .parse_prompt_attention (p ), [[p ,np .float32 (1.0 )]]) 146 147 148class Tokens (unittest .TestCase ): 149def test_bpe_and_specials (self ): 150bu = T .bytes_to_unicode () 151sp = bu [ord (" " )] 152tok = T .Qwen2Tok (["h e" ,"l l" ,"he ll" ,f" { sp } w" ,"o r" ]) 153ids = tok .encode ("<|im_start|>hello world<|im_end|>" ) 154base = 256 + 5 155self .assertEqual (ids [0 ],base + 1 ) 156self .assertEqual (ids [- 1 ],base + 2 ) 157self .assertEqual (tok .vocab [ids [1 ]],"hell" ) 158self .assertEqual ("" .join (tok .vocab [i ]for i in ids [1 :- 1 ]),"hello" + sp + "world" ) 159 160def test_split_specials (self ): 161self .assertEqual (T .split_with_special_tokens ("a<|im_end|>\nb" ,T .SPECIALS ), ["a" ,"<|im_end|>" ,"\nb" ]) 162 163 164class TinyModel (unittest .TestCase ): 165"""The layer on random weights: causal (token t sees only 0..t), f16op close to f32, NEOX rope = rotation.""" 166 167def setUp (self ): 168rng = np .random .default_rng (3 ) 169C ,Hh ,KV ,D ,Ff = 64 ,4 ,2 ,16 ,96 170 171class W : 172n_head ,n_kv ,hd ,theta ,eps = Hh ,KV ,D ,5e6 ,1e-6 173 174class L : 175pass 176self .W = W 177L .attn_norm = rng .uniform (0.5 ,1.5 ,C ).astype (F ) 178L .ffn_norm = rng .uniform (0.5 ,1.5 ,C ).astype (F ) 179L .qn = rng .uniform (0.5 ,1.5 ,D ).astype (F ) 180L .kn = rng .uniform (0.5 ,1.5 ,D ).astype (F ) 181mk = lambda o ,i : (rng .standard_normal ((o ,i ))/ math .sqrt (i )).astype (F ).astype (np .float64 )# noqa: E731 182L .q ,L .k ,L .v ,L .o = mk (Hh * D ,C ),mk (KV * D ,C ),mk (KV * D ,C ),mk (C ,Hh * D ) 183L .g ,L .u ,L .d = mk (Ff ,C ),mk (Ff ,C ),mk (C ,Ff ) 184self .L = L 185self .x = rng .standard_normal ((9 ,C )).astype (F ) 186 187def test_causal (self ): 188full = T .layer_forward (self .W ,self .L ,self .x ,False ,None ,0 ) 189part = T .layer_forward (self .W ,self .L ,self .x [:5 ],False ,None ,0 ) 190self .assertTrue (np .allclose (full [:5 ],part ,rtol = 1e-6 ,atol = 1e-6 )) 191 192def test_f16op_close (self ): 193a = T .layer_forward (self .W ,self .L ,self .x ,False ,None ,0 ) 194b = T .layer_forward (self .W ,self .L ,self .x ,True , {},0 ) 195self .assertLess (T .compare (b ,a )["rel_l2" ],5e-3 ) 196 197def test_rope_is_rotation (self ): 198x = np .random .default_rng (1 ).standard_normal ((6 ,2 ,16 )).astype (F ) 199r = T .rope_neox (x ,5e6 ) 200self .assertTrue (np .allclose (np .linalg .norm (r ,axis =- 1 ),np .linalg .norm (x ,axis =- 1 ),rtol = 1e-5 )) 201self .assertTrue (np .array_equal (r [0 ],x [0 ])) 202 203 204if __name__ == "__main__" : 205unittest .main ()