okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b749503db
main
1"""tools/test_dit_rope.py - our Qwen-Image-2.1 RoPE table (src/image/dit/qi21_rope.cpp) against the tables 2stable-diffusion.cpp 2988060 built for the same pictures: their sha256, recorded from sd.cpp's stock and native runners 3through the stage hook (tools/image/gate/stage_hooks.py pe_stock_<k>) in tools/image/gate/data/qi21_rope_sha.json 4(512x512 with four prompts, 1024x1024, 1536x1024, a 1,025-token prompt). Compiles with the system C++ compiler; no GPU, 5no sd.cpp, no model file. 6 7The table is std::cos / std::sin of float angles, so its last bit is the C library's: the recorded sha256 are sd.cpp's on 8glibc (Linux), and the byte check runs where the C library is glibc. Elsewhere sd.cpp gets that C library's bits too, not 9glibc's (macOS 27 on an M4: every float correctly rounded, 3,360 of the 269,568 floats of the first case 1 ulp from glibc's, 10so no recorded hash matches). The second test runs everywhere: every float of the table against a float64 reference of the 11same float steps, within 2 ulp plus the error of a 2-ulp powf in the angle. 12 13python -m pytest tools/test_dit_rope.py""" 14import hashlib 15import json 16import math 17import platform 18import shutil 19import struct 20import subprocess 21import tempfile 22import unittest 23from pathlib import Path 24 25ROOT = Path (__file__ ).resolve ().parents [1 ] 26CXX = shutil .which ("g++" )or shutil .which ("c++" )or shutil .which ("clang++" ) 27CASES = ROOT / "tools" / "image" / "gate" / "data" / "qi21_rope_sha.json" 28GLIBC = platform .system ()== "Linux" and platform .libc_ver ()[0 ]== "glibc" 29 30 31def build (td :Path )-> Path : 32exe = td / "strata-dit-rope" 33r = subprocess .run ([CXX ,"-std=c++17" ,"-O2" ,"-I" ,str (ROOT / "include" ), 34str (ROOT / "src" / "image" / "dit" / "qi21_rope.cpp" ), 35str (ROOT / "src" / "image" / "dit" / "qi21_rope_main.cpp" ),"-o" ,str (exe )], 36capture_output = True ,text = True ,timeout = 300 ) 37if r .returncode != 0 : 38raise AssertionError ("build failed:\n" + r .stderr [- 3000 :]) 39return exe 40 41 42def table (exe :Path ,td :Path ,c :dict )-> bytes : 43out = td / "t.bin" 44subprocess .run ([str (exe ),str (c ["text_tokens" ]),str (c ["H" ]),str (c ["W" ]),str (out )],check = True ) 45return out .read_bytes () 46 47 48def f32 (x :float )-> float : 49return struct .unpack ("<f" ,struct .pack ("<f" ,x ))[0 ] 50 51 52def reference (text :int ,H :int ,W :int ): 53"""(value, angle) for every float of the table: sd.cpp's float steps in float64, each rounded to float32, and cos / sin of 54the float32 angle rounded once to float32.""" 55pos = [(float (p ),)* 3 for p in range (text )] 56pos += [(float (text ),float (h - (H - H // 2 )),float (w - (W - W // 2 )))for h in range (H )for w in range (W )]# every picture token at text_len 57val ,ang = [0.0 ]* (len (pos )* 256 ), [0.0 ]* (len (pos )* 256 ) 58off = 0 59for a ,dim in enumerate ((16 ,56 ,56 )): 60half = dim // 2 61step = f32 (f32 (f32 (dim * 1.0 - 2 )/ dim )/ (half - 1 )) 62omega = [f32 (1.0 / f32 (10000.0 ** f32 (i * step )))for i in range (half )] 63for i ,p in enumerate (pos ): 64for j ,om in enumerate (omega ): 65t = f32 (p [a ]* om ) 66c ,s = f32 (math .cos (t )),f32 (math .sin (t )) 67k = i * 256 + off + 4 * j 68val [k :k + 4 ]= (c ,- s ,s ,c ) 69ang [k :k + 4 ]= (t ,)* 4 70off += half * 4 71return val ,ang 72 73 74def ulp32 (x :float )-> float : 75return 2.0 ** (math .floor (math .log2 (max (abs (x ),2.0 ** - 126 )))- 23 ) 76 77 78@ unittest . skipUnless ( CXX , "no C++ compiler" ) 79class RopeTableMatchesSdcpp (unittest .TestCase ): 80@ unittest . skipUnless ( GLIBC , "the recorded sha256 are sd.cpp's tables on glibc, and this C library rounds cosf / sinf " 81"differently in the last bit (test_tables_close_to_float64 checks every float here)" ) 82def test_tables (self ): 83cases = json .loads (CASES .read_text ()) 84self .assertGreaterEqual (len (cases ),7 ) 85with tempfile .TemporaryDirectory ()as td : 86exe = build (Path (td )) 87bad = [c ["from" ]for c in cases if hashlib .sha256 (table (exe ,Path (td ),c )).hexdigest ()!= c ["sha256" ]] 88self .assertEqual (bad , []) 89 90def test_tables_close_to_float64 (self ): 91cases = json .loads (CASES .read_text ()) 92self .assertGreaterEqual (len (cases ),7 ) 93with tempfile .TemporaryDirectory ()as td : 94exe = build (Path (td )) 95for c in cases : 96raw = table (exe ,Path (td ),c ) 97got = struct .unpack ("<%df" % (len (raw )// 4 ),raw ) 98val ,ang = reference (c ["text_tokens" ],c ["H" ],c ["W" ]) 99self .assertEqual (len (got ),len (val ),c ["from" ]) 100far = [k for k , (g ,v ,t )in enumerate (zip (got ,val ,ang )) 101if abs (g - v )> 2 * ulp32 (v )+ abs (t )* 2.0 ** - 22 ] 102self .assertEqual (far [:5 ], [],f" { c [ 'from' ] } : { len ( far ) } of { len ( got ) } floats off " 103f"(first at { far [ 0 ] if far else '-' } : ours { got [ far [ 0 ]] if far else '-' } , " 104f"float64 { val [ far [ 0 ]] if far else '-' } )" ) 105 106 107if __name__ == "__main__" : 108unittest .main ()