okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
e4309aaf3
main
1"""tools/image/gate/dit_replay.py - TEST-ONLY (OWN-5B trace): replay one DiT block of dit_ref.py from OUR stream. 2 3Our test build (STRATA_DIT_TRACE_DIR, STRATA_DIT_TRACE_BLOCK=B) dumps the stream after every block (txt_NN.bin, 4img_NN.bin) and the inside of block B (blk_*.bin). This tool: 51. runs dit_ref's block B in f32 and in f16op starting from OUR stream after block B-1, and compares each stage with 6our dump of the same stage: same input, so what is left is the difference in the block's own arithmetic; 72. runs the reference up to block B-1 (f32 and f16op), then block B in f32 from three inputs: the f32 state, the 8f16op state and our state; the attention output's distance from the f32-from-f32 one against the input's 9distance tells how much block B amplifies a given input difference, per input; 103. the same with random input perturbations of the size of ours (three trials), to see whether block B of this 11prompt amplifies any small difference or only ours; 124. a K / V layout check (rows of our blk_k16 / blk_v16 against the reference's text and image rows). 13 14python -I -B dit_replay.py <dit.gguf> --dump D --trace T --block B 15""" 16from __future__import annotations 17 18import argparse 19import sys 20from pathlib import Path 21 22import numpy as np 23 24_HERE = Path (__file__ ).resolve ().parent 25if str (_HERE )not in sys .path : 26sys .path .insert (0 ,str (_HERE )) 27from dit_ref import DitWeights ,Mode ,block ,layer_norm ,layout_positions ,load_dump ,prelude ,rope_table # noqa: E402 28from te_ref import compare # noqa: E402 29 30F32 = np .float32 31KEYS = ("qkv" ,"q16" ,"att" ,"x_mid" ,"ln2" ,"act" ) 32 33 34def rel (a ,b )-> float : 35return compare (np .asarray (a ,F32 ).reshape (a .shape [0 ],- 1 ),np .asarray (b ,F32 ).reshape (b .shape [0 ],- 1 ))["rel_l2" ] 36 37 38def ours_block (t :Path ,n :int ,H :int ,D :int )-> dict : 39def rd (name ,shape ,dt = "<f4" ): 40f = t / name 41return np .fromfile (f ,dtype = dt ).astype (F32 ).reshape (shape )if f .is_file ()else None 42q = rd ("blk_q16.bin" , (H ,n ,D ),"<f2" ) 43return {"qkv" :rd ("blk_qkv.bin" , (n ,- 1 )),"q16" :None if q is None else q .transpose (1 ,0 ,2 ), 44"att" :rd ("blk_att.bin" , (n ,- 1 )),"x_mid" :rd ("blk_x_mid.bin" , (n ,- 1 )),"ln2" :rd ("blk_ln2.bin" , (n ,- 1 )), 45"act" :rd ("blk_act.bin" , (n ,- 1 ))} 46 47 48def main (argv = None )-> int : 49ap = argparse .ArgumentParser () 50ap .add_argument ("gguf" ) 51ap .add_argument ("--dump" ,required = True ) 52ap .add_argument ("--trace" ,required = True ) 53ap .add_argument ("--block" ,type = int ,required = True ) 54ap .add_argument ("--trials" ,type = int ,default = 3 ) 55a = ap .parse_args (argv ) 56B = a .block 57d ,t = Path (a .dump ),Path (a .trace ) 58name = d .name 59Wt = DitWeights (Path (a .gguf )) 60xv ,xs = load_dump (d ,"dit_x_0" ) 61tv ,_ = load_dump (d ,"dit_t_0" ) 62cv ,cs = load_dump (d ,"cond" ) 63Ww ,Hh ,C = xs [0 ],xs [1 ],xs [2 ] 64x ,tt ,cond = xv .reshape (C ,Hh ,Ww ),float (tv [0 ]),cv .reshape (cs [1 ],cs [0 ]) 65L = cond .shape [0 ] 66c ,s = rope_table (layout_positions (L ,Hh ,Ww )) 67ours_prev = np .concatenate ([np .fromfile (t / f"txt_ { B - 1 :02d } .bin" ,dtype = "<f4" ).reshape (L ,- 1 ), 68np .fromfile (t / f"img_ { B - 1 :02d } .bin" ,dtype = "<f4" ).reshape (Hh * Ww ,- 1 )],0 ) 69n = Hh * Ww 70H ,D = ours_prev .shape [1 ]// 128 ,128 71got = ours_block (t ,n ,H ,D ) 72st = {} 73for mname in ("f32" ,"f16op" ): 74m = Mode (mname == "f16op" ) 75mods ,scale ,xj = prelude (Wt ,m ,tt ,cond ,x ) 76rows = np .array ([1 ]* L + [0 ]* (xj .shape [0 ]- L )) 77for i in range (B ): 78xj = block (Wt ,m ,i ,xj ,rows ,mods ,L ,c ,s ) 79st [mname ]= (m ,mods ,rows ,xj ) 80f" { name } : { mname } state after block { B - 1 } done" ,flush = True ) 81for nm , (m ,mods ,rows ,xj )in st .items (): 82f"INPUT { name } | { nm } state vs ours after block { B - 1 } | img { rel ( xj [ L :], ours_prev [ L :]):.6f } | " 83f"img LN { rel ( layer_norm ( xj [ L :]), layer_norm ( ours_prev [ L :])):.6f } | txt { rel ( xj [: L ], ours_prev [: L ]):.6f } " ) 84# 1. same input (ours), the block's arithmetic only 85caps = {} 86for nm , (m ,mods ,rows ,_ )in st .items (): 87cap = {} 88block (Wt ,m ,B ,ours_prev .copy (),rows ,mods ,L ,c ,s ,None ,None ,cap ) 89caps [nm ]= cap 90f"REPLAY { name } block { B } from OUR input | stage | ours vs f32 | ours vs f16op | f16op vs f32" ) 91for k in KEYS : 92g = got [k ] 93if g is None : 94continue 95f"REPLAY { name } | { k } | { rel ( g , caps [ 'f32' ][ k ]):.6f } | { rel ( g , caps [ 'f16op' ][ k ]):.6f } | " 96f" { rel ( caps [ 'f16op' ][ k ], caps [ 'f32' ][ k ]):.6f } " ) 97# 2. block B in f32 from three inputs 98m32 ,mods32 ,rows32 ,x32 = st ["f32" ] 99 100def att_from (xin ): 101cap = {} 102block (Wt ,m32 ,B ,xin .copy (),rows32 ,mods32 ,L ,c ,s ,None ,None ,cap ) 103return cap 104 105base = att_from (x32 ) 106f"AMPLIFY { name } block { B } (f32 arithmetic) | input | input img LN dist | att dist | act dist | att / input" ) 107for nm ,xin in (("f16op state" ,st ["f16op" ][3 ]), ("our state" ,ours_prev )): 108cp = att_from (xin ) 109di = rel (layer_norm (xin [L :]),layer_norm (x32 [L :])) 110da ,dact = rel (cp ["att" ],base ["att" ]),rel (cp ["act" ],base ["act" ]) 111f"AMPLIFY { name } | { nm } | { di :.6f } | { da :.6f } | { dact :.6f } | { da / max ( di , 1e-30 ):.2f } " ) 112# 3. random perturbations of our input's size (image rows only, per-row relative) 113di_ours = rel (ours_prev [L :],x32 [L :]) 114rng = np .random .default_rng (1 ) 115for k in range (a .trials ): 116e = rng .standard_normal (x32 [L :].shape ).astype (F32 ) 117e *= (np .linalg .norm (x32 [L :],axis = 1 ,keepdims = True )/ np .linalg .norm (e ,axis = 1 ,keepdims = True ))* F32 (di_ours ) 118xin = x32 .copy () 119xin [L :]+= e 120cp = att_from (xin ) 121di = rel (layer_norm (xin [L :]),layer_norm (x32 [L :])) 122da ,dact = rel (cp ["att" ],base ["att" ]),rel (cp ["act" ],base ["act" ]) 123f"AMPLIFY { name } | random { k } | { di :.6f } | { da :.6f } | { dact :.6f } | { da / max ( di , 1e-30 ):.2f } " ) 124# 4. K / V layout of our dump 125for key ,f in (("k16" ,"blk_k16.bin" ), ("v16" ,"blk_v16.bin" )): 126p = t / f 127if not p .is_file (): 128continue 129arr = np .fromfile (p ,dtype = "<f2" ).astype (F32 ) 130kvt = arr .size // (H * D ) 131o = arr .reshape (H ,kvt ,D ).transpose (1 ,0 ,2 ) 132r = caps ["f16op" ][key ]# [L + n, H, D] 133cells = [f"kvt { kvt } (L { L } + n { n } = { L + n } )" ] 134if kvt >= L + n : 135cells .append (f"[text;image] { rel ( o [: L + n ], r ):.6f } " ) 136cells .append (f"text rows { rel ( o [: L ], r [: L ]):.6f } image rows { rel ( o [ L : L + n ], r [ L :]):.6f } " ) 137cells .append (f"[image;text] { rel ( np . concatenate ([ o [ n : n + L ], o [: n ]], 0 ), r ):.6f } " ) 138f"LAYOUT { name } | { key } | " + " | " .join (cells )) 139return 0 140 141 142if __name__ == "__main__" : 143sys .exit (main ())