okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0f1e5e4cb
main
1"""A plain-torch port of the DFlash2 drafter (z-lab/dflash model.py, DFlash2DraftModel) for the offline acceptance experiment. 2 3Everything is fp32 on the CPU. The target's embedding table and LM head are the dequantized tensors of OUR GGUF (IQ4_XS embedding, 4Q6_K head), the context features are the hidden states dumped by the engine's STRATA_TAP_FILE hook. 5""" 6import json ,struct ,sys 7import numpy as np 8import torch 9import torch .nn .functional as F 10from safetensors import safe_open 11 12import os 13sys .path .insert (0 ,os .path .join (os .path .dirname (os .path .abspath (__file__ )),".." )) 14from _paths import gguf_lib 15gguf = gguf_lib () 16dequantize = gguf .quants .dequantize 17 18 19def rms (x ,w ,eps = 1e-6 ): 20v = x .pow (2 ).mean (- 1 ,keepdim = True ) 21return (x * torch .rsqrt (v + eps ))* w 22 23 24def rotate_half (x ): 25h = x .shape [- 1 ]// 2 26return torch .cat ((- x [...,h :],x [..., :h ]),dim =- 1 ) 27 28 29def load_dequant (path ,rows ,cols ,qtype ): 30raw = np .fromfile (path ,dtype = np .uint8 ) 31bs ,ts = gguf .GGML_QUANT_SIZES [qtype ] 32raw = raw .reshape (rows ,cols // bs * ts ) 33return torch .from_numpy (dequantize (raw ,qtype ).astype (np .float32 ).reshape (rows ,cols )) 34 35 36class Drafter : 37def __init__ (self ,st_path ,cfg_path ,embed ,head ,threads = 6 ): 38torch .set_num_threads (threads ) 39cfg = json .load (open (cfg_path )) 40dc = cfg ["dflash_config" ] 41self .H = cfg ["hidden_size" ] 42self .L = cfg ["num_hidden_layers" ] 43self .NH = cfg ["num_attention_heads" ] 44self .NKV = cfg ["num_key_value_heads" ] 45self .HD = cfg ["head_dim" ] 46self .win = cfg ["sliding_window" ] 47self .theta = cfg ["rope_parameters" ]["rope_theta" ] 48self .eps = cfg ["rms_norm_eps" ] 49self .gs = dc ["conv_group_size" ] 50self .ks = dc ["conv_kernel_size" ] 51self .mask_id = dc ["mask_token_id" ] 52self .top_k = dc ["selector_top_k" ] 53self .taps = dc ["target_layer_ids" ] 54self .embed = embed 55self .head = head 56self .w = {} 57with safe_open (st_path ,"pt" )as f : 58for k in f .keys (): 59t = f .get_tensor (k ) 60# the two codebooks stay bf16 (only gathered rows are used); everything else fp32 61self .w [k ]= t if "codebook" in k else t .float () 62self .inv_freq = 1.0 / (self .theta ** (torch .arange (0 ,self .HD ,2 ,dtype = torch .float32 )/ self .HD )) 63self .Kc = None 64self .fast_head = False 65self .head_bf16 = None 66 67def enable_fast_head (self ): 68self .head_bf16 = self .head .to (torch .bfloat16 ) 69self .fast_head = True 70 71def cos_sin (self ,pos ): 72fr = pos .float ()[:,None ]* self .inv_freq [None , :] 73emb = torch .cat ([fr ,fr ],dim =- 1 ) 74return emb .cos (),emb .sin () 75 76# ---- context: fc + hidden_norm over the tapped features, then every layer's K (norm + rope) and V 77def set_context (self ,feats ): 78"""feats: [n, taps*H] float32, row j = the features of position j.""" 79w = self .w 80h = rms (feats @w ["fc.weight" ].T ,w ["hidden_norm.weight" ],self .eps ) 81n = h .shape [0 ] 82cos ,sin = self .cos_sin (torch .arange (n )) 83self .Kc ,self .Vc = [], [] 84for l in range (self .L ): 85p = "layers.%d.self_attn." % l 86k = (h @w [p + "k_proj.weight" ].T ).view (n ,self .NKV ,self .HD ) 87v = (h @w [p + "v_proj.weight" ].T ).view (n ,self .NKV ,self .HD ) 88k = rms (k ,w [p + "k_norm.weight" ],self .eps ) 89k = k * cos [:,None , :]+ rotate_half (k )* sin [:,None , :] 90self .Kc .append (k .permute (1 ,0 ,2 ).contiguous ())# [NKV, n, HD] 91self .Vc .append (v .permute (1 ,0 ,2 ).contiguous ()) 92 93def conv (self ,x ,dyn ,base ): 94"""_grouped_dynamic_convolve over a block x [b, H]; dyn [b, ks, groups]; base [ks, H].""" 95b ,H = x .shape 96groups = H // self .gs 97blocks = x .view (b ,groups ,self .gs ) 98out = torch .zeros_like (blocks ) 99for o in range (base .shape [0 ]): 100vals = blocks if o == 0 else F .pad (blocks [:- o ], (0 ,0 ,0 ,0 ,o ,0 )) 101kern = base [o ].float ().view (1 ,groups ,self .gs ) 102out = out + kern * vals 103out = out + dyn [:,o , :,None ]* vals 104return out .view (b ,H ) 105 106def prepare (self ,x ,p ): 107w = self .w 108groups = self .H // self .gs 109dyn = (x @w [p + "kernel_projection.weight" ].T ).view (x .shape [0 ],2 ,self .ks ,groups ) 110return self .conv (x ,dyn [:,0 ],w [p + "base_kernel" ][0 ]),dyn [:,1 ] 111 112def finish (self ,x ,dyn ,p ): 113return self .conv (x ,dyn ,self .w [p + "base_kernel" ][1 ]) 114 115# ---- one block: anchor token at position s (s >= 1), block size b; returns the drafted path (b-1 tokens), the candidate lists 116def draft (self ,s ,anchor ,b ,greedy = True ): 117w = self .w 118H ,NH ,NKV ,HD = self .H ,self .NH ,self .NKV ,self .HD 119ids = torch .tensor ([anchor ]+ [self .mask_id ]* (b - 1 )) 120h = self .embed [ids ]# [b, H] 121pos = torch .arange (s ,s + b ) 122cos ,sin = self .cos_sin (pos ) 123# keys: context positions max(0, s-win+1) .. s-1 (a block row i sees ctx j when s+i-j < win), then the block 124lo = max (0 ,s - self .win + 1 ) 125for l in range (self .L ): 126p = "layers.%d." % l 127r = h 128x = rms (h ,w [p + "input_layernorm.weight" ],self .eps ) 129x ,kdyn = self .prepare (x ,p + "attention_conv." ) 130q = (x @w [p + "self_attn.q_proj.weight" ].T ).view (b ,NH ,HD ) 131q = rms (q ,w [p + "self_attn.q_norm.weight" ],self .eps ) 132kn = rms ((x @w [p + "self_attn.k_proj.weight" ].T ).view (b ,NKV ,HD ),w [p + "self_attn.k_norm.weight" ],self .eps ) 133vn = (x @w [p + "self_attn.v_proj.weight" ].T ).view (b ,NKV ,HD ) 134q = q * cos [:,None , :]+ rotate_half (q )* sin [:,None , :] 135kn = kn * cos [:,None , :]+ rotate_half (kn )* sin [:,None , :] 136Kc = self .Kc [l ][:,lo :s , :]# [NKV, c, HD] 137Vc = self .Vc [l ][:,lo :s , :] 138K = torch .cat ([Kc ,kn .permute (1 ,0 ,2 )],dim = 1 )# [NKV, c+b, HD] 139V = torch .cat ([Vc ,vn .permute (1 ,0 ,2 )],dim = 1 ) 140c = Kc .shape [1 ] 141kpos = torch .cat ([torch .arange (lo ,s ),pos ]) 142vis = (pos [:,None ]- kpos [None , :]).abs ()< self .win # [b, c+b] 143rep = NH // NKV 144Kx = K .repeat_interleave (rep ,dim = 0 )# [NH, c+b, HD] 145Vx = V .repeat_interleave (rep ,dim = 0 ) 146sc = torch .einsum ("bhd,hkd->hbk" ,q ,Kx )* (HD ** - 0.5 ) 147sc = sc .masked_fill (~ vis [None ],float ("-inf" )) 148att = torch .softmax (sc ,dim =- 1 ) 149o = torch .einsum ("hbk,hkd->bhd" ,att ,Vx ).reshape (b ,NH * HD ) 150o = o @w [p + "self_attn.o_proj.weight" ].T 151o = self .finish (o ,kdyn ,p + "attention_conv." ) 152h = r + o 153r = h 154x = rms (h ,w [p + "post_attention_layernorm.weight" ],self .eps ) 155x ,mdyn = self .prepare (x ,p + "mlp_conv." ) 156m = (F .silu (x @w [p + "mlp.gate_proj.weight" ].T )* (x @w [p + "mlp.up_proj.weight" ].T )) @w [p + "mlp.down_proj.weight" ].T 157m = self .finish (m ,mdyn ,p + "mlp_conv." ) 158h = r + m 159self .last_all = rms (h ,w ["norm.weight" ],self .eps ) 160out = self .last_all [1 :]# rows 1..b-1 161if self .fast_head : 162# candidates from a bf16 pass over the table (7x faster on this CPU), then the exact fp32 logits of the 32 best decide the top 16 163lb = (out .to (torch .bfloat16 ) @self .head_bf16 .T ) 164c32 = torch .topk (lb ,32 ,dim =- 1 ,sorted = False ).indices # [b-1, 32] 165ex = torch .einsum ("rkh,rh->rk" ,self .head [c32 ],out )# [b-1, 32] exact 166unary ,j16 = torch .topk (ex ,self .top_k ,dim =- 1 ,sorted = False ) 167cand = c32 .gather (- 1 ,j16 ) 168logits = None 169else : 170logits = out @self .head .T # [b-1, V] 171unary ,cand = torch .topk (logits ,self .top_k ,dim =- 1 ,sorted = False ) 172hp = out @w ["candidate_selector.hidden_projection.weight" ].T # [b-1, rank] 173A = w ["candidate_selector.predecessor_codebook" ] 174B = w ["candidate_selector.successor_codebook" ] 175pred = anchor 176path ,probs = [], [] 177for i in range (b - 1 ): 178sc = unary [i ]+ (B [cand [i ]].float () @ (A [pred ].float ()* hp [i ])) 179j = int (torch .argmax (sc )) 180probs .append (float (torch .softmax (sc ,dim =- 1 )[j ]))# the selector's own probability of the pick (a confidence) 181pred = int (cand [i ][j ]) 182path .append (pred ) 183top1 = (cand .gather (- 1 ,unary .argmax (- 1 ,keepdim = True ))[:,0 ]if logits is None else logits .argmax (- 1 )).tolist () 184self .last_probs = probs 185return path ,top1 186 187 188def read_taps (path ): 189f = open (path ,"rb" ) 190magic ,ver ,N ,nt = struct .unpack ("<4i" ,f .read (16 )) 191assert magic == 0x50415453 and ver == 1 , (hex (magic ),ver ) 192layers = struct .unpack ("<%di" % nt ,f .read (4 * nt )) 193rec = 8 + 4 * nt * N 194data = f .read () 195n = len (data )// rec 196pos = np .empty (n ,np .int32 ) 197tok = np .empty (n ,np .int32 ) 198taps = np .empty ((n ,nt * N ),np .float32 ) 199for i in range (n ): 200o = i * rec 201pos [i ],tok [i ]= struct .unpack_from ("<2i" ,data ,o ) 202taps [i ]= np .frombuffer (data ,np .float32 ,nt * N ,o + 8 ) 203return layers ,pos ,tok ,taps