okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1# Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). 2# Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file. 3"""tools/ds4/dspark_ref.py - DeepSeek-V4.1's DSpark drafter in torch, straight from DeepSeek's checkpoint, against what 4the engine's drafter computed (the engine's oracle for the drafter; ref.py / ref_gguf.py cover the trunk only). 5 6DS4_DSPARK_DUMP=d.bin maya-ds4 --pack <pack> ... --n 64 (the engine: its drafter's inputs and outputs) 7python tools/ds4/dspark_ref.py --dump d.bin --shards <dir with model-00044..46-of-00048> --pack <pack> 8[--rounds 4] [--head] 9 10It follows DeepSeek's inference/model.py (MIT) - DSparkBlock / DSparkAttention / forward_spec: the taps of target 11layers 37..39 (the streams' mean entering them) through main_proj / main_norm into every block's window ring (wkv, 12kv_norm, rope, FP8 rounding), the block [y, noise x 4] at the positions after the ring's through the three blocks 13(Hyper-Connections, window attention over the ring and the whole block, the 128-expert MoE with 3 picks), the final 14collapse and, with --head, the trunk's head plus the markov bias (the drafts) - with every weight decoded here from 15the checkpoint's own FP8 / FP4 / BF16 tensors (not from drafter_pack.py's dspark.bin), activations F32. Per round 16it prints how far the engine's hidden rows and confidences are from it, and with --head whether the drafts agree. 17""" 18from __future__import annotations 19 20import argparse 21import json 22import math 23import pathlib 24import struct 25import sys 26 27import numpy as np 28import torch 29import torch .nn .functional as F 30 31SHARDS = ("model-00044-of-00048.safetensors" ,"model-00045-of-00048.safetensors" ,"model-00046-of-00048.safetensors" ) 32 33 34def e4m3_table ()-> np .ndarray : 35t = np .zeros (256 ,np .float32 ) 36for c in range (256 ): 37s ,e ,m = c >> 7 , (c >> 3 )& 15 ,c & 7 38v = np .nan if (e == 15 and m == 7 )else (m / 8.0 )* 2.0 ** - 6 if e == 0 else (1 + m / 8.0 )* 2.0 ** (e - 7 ) 39t [c ]= - v if s else v 40return t 41 42 43E4M3 = e4m3_table () 44E2M1 = np .array ([0 ,0.5 ,1 ,1.5 ,2 ,3 ,4 ,6 ,- 0.0 ,- 0.5 ,- 1 ,- 1.5 ,- 2 ,- 3 ,- 4 ,- 6 ],np .float32 ) 45 46 47class Ckpt : 48"""The drafter's shards: each tensor decoded to F32 on request (FP8 with its 32 x 32 E8M0 block scales; FP4 codes 49two to a byte, the first in the low nibble, an E8M0 scale per 32 along K; BF16; F32).""" 50 51def __init__ (self ,d :pathlib .Path ): 52self .t = {} 53for name in SHARDS : 54raw = np .memmap (d / name ,np .uint8 ,mode = "r" ) 55n = struct .unpack ("<Q" ,bytes (raw [:8 ]))[0 ] 56head = json .loads (bytes (raw [8 :8 + n ])) 57head .pop ("__metadata__" ,None ) 58for k ,e in head .items (): 59self .t [k ]= (raw ,8 + n ,e ) 60 61def raw (self ,k ): 62raw ,base ,e = self .t [k ] 63a ,b = e ["data_offsets" ] 64return raw [base + a :base + b ],e ["dtype" ],e ["shape" ] 65 66def get (self ,k )-> torch .Tensor : 67w ,dt ,sh = self .raw (k ) 68if dt == "F32" : 69v = np .frombuffer (w ,np .float32 ).reshape (sh ) 70elif dt == "BF16" : 71v = (np .frombuffer (w ,np .uint16 ).astype (np .uint32 )<< 16 ).view (np .float32 ).reshape (sh ) 72elif dt == "F8_E4M3" : 73s ,_ ,ssh = self .raw (k [:- len ("weight" )]+ "scale" ) 74r ,c = sh 75sc = np .exp2 (np .asarray (s ,np .float32 ).reshape (ssh )- 127.0 ) 76v = E4M3 [np .asarray (w ).reshape (r ,c )]* np .repeat (np .repeat (sc ,32 ,0 ),32 ,1 )[:r , :c ] 77elif dt == "I8" : 78s ,_ ,ssh = self .raw (k [:- len ("weight" )]+ "scale" ) 79r ,c2 = sh 80p = np .asarray (w ).reshape (r ,c2 ) 81codes = np .empty ((r ,c2 * 2 ),np .uint8 ) 82codes [:,0 ::2 ]= p & 15 83codes [:,1 ::2 ]= p >> 4 84sc = np .exp2 (np .asarray (s ,np .float32 ).reshape (ssh )- 127.0 ) 85v = E2M1 [codes ]* np .repeat (sc ,32 ,1 ) 86else : 87raise SystemExit ("%s: dtype %s" % (k ,dt )) 88return torch .from_numpy (np .ascontiguousarray (v ,np .float32 )) 89 90 91def fp8_round (x :torch .Tensor ,block :int = 32 )-> torch .Tensor : 92sh = x .shape 93v = x .float ().reshape (* sh [:- 1 ],sh [- 1 ]// block ,block ) 94amax = v .abs ().amax (- 1 ,keepdim = True ).clamp_min (1e-4 ) 95s = torch .exp2 (torch .ceil (torch .log2 (amax / 448.0 ))) 96y = (v / s ).clamp (- 448.0 ,448.0 ).to (torch .float8_e4m3fn ).float ()* s 97return y .reshape (sh ) 98 99 100def rms (x ,w ,eps ): 101x = x .float () 102y = x * torch .rsqrt (x .square ().mean (- 1 ,keepdim = True )+ eps ) 103return y * w if w is not None else y 104 105 106def freqs (dim ,n ,base ): 107f = 1.0 / (base ** (torch .arange (0 ,dim ,2 ,dtype = torch .float32 )/ dim )) 108a = torch .outer (torch .arange (n ,dtype = torch .float32 ),f ) 109return torch .polar (torch .ones_like (a ),a ) 110 111 112def rope (x ,fc ,inverse = False ): 113c = torch .view_as_complex (x .float ().reshape (* x .shape [:- 1 ],- 1 ,2 ).contiguous ()) 114if inverse : 115fc = fc .conj () 116if x .ndim == 3 : 117fc = fc [:,None , :] 118return torch .view_as_real (c * fc ).flatten (- 2 ) 119 120 121def pack_conf (pack :pathlib .Path ): 122cfg = {} 123for line in (pack / "ds4.txt" ).read_text ().splitlines (): 124k ,_ ,v = line .partition (" " ) 125cfg [k ]= v 126files ,tens = {}, {} 127for line in (pack / "tensors.txt" ).read_text ().splitlines (): 128p = line .split () 129if p [0 ]== "file" : 130files [int (p [1 ])]= p [2 ] 131elif p [0 ]== "t" : 132tens [p [1 ]]= (p [2 ],int (p [3 ]),int (p [4 ]),int (p [5 ]), [int (x )for x in p [6 :]]) 133return cfg ,files ,tens 134 135 136def gguf_rows (pack ,cfg ,files ,tens ,name ): 137dt ,fi ,off ,nb ,sh = tens [name ] 138if dt != "BF16" : 139raise SystemExit ("%s: %s, the oracle reads a BF16 one" % (name ,dt )) 140path = pathlib .Path (cfg ["model_dir" ])/ files [fi ] 141return np .memmap (path ,np .uint16 ,mode = "r" ,offset = off ,shape = tuple (sh )) 142 143 144def bf16_rows (m ,idx ): 145return torch .from_numpy ((np .asarray (m [idx ]).astype (np .uint32 )<< 16 ).view (np .float32 )) 146 147 148class Drafter : 149def __init__ (self ,ck :Ckpt ,cfg :dict ): 150self .ck ,self .cfg = ck ,cfg 151self .D = int (cfg ["hidden_size" ]) 152self .hc = int (cfg ["hc_mult" ]) 153self .eps = float (cfg ["rms_norm_eps" ]) 154self .hc_eps = float (cfg ["hc_eps" ]) 155self .sink_iters = int (cfg ["hc_sinkhorn_iters" ]) 156self .H ,self .HD ,self .rd = int (cfg ["num_attention_heads" ]),int (cfg ["head_dim" ]),int (cfg ["qk_rope_head_dim" ]) 157self .G = int (cfg ["o_groups" ]) 158self .win = int (cfg ["sliding_window" ]) 159self .k = int (cfg ["dspark_num_experts_per_tok" ]) 160self .scale = float (cfg ["routed_scaling_factor" ]) 161self .lim = float (cfg ["swiglu_limit" ]) 162self .fc = freqs (self .rd ,1 << 16 ,float (cfg ["rope_theta" ])) 163self .nb = 3 164self .cache = {} 165self .ring = [dict ()for _ in range (self .nb )]# position -> main KV row, per block 166 167def W (self ,k ): 168if k not in self .cache : 169self .cache [k ]= self .ck .get (k ) 170return self .cache [k ] 171 172def seed (self ,p0 ,taps ):# taps [n, 3 * D] 173main_x = rms (taps @self .W ("mtp.0.main_proj.weight" ).T ,self .W ("mtp.0.main_norm.weight" ),self .eps ) 174n = taps .shape [0 ] 175fc = self .fc [p0 :p0 + n ] 176for b in range (self .nb ): 177A = "mtp.%d.attn." % b 178kv = rms (main_x @self .W (A + "wkv.weight" ).T ,self .W (A + "kv_norm.weight" ),self .eps ) 179kv = torch .cat ([kv [:, :- self .rd ],rope (kv [:,- self .rd :],fc )],- 1 ) 180kv = fp8_round (kv ) 181for i in range (n ): 182self .ring [b ][p0 + i ]= kv [i ] 183 184def hc_mixes (self ,x ,P ): 185hc = self .hc 186fn ,scale ,base = self .W (P + "_fn" ),self .W (P + "_scale" ),self .W (P + "_base" ) 187xf = x .flatten (1 ).float () 188r = torch .rsqrt (xf .square ().mean (- 1 ,keepdim = True )+ self .eps ) 189mixes = (xf @fn .T )* r 190pre = torch .sigmoid (mixes [:, :hc ]* scale [0 ]+ base [:hc ])+ self .hc_eps 191post = 2 * torch .sigmoid (mixes [:,hc :2 * hc ]* scale [1 ]+ base [hc :2 * hc ]) 192comb = (mixes [:,2 * hc :]* scale [2 ]+ base [2 * hc :]).view (- 1 ,hc ,hc ) 193eps = self .hc_eps 194comb = comb .softmax (- 1 )+ eps 195comb = comb / (comb .sum (- 2 ,keepdim = True )+ eps ) 196for _ in range (self .sink_iters - 1 ): 197comb = comb / (comb .sum (- 1 ,keepdim = True )+ eps ) 198comb = comb / (comb .sum (- 2 ,keepdim = True )+ eps ) 199return pre ,post ,comb 200 201def attention (self ,b ,x ,p0 ): 202A = "mtp.%d.attn." % b 203T = x .shape [0 ] 204H ,D ,rd = self .H ,self .HD ,self .rd 205fc = self .fc [p0 :p0 + T ] 206qr = rms (x @self .W (A + "wq_a.weight" ).T ,self .W (A + "q_norm.weight" ),self .eps ) 207q = (qr @self .W (A + "wq_b.weight" ).T ).view (T ,H ,D ) 208q = torch .cat ([q [..., :- rd ],rope (q [...,- rd :],fc )],- 1 ) 209kv = rms (x @self .W (A + "wkv.weight" ).T ,self .W (A + "kv_norm.weight" ),self .eps ) 210kv = torch .cat ([kv [:, :- rd ],rope (kv [:,- rd :],fc )],- 1 ) 211kv = fp8_round (kv ) 212ring = [self .ring [b ][p ]for p in range (max (0 ,p0 - self .win ),p0 )if p in self .ring [b ]] 213allkv = torch .cat ([torch .stack (ring ),kv ],0 )if ring else kv 214sink = self .W (A + "attn_sink" ) 215s = torch .einsum ("thd,kd->thk" ,q ,allkv )* D ** - 0.5 216m = torch .maximum (s .amax (- 1 ),sink [None , :]) 217pr = torch .exp (s - m .unsqueeze (- 1 )) 218den = pr .sum (- 1 )+ torch .exp (sink [None , :]- m ) 219o = torch .einsum ("thk,kd->thd" ,pr ,allkv )/ den .unsqueeze (- 1 ) 220o = torch .cat ([o [..., :- rd ],rope (o [...,- rd :],fc ,inverse = True )],- 1 ) 221o = fp8_round (o .reshape (T ,self .G ,- 1 )) 222wo_a = self .W (A + "wo_a.weight" ).view (self .G ,- 1 ,o .shape [- 1 ]) 223oa = torch .einsum ("tgd,grd->tgr" ,o ,wo_a ) 224return oa .flatten (1 ) @self .W (A + "wo_b.weight" ).T 225 226def moe (self ,b ,x ): 227M = "mtp.%d.ffn." % b 228T = x .shape [0 ] 229scores = F .softplus (x .float () @self .W (M + "gate.weight" ).T ).sqrt () 230idx = (scores + self .W (M + "gate.bias" )).topk (self .k ,dim =- 1 )[1 ] 231wts = scores .gather (1 ,idx ) 232wts = wts / (wts .sum (- 1 ,keepdim = True )+ 1e-20 )* self .scale 233lim = self .lim 234y = torch .zeros (T ,self .D ) 235for e in torch .unique (idx ).tolist (): 236P = M + "experts.%d." % e 237rows ,slot = torch .where (idx == e ) 238xs = x [rows ] 239w1 ,w3 = self .ck .get (P + "w1.weight" ),self .ck .get (P + "w3.weight" ) 240h = F .silu ((xs @w1 .T ).clamp (max = lim ))* (xs @w3 .T ).clamp (- lim ,lim ) 241del w1 ,w3 242w2 = self .ck .get (P + "w2.weight" ) 243y .index_add_ (0 ,rows , (h * wts [rows ,slot ,None ]) @w2 .T ) 244del w2 245S = M + "shared_experts." 246h = F .silu ((x @self .W (S + "w1.weight" ).T ).clamp (max = lim ))* (x @self .W (S + "w3.weight" ).T ).clamp (- lim ,lim ) 247return y + h @self .W (S + "w2.weight" ).T ,idx 248 249def block_forward (self ,emb ,p0 ):# emb [T, D] -> the collapsed hidden rows [T, D], each block's stream 250T = emb .shape [0 ] 251h = emb .unsqueeze (1 ).repeat (1 ,self .hc ,1 ) 252pre = torch .zeros (T ,self .hc ) 253pre [:,0 ]= 1.0 254routes = [] 255streams = [] 256for b in range (self .nb ): 257B = "mtp.%d." % b 258res = h 259a_pre ,a_post ,a_comb = self .hc_mixes (h ,B + "hc_attn" ) 260x = rms ((pre .unsqueeze (- 1 )* h ).sum (1 ),self .W (B + "attn_norm.weight" ),self .eps ) 261y = self .attention (b ,x ,p0 ) 262h = a_post .unsqueeze (- 1 )* y .unsqueeze (1 )+ (a_comb .unsqueeze (- 1 )* res .unsqueeze (2 )).sum (1 ) 263res = h 264f_pre ,f_post ,f_comb = self .hc_mixes (h ,B + "hc_ffn" ) 265x = rms ((a_pre .unsqueeze (- 1 )* h ).sum (1 ),self .W (B + "ffn_norm.weight" ),self .eps ) 266y ,idx = self .moe (b ,x ) 267routes .append (idx ) 268h = f_post .unsqueeze (- 1 )* y .unsqueeze (1 )+ (f_comb .unsqueeze (- 1 )* res .unsqueeze (2 )).sum (1 ) 269pre = f_pre 270streams .append (h ) 271return (pre .unsqueeze (- 1 )* h ).sum (1 ),routes ,streams 272 273 274def records (path ,nb ,hc ,win ,hd ): 275"""The engine's dump: 'S' seeds (first position, the taps), 'D' draft rounds (the block's position, y, the drafts, 276their confidences, the collapsed hidden rows, then per block the ring it read (BF16) and the stream it left).""" 277with open (path ,"rb" )as f : 278while True : 279hb = f .read (32 ) 280if len (hb )< 32 : 281return 282kind ,a ,b ,c = struct .unpack ("<4q" ,hb ) 283if kind == ord ("S" ): 284n ,w = b ,c 285taps = np .frombuffer (f .read (n * w * 4 ),np .float32 ).reshape (n ,w ) 286yield "S" ,a ,taps 287elif kind == ord ("D" ): 288T = c 289D = int (DIM [0 ]) 290toks = np .frombuffer (f .read (T * 4 ),np .int32 ) 291conf = np .frombuffer (f .read (T * 4 ),np .float32 ) 292x = np .frombuffer (f .read (T * 4 * D ),np .float32 ).reshape (T ,D ) 293rings ,streams = [], [] 294for _ in range (nb ): 295r = np .frombuffer (f .read (win * hd * 2 ),np .uint16 ).reshape (win ,hd ) 296rings .append ((r .astype (np .uint32 )<< 16 ).view (np .float32 )) 297streams .append (np .frombuffer (f .read (T * hc * D * 4 ),np .float32 ).reshape (T ,hc ,D )) 298yield "D" , (a ,b ,T ,toks ,conf ,x ,rings ,streams ),None 299else : 300raise SystemExit ("dump: record %d" % kind ) 301 302 303DIM = [5120 ] 304 305 306def rel (a :torch .Tensor ,b :torch .Tensor )-> float : 307return float ((a - b ).norm ()/ b .norm ().clamp_min (1e-30 )) 308 309 310def main ()-> int : 311ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 312ap .add_argument ("--dump" ,required = True ) 313ap .add_argument ("--shards" ,required = True ,help = "the folder with DeepSeek's model-00044..46-of-00048" ) 314ap .add_argument ("--pack" ,required = True ,help = "the maya-ds4 pack (ds4.txt, tensors.txt: the embedding, the head)" ) 315ap .add_argument ("--rounds" ,type = int ,default = 4 ,help = "draft rounds to check (from --skip)" ) 316ap .add_argument ("--skip" ,type = int ,default = 0 ,help = "draft rounds to pass over first" ) 317ap .add_argument ("--head" ,action = "store_true" ,help = "also the drafts: the trunk's head + the markov bias" ) 318ap .add_argument ("--threads" ,type = int ,default = 4 ) 319a = ap .parse_args () 320torch .set_num_threads (a .threads ) 321pack = pathlib .Path (a .pack ) 322cfg ,files ,tens = pack_conf (pack ) 323DIM [0 ]= int (cfg ["hidden_size" ]) 324ck = Ckpt (pathlib .Path (a .shards )) 325dr = Drafter (ck ,cfg ) 326emb = gguf_rows (pack ,cfg ,files ,tens ,"embed.weight" ) 327head = gguf_rows (pack ,cfg ,files ,tens ,"head.weight" )if a .head else None 328noise = int (cfg ["dspark_noise_token_id" ]) 329seen = done = 0 330worst_x = worst_c = 0.0 331agree = total = 0 332for kind ,v ,taps in records (a .dump ,dr .nb ,dr .hc ,dr .win ,dr .HD ): 333if kind == "S" : 334dr .seed (v ,torch .from_numpy (taps .copy ())) 335continue 336p0 ,y ,T ,toks ,conf ,xd ,rings ,streams = v 337seen += 1 338if seen <= a .skip : 339continue 340ex = torch .from_numpy (xd .copy ()) 341ids = [y ]+ [noise ]* (T - 1 ) 342xh ,routes ,ref_streams = dr .block_forward (bf16_rows (emb ,ids ),p0 ) 343for b in range (dr .nb ):# the ring each block read (the positions the reference holds), the stream it left 344ps = [p for p in range (max (0 ,p0 - dr .win ),p0 )if p in dr .ring [b ]] 345er = torch .from_numpy (rings [b ][[p % dr .win for p in ps ]].copy ()) 346rr = torch .stack ([dr .ring [b ][p ]for p in ps ]) 347" block %d: ring rel err %.4f (%d rows), stream rel err %.4f, routes %s" % ( 348b ,rel (er ,rr ),len (ps ),rel (torch .from_numpy (streams [b ].copy ()),ref_streams [b ]), 349routes [b ].tolist ()),flush = True ) 350prev = [y ]+ [int (t )for t in toks [:- 1 ]] 351me = dr .W ("mtp.2.markov_head.embed.weight" )[prev ] 352cw = dr .W ("mtp.2.confidence_head.proj.weight" )[0 ] 353cf = torch .sigmoid (torch .cat ([xh ,me ],- 1 ) @cw ) 354rerr = ((ex - xh ).norm (dim =- 1 )/ xh .norm (dim =- 1 )).tolist () 355cos = F .cosine_similarity (ex ,xh ,dim =- 1 ).tolist () 356dc = (torch .from_numpy (conf .copy ())- cf ).abs ().tolist () 357worst_x = max (worst_x ,max (rerr )) 358worst_c = max (worst_c ,max (dc )) 359line = "round %d (pos %d, y %d): hidden rel err %s, cos %s; conf engine %s ref %s" % ( 360seen ,p0 ,y ," " .join ("%.4f" % r for r in rerr )," " .join ("%.5f" % c for c in cos ), 361" " .join ("%.3f" % c for c in conf .tolist ())," " .join ("%.3f" % c for c in cf .tolist ())) 362if head is not None : 363xn = rms (xh ,dr .W ("mtp.2.norm.weight" ),dr .eps ) 364lg = torch .zeros (T ,head .shape [0 ]) 365for c0 in range (0 ,head .shape [0 ],16384 ): 366c1 = min (head .shape [0 ],c0 + 16384 ) 367lg [:,c0 :c1 ]= xn @bf16_rows (head ,slice (c0 ,c1 )).T 368mh = dr .W ("mtp.2.markov_head.head.weight" ) 369ref_t = [] 370p = y 371for i in range (T ):# greedy chain on the reference's own drafts 372row = lg [i ]+ mh @dr .W ("mtp.2.markov_head.embed.weight" )[p ] 373p = int (row .argmax ()) 374ref_t .append (p ) 375same = sum (int (r == int (t ))for r ,t in zip (ref_t ,toks )) 376agree += same 377total += T 378line += "; drafts engine %s ref %s" % (list (map (int ,toks )),ref_t ) 379line ,flush = True ) 380done += 1 381if done >= a .rounds : 382break 383"checked %d rounds: worst hidden rel err %.4f, worst conf diff %.4f%s" % ( 384done ,worst_x ,worst_c , (", drafts agree %d/%d" % (agree ,total ))if head is not None else "" )) 385return 0 386 387 388if __name__ == "__main__" : 389sys .exit (main ())