okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
e4309aaf3
main
1"""tools/image/gate/dit_ref.py - TEST-ONLY (OWN-5 gate harness): a numpy reference of one Qwen-Image-2.1 DiT call as 2stable-diffusion.cpp 2988060 computes it (src/model/diffusion/qwen_image_2_1.hpp, QwenImage21Runner, no reference 3pictures, text prefix + image tokens in one sequence), from the stage-hook dumps of that call: the latent and the 4timestep it got (dit_x_<k>, dit_t_<k>) and the condition (cond). The oracle of step 4 (our own DiT GEMMs and runner). 5 6The model (read from the pinned tree): 7time = [t, 0] -> sinusoid 256 (cos half, then sin half; freq = exp(-ln 10000 * j / 128)) -> linear_1 -> SiLU -> 8linear_2 -> SiLU; mod = modulation.1(time) -> 4 chunks m0..m3 of 4096, row 0 for image tokens, row 1 (t = 0) 9for text tokens; scale = norm_out.linear(time row 0) 10text = txt_in: RMSNorm(eps 1e-6) x (1 + w) -> in_layer -> GELU (tanh form) -> out_layer; image = img_in(latent 11tokens, patch 1, token h*W + w); joint = [text ; image] 12block = h = LN(x) (1 + m0); q k v = h W^T, per-head RMSNorm (norm_q / norm_k, eps 1e-6), RoPE (interleaved pairs, 13axes 16 / 56 / 56, theta 10000, positions text (p, p, p), image (L, h - (H - H/2), w - (W - W/2))); 14attention scale 1/sqrt(128): text rows causal over the text, image rows over everything; 15x += to_out(attn) tanh(m1); h = LN(x) (1 + m2); gate | up = h Wgu^T; x += out(up silu(gate)) tanh(m3) 16head = LN(image rows) (1 + scale) -> proj_out -> velocity [64, H, W] 17(LN: no affine, eps 1e-6; no linear has a bias) 18 19Modes: "f32" (weights dequantized exactly, every GEMM and the attention in float64 rounded to float32) and "f16op" 20(f16 weights and GEMM inputs, exact accumulation, Q / K / V and the probabilities f16) and "f16acc32" (as f16op but 21every GEMM sums in float32, as the GPU does; the stage rule's comparison since 11-11, coordinator: on prompt 5 the 22exact-sum emulation moves 1.6x from inputs 3e-6 apart; the nine-case table: dit_acc32_cases.py). 23 24python -I -B dit_ref.py <dit.gguf> --dumps D [D ...] [--call 0] [--mode f32,f16op] [--out-dir O] 25[--cmp NAME=<file with {dump}>] e.g. --cmp stock={dump}/vel_0.bin 26each D is a stage dump dir with dit_x_<call>, dit_t_<call>, cond; writes O/<dump name>_<mode>.npy""" 27from __future__import annotations 28 29import argparse 30import json 31import math 32import sys 33import time 34from pathlib import Path 35 36import numpy as np 37 38_HERE = Path (__file__ ).resolve ().parent 39for _p in (_HERE ,_HERE .parents [1 ]): 40if str (_p )not in sys .path : 41sys .path .insert (0 ,str (_p )) 42from gguf_reader import GGUFFile # noqa: E402 43from te_ref import DEQ ,compare ,f16r # noqa: E402 44 45PFX = "model.diffusion_model." 46AXES = (16 ,56 ,56 ) 47F32 = np .float32 48 49 50class DitWeights : 51def __init__ (self ,path :Path ): 52self .g = GGUFFile (path ) 53self .t = {t .name :t for t in self .g .tensors } 54self .mm = np .memmap (path ,dtype = np .uint8 ,mode = "r" ) 55self .n_layer = 1 + max (int (n [len (PFX + "transformer_blocks." ):].split ("." )[0 ])for n in self .t 56if n .startswith (PFX + "transformer_blocks." )) 57 58def mat (self ,name :str )-> np .ndarray : 59t = self .t [PFX + name ] 60a = self .g .data_start + t .offset 61r = np .asarray (self .mm [a :a + t .expected_bytes ()]) 62ne0 = t .shape [0 ] 63return DEQ [t .type_name ](r ).reshape (- 1 ,ne0 ) 64 65 66# ------------------------------------------------------------------ positions and RoPE (Rope::embed_nd, QwenImage21Layout) 67def layout_positions (text_len :int ,H :int ,W :int )-> np .ndarray : 68pos = [[float (p )]* 3 for p in range (text_len )] 69for h in range (H ): 70for w in range (W ): 71pos .append ([float (text_len ),float (h - (H - H // 2 )),float (w - (W - W // 2 ))]) 72return np .asarray (pos ,dtype = F32 ) 73 74 75def rope_table (pos :np .ndarray ,theta :float = 10000.0 )-> tuple [np .ndarray ,np .ndarray ]: 76"""cos, sin [n, 64] in the order sd.cpp concatenates the axes (axis 0: 8 pairs, axis 1 and 2: 28 each).""" 77cs ,sn = [], [] 78for ax ,dim in enumerate (AXES ): 79half = dim // 2 80start ,end = F32 (0 ),F32 ((dim * 1.0 - 2 )/ dim ) 81step = F32 ((end - start )/ F32 (half - 1 )) 82scale = np .array ([F32 (start + F32 (i )* step )for i in range (half )],dtype = F32 ) 83omega = (F32 (1.0 )/ np .power (F32 (theta ),scale ).astype (F32 )).astype (F32 ) 84ang = (pos [:,ax :ax + 1 ].astype (F32 )* omega [None , :]).astype (F32 ) 85cs .append (np .cos (ang ).astype (F32 )) 86sn .append (np .sin (ang ).astype (F32 )) 87return np .concatenate (cs ,1 ),np .concatenate (sn ,1 ) 88 89 90def apply_rope (x :np .ndarray ,c :np .ndarray ,s :np .ndarray )-> np .ndarray : 91"""x [n, H, 128]; interleaved pairs (2j, 2j+1): [[cos, -sin], [sin, cos]].""" 92a = x [...,0 ::2 ].astype (np .float64 ) 93b = x [...,1 ::2 ].astype (np .float64 ) 94cc ,ss = c [:,None , :].astype (np .float64 ),s [:,None , :].astype (np .float64 ) 95out = np .empty (x .shape ,np .float64 ) 96out [...,0 ::2 ]= a * cc - b * ss 97out [...,1 ::2 ]= a * ss + b * cc 98return out .astype (F32 ) 99 100 101# ------------------------------------------------------------------ pieces 102def layer_norm (x ): 103x64 = x .astype (np .float64 ) 104m = x64 .mean (- 1 ,keepdims = True ) 105v = ((x64 - m )** 2 ).mean (- 1 ,keepdims = True ) 106return ((x64 - m )/ np .sqrt (v + 1e-6 )).astype (F32 ) 107 108 109def rms_norm (x ,w ): 110x64 = x .astype (np .float64 ) 111return ((x64 / np .sqrt ((x64 ** 2 ).mean (- 1 ,keepdims = True )+ np .float64 (F32 (1e-6 )))).astype (F32 )* w ).astype (F32 ) 112 113 114def gelu_tanh (x ): 115x64 = x .astype (np .float64 ) 116return (0.5 * x64 * (1.0 + np .tanh (0.7978845608028654 * x64 * (1.0 + 0.044715 * x64 * x64 )))).astype (F32 ) 117 118 119def silu (x ): 120x64 = x .astype (np .float64 ) 121return (x64 / (1.0 + np .exp (- x64 ))).astype (F32 ) 122 123 124def timestep_embedding (t :np .ndarray ,dim :int = 256 ,max_period :int = 10000 )-> np .ndarray : 125half = dim // 2 126j = np .arange (half ,dtype = np .float64 ) 127freq = np .exp (- math .log (max_period )* j / half ) 128arg = t [:,None ].astype (np .float64 )* freq [None , :] 129return np .concatenate ([np .cos (arg ),np .sin (arg )],1 ).astype (F32 ) 130 131 132class Mode : 133def __init__ (self ,f16 :bool ): 134self .f16 = f16 135 136def w (self ,m :np .ndarray )-> np .ndarray : 137return (f16r (m )if self .f16 else m ).astype (np .float64 ) 138 139def gemm (self ,x :np .ndarray ,W64 :np .ndarray )-> np .ndarray : 140xi = f16r (x )if self .f16 else x 141return (xi .astype (np .float64 ) @W64 .T ).astype (F32 ) 142 143 144class ModeAcc32 (Mode ): 145""""f16acc32": f16 weights and GEMM inputs, FLOAT32 accumulation (numpy float32 matmul, the BLAS's summation 146order), as cuBLAS GemmEx with compute 32F sums; everything else as "f16op".""" 147def __init__ (self ): 148super ().__init__ (True ) 149 150def w (self ,m :np .ndarray )-> np .ndarray : 151return f16r (m ).astype (F32 ) 152 153def gemm (self ,x :np .ndarray ,W :np .ndarray )-> np .ndarray : 154return (f16r (x ).astype (F32 ) @W .astype (F32 ,copy = False ).T ).astype (F32 ) 155 156 157MODES = ("f32" ,"f16op" ,"f16acc32" ) 158 159 160def make_mode (name :str )-> Mode : 161if name not in MODES : 162raise SystemExit (f"dit_ref: unknown mode { name !r } (known: { ', ' . join ( MODES ) } )" ) 163return ModeAcc32 ()if name == "f16acc32" else Mode (name == "f16op" ) 164 165 166def attention (q ,k ,v ,L :int ,f16 :bool )-> np .ndarray : 167"""q k v [n, H, D] (after norms and rope); rows < L (text) causal over the text, the rest over all n.""" 168n ,H ,D = q .shape 169if f16 : 170q ,k ,v = f16r (q ),f16r (k ),f16r (v ) 171out = np .empty ((n ,H ,D ),F32 ) 172scale = 1.0 / math .sqrt (D ) 173for h in range (H ): 174s = q [:,h ].astype (np .float64 ) @k [:,h ].astype (np .float64 ).T 175s = (s .astype (F32 )* F32 (scale )).astype (np .float64 )if f16 else s * scale 176s [:L ,L :]= - np .inf # text rows see only the text 177s [:L , :L ]+= np .triu (np .full ((L ,L ),- np .inf ),1 )# and causally 178s -= s .max (- 1 ,keepdims = True ) 179p = np .exp (s ) 180p /= p .sum (- 1 ,keepdims = True ) 181if f16 : 182p = f16r (p .astype (F32 )).astype (np .float64 ) 183out [:,h ]= (p @v [:,h ].astype (np .float64 )).astype (F32 ) 184return out 185 186 187def prelude (Wt :DitWeights ,m :Mode ,t :float ,cond :np .ndarray ,x :np .ndarray ): 188tm = timestep_embedding (np .array ([t ,0.0 ],dtype = F32 )) 189tm = silu (m .gemm (tm ,m .w (Wt .mat ("time_text_embed.timestep_embedder.linear_1.weight" )))) 190tm = silu (m .gemm (tm ,m .w (Wt .mat ("time_text_embed.timestep_embedder.linear_2.weight" )))) 191mod = m .gemm (tm ,m .w (Wt .mat ("modulation.1.weight" )))# [2, 4C] 192scale = m .gemm (tm [:1 ],m .w (Wt .mat ("norm_out.linear.weight" )))[0 ]# [C] 193txt = rms_norm (cond , (Wt .mat ("txt_in.text_norm.weight" ).reshape (- 1 )+ F32 (1 )).astype (F32 )) 194txt = gelu_tanh (m .gemm (txt ,m .w (Wt .mat ("txt_in.in_layer.weight" )))) 195txt = m .gemm (txt ,m .w (Wt .mat ("txt_in.out_layer.weight" ))) 196C ,Hh ,Ww = x .shape 197tok = x .reshape (C ,Hh * Ww ).T .copy ()# token h*W + w, channels 198img = m .gemm (tok ,m .w (Wt .mat ("img_in.weight" ))) 199return mod ,scale ,np .concatenate ([txt ,img ],0 ) 200 201 202def block (Wt :DitWeights ,m :Mode ,i :int ,xj :np .ndarray ,rows :np .ndarray ,mods ,L :int ,c ,s ,wcache = None ,mx = None , 203cap = None ): 204p = f"transformer_blocks. { i } ." 205C = xj .shape [1 ] 206H ,D = C // 128 ,128 207W = wcache if wcache is not None else {} 208if not W : 209for n in ("attn.to_q" ,"attn.to_k" ,"attn.to_v" ,"attn.to_out.0" ,"img_mlp.gate_up" ,"img_mlp.out" ): 210W [n ]= m .w (Wt .mat (p + n + ".weight" )) 211W ["nq" ]= Wt .mat (p + "attn.norm_q.weight" ).reshape (- 1 ) 212W ["nk" ]= Wt .mat (p + "attn.norm_k.weight" ).reshape (- 1 ) 213m0 ,m1 ,m2 ,m3 = (mods [:,k * C :(k + 1 )* C ][rows ]for k in range (4 ))# per token rows 214h = (layer_norm (xj )* (F32 (1 )+ m0 )).astype (F32 ) 215n = xj .shape [0 ] 216qr ,kr = m .gemm (h ,W ["attn.to_q" ]),m .gemm (h ,W ["attn.to_k" ]) 217q = rms_norm (qr .reshape (n ,H ,D ),W ["nq" ]) 218k = rms_norm (kr .reshape (n ,H ,D ),W ["nk" ]) 219v = m .gemm (h ,W ["attn.to_v" ]).reshape (n ,H ,D ) 220q ,k = apply_rope (q ,c ,s ),apply_rope (k ,c ,s ) 221a = attention (q ,k ,v ,L ,m .f16 ).reshape (n ,C ) 222if mx is not None :# largest |value| of every GEMM / attention input, text and image rows 223for nm ,arr in (("qkv_in" ,h ), ("q" ,q ), ("k" ,k ), ("v" ,v ), ("to_out_in" ,a )): 224mx [f"txt { i } { nm } " ]= float (np .abs (arr [:L ]).max ()) 225mx [f"img { i } { nm } " ]= float (np .abs (arr [L :]).max ()) 226xj = (xj + (m .gemm (a ,W ["attn.to_out.0" ])* np .tanh (m1 .astype (np .float64 )).astype (F32 ))).astype (F32 ) 227h = (layer_norm (xj )* (F32 (1 )+ m2 )).astype (F32 ) 228if cap is not None :# one block in detail (image rows; K / V over all rows) 229cap .update (qkv = np .concatenate ([qr ,kr ,v .reshape (n ,C )],1 )[L :],q16 = q [L :],k16 = k ,v16 = v ,att = a [L :], 230x_mid = xj [L :].copy (),ln2 = h [L :]) 231gu = m .gemm (h ,W ["img_mlp.gate_up" ]) 232F = gu .shape [1 ]// 2 233act = (gu [:,F :]* silu (gu [:, :F ])).astype (F32 ) 234if mx is not None : 235for nm ,arr in (("gate_up_in" ,h ), ("out_in" ,act )): 236mx [f"txt { i } { nm } " ]= float (np .abs (arr [:L ]).max ()) 237mx [f"img { i } { nm } " ]= float (np .abs (arr [L :]).max ()) 238xj = (xj + (m .gemm (act ,W ["img_mlp.out" ])* np .tanh (m3 .astype (np .float64 )).astype (F32 ))).astype (F32 ) 239if cap is not None : 240cap .update (act = act [L :]) 241return xj 242 243 244def head (Wt :DitWeights ,m :Mode ,xj :np .ndarray ,L :int ,scale :np .ndarray ,Hh :int ,Ww :int )-> np .ndarray : 245img = (layer_norm (xj [L :])* (F32 (1 )+ scale )).astype (F32 ) 246out = m .gemm (img ,m .w (Wt .mat ("proj_out.weight" )))# [T, 64] 247return out .T .reshape (- 1 ,Hh ,Ww ).astype (F32 ) 248 249 250TRACE :dict = {} 251MAXIMA :dict = {} 252STATES :dict = {} 253CAPS :dict = {} 254 255 256def trace_cmp (pat :str ,d :Path ,mode :str ,stage :str ,parts :dict ,normalise :bool = False )-> None : 257"""rel L2 of our run (the trace files) against this mode's value at the same stage, kept in TRACE.""" 258tdir = Path (pat .replace ("{name}" ,d .name )) 259for part , (ref ,fname )in parts .items (): 260f = tdir / fname 261if not f .is_file (): 262continue 263ours = np .fromfile (f ,dtype = "<f4" ).reshape (ref .shape ) 264if normalise : 265ours = layer_norm (ours ) 266r = compare (ours ,ref ) 267TRACE .setdefault ((d .name ,stage ,part ), {})[mode ]= r ["rel_l2" ] 268 269 270def load_dump (d :Path ,name :str ): 271shape = [int (v )for v in (d / f" { name } .shape" ).read_text ().split ()] 272a = np .fromfile (d / f" { name } .bin" ,dtype = "<f4" ) 273return a ,shape 274 275 276def main (argv = None )-> int : 277ap = argparse .ArgumentParser () 278ap .add_argument ("gguf" ) 279ap .add_argument ("--dumps" ,nargs = "+" ,required = True ) 280ap .add_argument ("--call" ,type = int ,default = 0 ) 281ap .add_argument ("--mode" ,default = "f32,f16op" ) 282ap .add_argument ("--out-dir" ) 283ap .add_argument ("--cmp" ,action = "append" ,default = []) 284ap .add_argument ("--layers" ,type = int ,default = 0 ) 285ap .add_argument ("--trace-block" ,type = int ,default =- 1 ,help = "with --trace: compare the inside of this block (image rows)" ) 286ap .add_argument ("--trace" ,help = "per-stage comparison with a STRATA_DIT_TRACE_DIR dump; {name} = the dump dir name" ) 287a = ap .parse_args (argv ) 288Wt = DitWeights (Path (a .gguf )) 289modes = a .mode .split ("," ) 290jobs = {} 291for dd in a .dumps : 292d = Path (dd ) 293xv ,xs = load_dump (d ,f"dit_x_ { a . call } " ) 294tv ,_ = load_dump (d ,f"dit_t_ { a . call } " ) 295cv ,cs = load_dump (d ,"cond" ) 296Ww ,Hh ,C = xs [0 ],xs [1 ],xs [2 ] 297jobs [d ]= {"x" :xv .reshape (C ,Hh ,Ww ),"t" :float (tv [0 ]),"cond" :cv .reshape (cs [1 ],cs [0 ]),"H" :Hh ,"W" :Ww } 298state = {} 299t0 = time .time () 300for mname in modes : 301m = make_mode (mname ) 302for d ,j in jobs .items (): 303mods ,scale ,xj = prelude (Wt ,m ,j ["t" ],j ["cond" ],j ["x" ]) 304L = j ["cond" ].shape [0 ] 305c ,s = rope_table (layout_positions (L ,j ["H" ],j ["W" ])) 306rows = np .array ([1 ]* L + [0 ]* (xj .shape [0 ]- L )) 307state [(d ,mname )]= [mods ,scale ,xj ,L ,c ,s ,rows ] 308if a .trace : 309trace_cmp (a .trace ,d ,mname ,"prelude" , {"mod" : (mods ,"mod.bin" ),"scale" : (scale [None , :],"scale.bin" ), 310"txt_in" : (xj [:L ],"txtin.bin" ),"img_in" : (xj [L :],"imgin.bin" )}) 311nl = a .layers or Wt .n_layer 312for i in range (nl ): 313for mname in modes : 314m = make_mode (mname ) 315wc = {} 316for d in jobs : 317st = state [(d ,mname )] 318mx = MAXIMA .setdefault ((d .name ,mname ), {})if a .trace else None 319cap = CAPS .setdefault ((d .name ,mname ), {})if (a .trace and i == a .trace_block )else None 320st [2 ]= block (Wt ,m ,i ,st [2 ],st [6 ],st [0 ],st [3 ],st [4 ],st [5 ],wc ,mx ,cap ) 321if a .trace : 322L = st [3 ] 323trace_cmp (a .trace ,d ,mname ,f"block { i :02d } " , {"txt" : (st [2 ][:L ],f"txt_ { i :02d } .bin" ), 324"img" : (st [2 ][L :],f"img_ { i :02d } .bin" )}) 325# what the next step reads of the stream is LayerNorm(x): the same comparison per token-normalised 326trace_cmp (a .trace ,d ,mname ,f"block { i :02d } " , {"txt LN" : (layer_norm (st [2 ][:L ]),f"txt_ { i :02d } .bin" ), 327"img LN" : (layer_norm (st [2 ][L :]),f"img_ { i :02d } .bin" )}, 328normalise = True ) 329STATES [(d .name ,mname ,i )]= st [2 ].copy () 330if a .trace and "f32" in modes and "f16op" in modes :# the emulation against the reference, same stage 331for d in jobs : 332L = state [(d ,"f32" )][3 ] 333for part ,sl in (("txt" ,slice (0 ,L )), ("img" ,slice (L ,None ))): 334TRACE .setdefault ((d .name ,f"block { i :02d } " ,part ), {})["emu_vs_f32" ]= \ 335compare (state [(d ,"f16op" )][2 ][sl ],state [(d ,"f32" )][2 ][sl ])["rel_l2" ] 336f"block { i } done { time . time () - t0 :.0f } s" ,flush = True ) 337res = {} 338out = Path (a .out_dir )if a .out_dir else None 339if out : 340out .mkdir (parents = True ,exist_ok = True ) 341for d ,j in jobs .items (): 342r = {"t" :j ["t" ],"text_tokens" :int (j ["cond" ].shape [0 ]),"image_tokens" :j ["H" ]* j ["W" ]} 343vel = {} 344for mname in modes : 345st = state [(d ,mname )] 346vel [mname ]= head (Wt ,make_mode (mname ),st [2 ],st [3 ],st [1 ],j ["H" ],j ["W" ]) 347if a .trace : 348trace_cmp (a .trace ,d ,mname ,"head" , {"velocity" : (vel [mname ].reshape (64 ,- 1 ).T ,"out.bin" )}) 349if out : 350np .save (out / f" { d . name } _ { mname } .npy" ,vel [mname ]) 351if "f32" in vel and "f16op" in vel : 352r ["f16op_vs_f32" ]= compare (vel ["f16op" ].reshape (64 ,- 1 ).T ,vel ["f32" ].reshape (64 ,- 1 ).T ) 353for spec in a .cmp : 354name ,pat = spec .split ("=" ,1 ) 355p = Path (pat .replace ("{dump}" ,str (d )).replace ("{name}" ,d .name )) 356if not p .is_file (): 357continue 358ref = np .fromfile (p ,dtype = "<f4" ).reshape (64 ,- 1 ).T 359for mname in modes : 360r [f" { name } _vs_ { mname } " ]= compare (ref ,vel [mname ].reshape (64 ,- 1 ).T ) 361res [d .name ]= r 362d .name ,json .dumps ({k : ({kk :round (vv ,6 )if isinstance (vv ,float )else vv for kk ,vv in v .items ()} 363if isinstance (v ,dict )else v )for k ,v in r .items ()}),flush = True ) 364keys = sorted ({k for r in res .values ()for k ,v in r .items ()if isinstance (v ,dict )}) 365for k in keys : 366rows = [r [k ]for r in res .values ()if k in r ] 367f"SUMMARY { k } : n { len ( rows ) } rel_l2 mean { np . mean ([ x [ 'rel_l2' ] for x in rows ]):.6f } max " 368f" { max ( x [ 'rel_l2' ] for x in rows ):.6f } cos min { min ( x [ 'cos' ] for x in rows ):.8f } " ) 369if out : 370 (out / "dit_ref.json" ).write_text (json .dumps (res ,indent = 1 )) 371if a .trace : 372for dn in sorted ({k [0 ]for k in TRACE }): 373f"TRACE { dn } : stage | part | ours vs f32 | ours vs f16op | f16op vs f32" ) 374for (n ,stage ,part ),v in TRACE .items (): 375if n == dn : 376f = lambda key :f" { v [ key ]:.6f } " if key in v else "-" # noqa: E731 377f"TRACE { dn } | { stage } | { part } | { f ( 'f32' ) } | { f ( 'f16op' ) } | { f ( 'emu_vs_f32' ) } " ) 378# alignment check: our block-i dump against the reference after blocks i-1, i, i+1 (f32 mode, image rows) 379for dn in sorted ({k [0 ]for k in STATES }): 380tdir = Path (a .trace .replace ("{name}" ,dn )) 381for i in (0 ,1 ,2 ,5 ,15 ,30 ): 382f = tdir / f"img_ { i :02d } .bin" 383if not f .is_file ()or (dn ,"f32" ,i )not in STATES : 384continue 385L = next (st [3 ]for (dd ,mm ),st in state .items ()if dd .name == dn and mm == "f32" ) 386ours = np .fromfile (f ,dtype = "<f4" ).reshape (- 1 ,STATES [(dn ,"f32" ,i )].shape [1 ]) 387cells = [] 388for j in (i - 1 ,i ,i + 1 ): 389if (dn ,"f32" ,j )in STATES : 390cells .append (f"ref after block { j } : { compare ( ours , STATES [( dn , 'f32' , j )][ L :])[ 'rel_l2' ]:.5f } " ) 391f"ALIGN { dn } ours img after block { i } : " + "; " .join (cells )) 392for (dn ,mname ),cp in sorted (CAPS .items ()): 393if mname != "f32" or not cp : 394continue 395tdir = Path (a .trace .replace ("{name}" ,dn )) 396emu = CAPS .get ((dn ,"f16op" ), {}) 397n = cp ["att" ].shape [0 ] 398Hh ,D = cp ["q16" ].shape [1 ],cp ["q16" ].shape [2 ] 399def ours (name ,shape ,dt = "<f4" ): 400f = tdir / name 401return np .fromfile (f ,dtype = dt ).astype (np .float32 ).reshape (shape )if f .is_file ()else None 402q16 = ours ("blk_q16.bin" , (Hh ,n ,D ),"<f2" ) 403kvt = cp ["k16" ].shape [0 ] 404got = {"qkv" :ours ("blk_qkv.bin" , (n ,- 1 )),"q16" :None if q16 is None else q16 .transpose (1 ,0 ,2 ), 405"k16" :ours ("blk_k16.bin" , (Hh ,kvt ,D ),"<f2" ),"v16" :ours ("blk_v16.bin" , (Hh ,kvt ,D ),"<f2" ), 406"att" :ours ("blk_att.bin" , (n ,- 1 )),"x_mid" :ours ("blk_x_mid.bin" , (n ,- 1 )),"ln2" :ours ("blk_ln2.bin" , (n ,- 1 )), 407"act" :ours ("blk_act.bin" , (n ,- 1 ))} 408for key in ("k16" ,"v16" ): 409if got [key ]is not None : 410got [key ]= got [key ].transpose (1 ,0 ,2 ) 411f"BLOCK { a . trace_block } { dn } | stage | ours vs f32 | ours vs f16op | f16op vs f32" ) 412for key in ("qkv" ,"q16" ,"k16" ,"v16" ,"att" ,"x_mid" ,"ln2" ,"act" ): 413g = got [key ] 414if g is None : 415continue 416r = cp [key ].reshape (g .shape [0 ],- 1 ) 417gg = g .reshape (g .shape [0 ],- 1 ) 418e = emu [key ].reshape (g .shape [0 ],- 1 )if key in emu else None 419f = lambda x ,y :"%.6f" % compare (x ,y )["rel_l2" ]# noqa: E731 420ge = f (gg ,e )if e is not None else "-" 421er = f (e ,r )if e is not None else "-" 422f"BLOCK { a . trace_block } { dn } | { key } | { f ( gg , r ) } | { ge } | { er } " ) 423for (dn ,mname ),mx in MAXIMA .items (): 424if mname == "f32" : 425f"MAXIMA { dn } f32 " + json .dumps ({k :round (x ,4 )for k ,x in mx .items ()})) 426if out : 427 (out / "trace.json" ).write_text (json .dumps ({"trace" : {" | " .join (k ):v for k ,v in TRACE .items ()}, 428"maxima" : {" | " .join (k ):v for k ,v in MAXIMA .items ()}})) 429return 0 430 431 432if __name__ == "__main__" : 433sys .exit (main ())