okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3dfb046bf
main
1"""Checks the Metal engine's DFlash2 drafter against the torch port (dflash2_ref.py) on a real round. 2 3python check_metal_dump.py <dump.bin> <drafter.safetensors> <drafter_config.json> 4 5dump.bin is written by the Metal engine with STRATA_DF2_DUMP=<file> [STRATA_DF2_DUMP_ROUND=n] (metal/src/engine/dflash2.inc): every context row the 6drafter was given (positions 0 .. s-1: a prompt short enough that the whole context was fed), the anchor and mask embeddings, and the engine's answer 7of that round (the 8 final normalized rows, the selector's hidden projection, the top-16 per row, the picked tokens and their probabilities, the 8draft head's logits). The checks: 91. the 8 final rows against the torch port run on the same context (weights fp32 against the engine's Q8_0: cosine similarity, not equality), 102. the engine's top-16 per row against a sort of its own logits, 113. the selector's walk (torch, on the engine's own rows and candidates) against the engine's picks. 12""" 13import struct 14import sys 15from pathlib import Path 16 17import numpy as np 18import torch 19 20sys .path .insert (0 ,str (Path (__file__ ).parent )) 21import dflash2_ref as R 22 23 24class Embed : 25def __init__ (self ,rows ): 26self .rows = rows 27 28def __getitem__ (self ,ids ): 29return torch .stack ([self .rows [int (i )]for i in ids ]) 30 31 32def main (): 33dump ,st ,cfgp = sys .argv [1 :4 ] 34raw = open (dump ,"rb" ).read () 35magic ,ver ,s ,anchor ,nd ,nt ,H ,mask = struct .unpack_from ("<8i" ,raw ,0 ) 36assert magic == 0x32465344 ,"not a DF2 dump" 37off = 32 38def take (n ,dt = np .float32 ): 39nonlocal off 40a = np .frombuffer (raw ,dt ,n ,off ) 41off += a .nbytes 42return a 43taps = take (s * nt * H ).reshape (s ,nt * H ) 44emb_a ,emb_m = take (H ),take (H ) 45fn = take (8 * H ).reshape (8 ,H ) 46hsel = take (7 * 256 ).reshape (7 ,256 ) 47topval = take (7 * 16 ).reshape (7 ,16 ) 48toptok = take (7 * 16 ,np .int32 ).reshape (7 ,16 ) 49out = take (32 ,np .int32 ) 50out_prob = np .frombuffer (out .tobytes (),np .float32 )[16 :23 ] 51out_tok = out [:7 ] 52rest = len (raw )- off 53has_map = rest > 7 * nd * 4 54vmap = take (nd ,np .int32 )if has_map else None 55logits = take (7 * nd ).reshape (7 ,nd ) 56"dump: %d context rows, anchor %d, %d-token head%s" % (s ,anchor ,nd ," (mapped)" if has_map else "" )) 57 58d = R .Drafter (st ,cfgp ,Embed ({anchor :torch .from_numpy (emb_a .copy ()),mask :torch .from_numpy (emb_m .copy ())}),torch .randn (64 ,H ),threads = 6 ) 59d .set_context (torch .from_numpy (taps .copy ())) 60d .draft (s ,anchor ,8 ) 61ref = d .last_all .numpy () 62bad = 0 63"1. final rows against the torch port (fp32 weights):" ) 64worst = 1.0 65for r in range (8 ): 66a ,b = fn [r ].astype (np .float64 ),ref [r ].astype (np .float64 ) 67cs = float (a @b / (np .linalg .norm (a )* np .linalg .norm (b )+ 1e-30 )) 68worst = min (worst ,cs ) 69" row %d: cos %.5f norm ratio %.4f" % (r ,cs ,np .linalg .norm (a )/ (np .linalg .norm (b )+ 1e-30 ))) 70if worst < 0.98 : 71" FAIL: a row's cosine similarity %.4f is below 0.98" % worst ) 72bad += 1 73 74"2. top-16 of the engine's logits:" ) 75for i in range (7 ): 76order = np .lexsort ((np .arange (nd ),- logits [i ]))[:16 ]# value descending, ties to the lower column 77want = (vmap [order ]if has_map else order ).astype (np .int32 ) 78if not (np .array_equal (want ,toptok [i ])and np .allclose (logits [i ][order ],topval [i ])): 79" FAIL row %d: engine %s, sort %s" % (i ,toptok [i ].tolist (),want .tolist ())) 80bad += 1 81if not bad : 82" all 7 rows equal" ) 83 84"3. the selector's walk on the engine's rows and candidates:" ) 85w = d .w 86hp = torch .from_numpy (fn [1 :].copy ()) @w ["candidate_selector.hidden_projection.weight" ].T 87A ,B = w ["candidate_selector.predecessor_codebook" ],w ["candidate_selector.successor_codebook" ] 88pred = anchor 89same = 0 90for i in range (7 ): 91cand = torch .from_numpy (toptok [i ].astype (np .int64 )) 92sc = torch .from_numpy (topval [i ].copy ())+ (B [cand ].float () @ (A [pred ].float ()* hp [i ])) 93j = int (torch .argmax (sc )) 94p = float (torch .softmax (sc ,dim =- 1 )[j ]) 95pick = int (cand [j ]) 96ok = pick == int (out_tok [i ])and abs (p - float (out_prob [i ]))< 0.02 97same += ok 98" %d: engine %d (p %.3f) torch %d (p %.3f) %s" % (i ,out_tok [i ],out_prob [i ],pick ,p ,"ok" if ok else "DIFF" )) 99pred = int (out_tok [i ]) 100if same < 7 : 101bad += 1 102"hsel against torch: max abs diff %.4f" % float (np .abs (hsel - hp .numpy ()).max ())) 103"check_metal_dump: %s" % ("FAIL" if bad else "ok" )) 104return 1 if bad else 0 105 106 107if __name__ == "__main__" : 108sys .exit (main ())