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/ref_gguf.py - tools/ds4/ref.py's oracle over a GGUF (tools/ds4/pack_gguf.py's pack): the same forward, 4each weight dequantised in torch from the GGUF's own blocks (BF16, Q8_0, MXFP4, MXFP8) - a check of maya-ds4's GGUF 5path that shares none of its code. 6 7python tools/ds4/ref_gguf.py --pack <model>/maya-ds4 --ids 0,671,6102 [--dump out.npz] [--gen 8] 8 9The token ids come from the server's tokenizer (maya-ds4 --serve, or the engine's own --ids runs); --dump writes 10what tools/ds4/compare.py reads. 11""" 12from __future__import annotations 13 14import argparse 15import math 16import os 17import pathlib 18import struct 19import sys 20import time 21from types import SimpleNamespace 22 23import numpy as np 24import torch 25import torch .nn .functional as F 26 27HERE = pathlib .Path (__file__ ).resolve ().parent 28sys .path .insert (0 ,str (HERE )) 29import ref as R # noqa: E402 30 31BLOCK = {"Q8_0" :34 ,"MXFP4" :17 ,"MXFP8" :33 } 32E2M1 = torch .tensor ([0 ,1 ,2 ,3 ,4 ,6 ,8 ,12 ,0 ,- 1 ,- 2 ,- 3 ,- 4 ,- 6 ,- 8 ,- 12 ],dtype = torch .float32 ) 33 34 35class Pack : 36"""pack_gguf.py's tensors.txt over the GGUF's files (memory-mapped), and ds4.txt's geometry.""" 37 38def __init__ (self ,d :pathlib .Path ): 39self .kv = {} 40for line in (d / "ds4.txt" ).read_text ().splitlines (): 41k ,_ ,v = line .partition (" " ) 42self .kv [k ]= v 43model = pathlib .Path (self .kv ["model_dir" ]) 44self .mm ,self .t = {}, {} 45for line in (d / "tensors.txt" ).read_text ().splitlines (): 46f = line .split () 47if f [0 ]== "file" : 48self .mm [int (f [1 ])]= np .memmap (model / f [2 ],dtype = np .uint8 ,mode = "r" ) 49elif f [0 ]== "t" : 50self .t [f [1 ]]= (f [2 ],int (f [3 ]),int (f [4 ]),int (f [5 ]),tuple (int (x )for x in f [6 :])) 51self ._embed = None 52 53def has (self ,name ): 54return name in self .t 55 56def raw (self ,name )-> np .ndarray : 57dt ,fi ,off ,nb ,_ = self .t [name ] 58return self .mm [fi ][off :off + nb ] 59 60def num (self ,k ,d = 0.0 ): 61return float (self .kv .get (k ,d )) 62 63def ints (self ,k ): 64return [int (x )for x in self .kv .get (k ,"" ).split ("," )if x ] 65 66 67def dequant (p :Pack ,name :str ,dev )-> torch .Tensor : 68"""A tensor as F32 on dev, shaped as stored ([out][in] for a matrix).""" 69dt ,_ ,_ ,_ ,shape = p .t [name ] 70r = torch .from_numpy (np .array (p .raw (name ))).to (dev ) 71if dt == "F32" : 72v = r .view (torch .float32 ) 73elif dt == "F16" : 74v = r .view (torch .float16 ).float () 75elif dt == "BF16" : 76v = r .view (torch .bfloat16 ).float () 77elif dt == "Q8_0" : 78b = r .view (- 1 ,34 ) 79v = (b [:, :2 ].contiguous ().view (torch .float16 ).float ()* b [:,2 :].view (torch .int8 ).float ()).reshape (- 1 ) 80elif dt == "MXFP4" : 81b = r .view (- 1 ,17 ) 82s = torch .ldexp (torch .ones (1 ,device = dev ),b [:, :1 ].int ()- 128 )# 2^(e - 128) 83q = b [:,1 :].long () 84lut = E2M1 .to (dev ) 85v = (torch .cat ([lut [q & 15 ],lut [q >> 4 ]],1 )* s ).reshape (- 1 )# values 0..15, then 16..31 86elif dt == "MXFP8" : 87b = r .view (- 1 ,33 ) 88s = torch .ldexp (torch .ones (1 ,device = dev ),b [:, :1 ].int ()- 127 ) 89v = (b [:,1 :].contiguous ().view (torch .float8_e4m3fn ).float ()* s ).reshape (- 1 ) 90else :# the low-bit expert types (IQ2_XXS .. Q4_K): gguf-py's numpy dequantisers (ggml's dequantize_row_*) 91v = torch .from_numpy (gq_values (np .array (p .raw (name )),dt ,name )).to (dev ) 92return v .reshape (shape ) 93 94 95def gq_values (raw :np .ndarray ,dt :str ,name :str )-> np .ndarray : 96"""ggml blocks of type dt as F32 (flat) through gguf-py's dequantisers - the installed package, else a llama.cpp 97checkout's ($GGUF_PY, ~/llama.cpp/gguf-py).""" 98try : 99try : 100import gguf 101except ImportError : 102for d in (os .environ .get ("GGUF_PY" ,"" ),os .path .expanduser ("~/llama.cpp/gguf-py" )): 103if d and os .path .isdir (d ): 104sys .path .insert (0 ,d ) 105import gguf 106from gguf .quants import dequantize as gq_dequant 107qt = gguf .GGMLQuantizationType [dt ] 108except (ImportError ,KeyError ): 109raise SystemExit ("%s: dtype %s (no gguf-py with a dequantiser for it: GGUF_PY=<llama.cpp>/gguf-py)" % (name ,dt )) 110return np .ascontiguousarray (gq_dequant (raw ,qt ),dtype = np .float32 ).reshape (- 1 ) 111 112 113class Hasher : 114"""engram_hash.Hasher from the pack's engram.bin (the token map, multipliers, primes and offsets).""" 115 116def __init__ (self ,path :pathlib .Path ): 117b = path .read_bytes () 118vocab ,nl ,ngram ,heads ,hd ,pad = struct .unpack_from ("<6i" ,b ,4 ) 119cols = (ngram - 1 )* heads 120o = 28 121self .tm = np .frombuffer (b ,np .int32 ,vocab ,o ).astype (np .int64 ) 122o += 4 * vocab 123self .mult = np .frombuffer (b ,np .int64 ,nl * ngram ,o ).reshape (nl ,ngram ) 124o += 8 * nl * ngram 125self .primes = np .frombuffer (b ,np .int64 ,nl * cols ,o ).reshape (nl ,ngram - 1 ,heads ) 126o += 8 * nl * cols 127self .off = np .frombuffer (b ,np .int64 ,nl * cols ,o ).reshape (nl ,cols ) 128self .ngram ,self .pad ,self .hd = ngram ,pad ,hd 129 130def ids (self ,tokens )-> np .ndarray :# engram_hash.Hasher.ids 131c = self .tm [np .asarray (tokens ,dtype = np .int64 )] 132T = len (c ) 133pos = np .arange (T ) 134toks ,blocked = [],np .zeros (T ,dtype = bool ) 135for s in range (self .ngram ): 136src = c [np .clip (pos - s ,0 ,None )] 137blocked = blocked | (pos < s ) 138toks .append (np .where (blocked ,self .pad ,src )) 139toks = np .stack (toks ,axis =- 1 ) 140prod = toks [:,None , :]* self .mult [None ] 141rolling ,out = prod [...,0 ], [] 142for i in range (1 ,self .ngram ): 143rolling = np .bitwise_xor (rolling ,prod [...,i ]) 144out .append (rolling [...,None ]% self .primes [None , :,i - 1 ]) 145return np .concatenate (out ,axis =- 1 )+ self .off [None ] 146 147 148def q6k_rows (rows :np .ndarray ,name :str )-> np .ndarray : 149"""Engram rows of Q6_K superblocks as F32 (ggml's dequantize_row_q6_K, through gguf-py).""" 150return gq_values (rows .reshape (- 1 ),"Q6_K" ,name ) 151 152 153class RefGguf (R .Ref ): 154def __init__ (self ,pack :pathlib .Path ,dev :str = "cuda:0" ,max_seq :int = 8192 ): 155self .dir = pack 156self .st = p = Pack (pack ) 157g = p .num 158t = {k :int (g (k ))for k in ("hidden_size" ,"hc_mult" ,"num_hidden_layers" ,"candidate_source_layer_id" , 159"qk_rope_head_dim" ,"num_experts_per_tok" ,"sliding_window" ,"o_groups" , 160"num_attention_heads" ,"index_topk" ,"index_n_heads" ,"index_head_dim" ,"head_dim" , 161"candidate_topk_blocks" ,"candidate_block_size" )} 162t .update (hc_eps = g ("hc_eps" ),hc_sinkhorn_iters = int (g ("hc_sinkhorn_iters" )), 163rms_norm_eps = g ("rms_norm_eps" ),routed_scaling_factor = g ("routed_scaling_factor" ), 164swiglu_limit = g ("swiglu_limit" ),rope_theta = g ("rope_theta" ),compress_rope_theta = g ("compress_rope_theta" ), 165compress_ratios = p .ints ("compress_ratios" ),kv_source_layer_ids = p .ints ("kv_source_layer_ids" ), 166index_source_layer_ids = p .ints ("index_source_layer_ids" ), 167rope_scaling = {"factor" :g ("rope_scaling.factor" ),"beta_fast" :g ("rope_scaling.beta_fast" ), 168"beta_slow" :g ("rope_scaling.beta_slow" ), 169"original_max_position_embeddings" :int (g ("rope_scaling.original_max_position_embeddings" ))}) 170self .cfg = {"text_config" :t } 171self .t = t 172self .dev = dev 173self .dim ,self .hc = t ["hidden_size" ],t ["hc_mult" ] 174self .eps = t ["rms_norm_eps" ] 175self .nl = t ["num_hidden_layers" ] 176self .ratios = t ["compress_ratios" ] 177self .kv_src = set (t ["kv_source_layer_ids" ]) 178self .ix_src = set (t ["index_source_layer_ids" ]) 179self .cand_src = t ["candidate_source_layer_id" ] 180rs ,rd = t ["rope_scaling" ],t ["qk_rope_head_dim" ] 181self .fc_window = R .freqs_cis (rd ,max_seq ,0 ,t ["rope_theta" ],rs ["factor" ],rs ["beta_fast" ],rs ["beta_slow" ],dev ) 182self .fc_comp = R .freqs_cis (rd ,max_seq ,rs ["original_max_position_embeddings" ],t ["compress_rope_theta" ], 183rs ["factor" ],rs ["beta_fast" ],rs ["beta_slow" ],dev ) 184self .hasher = Hasher (pack / "engram.bin" ) 185self .lay = SimpleNamespace (layer_ids = tuple (p .ints ("engram_layer_ids" )),head_dim = self .hasher .hd ) 186self .timing = {} 187self ._embed = None 188 189def W (self ,prefix :str )-> torch .Tensor : 190return dequant (self .st ,prefix + ".weight" ,self .dev ) 191 192def V (self ,name :str )-> torch .Tensor : 193return dequant (self .st ,name ,self .dev ).float () 194 195def engram (self ,li ,x ,hash_ids ): 196P = "layers.%d.engram." % li 197T ,cols = hash_ids .shape 198hd = self .lay .head_dim 199dt = self .st .t [P + "embed.weight" ][0 ] 200rb = hd // 256 * 210 if dt == "Q6_K" else hd // 32 * 33 # (a row's bytes: Q6_K or MXFP8 blocks) 201tab = self .st .raw (P + "embed.weight" ).reshape (- 1 ,rb ) 202flat = hash_ids .reshape (- 1 ) 203order = np .argsort (flat ) 204rows = np .empty ((flat .size ,rb ),np .uint8 ) 205rows [order ]= tab [flat [order ]] 206if dt == "Q6_K" : 207e = torch .from_numpy (q6k_rows (rows ,P )).to (self .dev ).view (T ,cols * hd ) 208else : 209b = torch .from_numpy (rows ).to (self .dev ).view (- 1 ,33 ) 210s = torch .ldexp (torch .ones (1 ,device = self .dev ),b [:, :1 ].int ()- 127 ) 211e = (b [:,1 :].contiguous ().view (torch .float8_e4m3fn ).float ()* s ).view (T ,cols * hd ) 212e = e .to (torch .bfloat16 ).float () 213kv = e @self .W (P + "wkv" ).T 214d ,hc = self .dim ,self .hc 215key ,value = kv [:, :hc * d ].view (T ,hc ,d ),kv [:,hc * d :] 216w = self .V (P + "gate.weight" )# q_weight * k_weight (folded) 217h = x .float () 218rstd = torch .rsqrt (h .square ().mean (- 1 )+ self .eps )* torch .rsqrt (key .square ().mean (- 1 )+ self .eps ) 219dot = (h * w * key ).sum (- 1 )* rstd * d ** - 0.5 220gate = torch .sigmoid (torch .copysign (dot .abs ().clamp_min (1e-6 ).sqrt (),dot )) 221return h + gate .unsqueeze (- 1 )* value .unsqueeze (1 ) 222 223def moe (self ,li ,x ): 224t = self .t 225M = "layers.%d.ffn." % li 226T = x .shape [0 ] 227gw = self .V (M + "gate.weight" ) 228scores = F .softplus (x .float () @gw .T ).sqrt () 229idx = (scores + self .V (M + "gate.bias" )).topk (t ["num_experts_per_tok" ],dim =- 1 )[1 ] 230wts = scores .gather (1 ,idx ) 231wts = wts / (wts .sum (- 1 ,keepdim = True )+ 1e-20 )* t ["routed_scaling_factor" ] 232lim = t ["swiglu_limit" ] 233y = torch .zeros (T ,self .dim ,device = self .dev ) 234for e in torch .unique (idx ).tolist (): 235P = M + "experts.%d." % e 236rows ,slot = torch .where (idx == e ) 237xs = x [rows ] 238h = F .silu ((xs @self .W (P + "w1" ).T ).clamp (max = lim ))* (xs @self .W (P + "w3" ).T ).clamp (- lim ,lim ) 239y .index_add_ (0 ,rows , (h * wts [rows ,slot ,None ]) @self .W (P + "w2" ).T ) 240S = M + "shared_experts." 241h = F .silu ((x @self .W (S + "w1" ).T ).clamp (max = lim ))* (x @self .W (S + "w3" ).T ).clamp (- lim ,lim ) 242y += h @self .W (S + "w2" ).T 243self .last_route = (idx ,wts ) 244return y 245 246@ torch . inference_mode () 247def forward (self ,ids ,dump = None ): 248# ref.py's forward reads the embedding rows as BF16: a Q8_0 table is dequantised for the rows asked 249dt = self .st .t ["embed.weight" ][0 ] 250if dt != "BF16" : 251full = self .st .raw ("embed.weight" ).reshape (- 1 ,self .dim // 32 * 34 ) 252sel = torch .from_numpy (np .array (full [np .asarray (ids )])).to (self .dev ).view (- 1 ,34 ) 253v = (sel [:, :2 ].contiguous ().view (torch .float16 ).float ()* sel [:,2 :].view (torch .int8 ).float ()) 254rows = v .reshape (len (ids ),self .dim ).to (torch .bfloat16 ).view (torch .uint16 ).cpu ().numpy () 255raw0 = self .st .raw 256emb = np .zeros ((max (ids )+ 1 ,self .dim ),np .uint16 ) 257emb [np .asarray (ids )]= rows 258self .st .raw = lambda n ,e = emb ,r = raw0 :e .view (np .uint8 )if n == "embed.weight" else r (n ) 259try : 260return super ().forward (ids ,dump ) 261finally : 262self .st .raw = raw0 263return super ().forward (ids ,dump ) 264 265 266def main ()-> int : 267ap = argparse .ArgumentParser () 268ap .add_argument ("--pack" ,required = True ,help = "pack_gguf.py's pack (<model>/maya-ds4)" ) 269ap .add_argument ("--ids" ,required = True ,help = "comma-separated token ids" ) 270ap .add_argument ("--gen" ,type = int ,default = 0 ,help = "greedy tokens to append (a whole forward each)" ) 271ap .add_argument ("--dump" ,help = "write the per-layer residual streams, the logits and the ids (.npz)" ) 272ap .add_argument ("--no-hs" ,action = "store_true" ,help = "--dump without the per-layer residual streams" ) 273ap .add_argument ("--dev" ,default = "cuda:0" ) 274a = ap .parse_args () 275ids = [int (x )for x in a .ids .split ("," )] 276r = RefGguf (pathlib .Path (a .pack ).expanduser (),a .dev ) 277"tokens:" ,len (ids ),ids [:32 ],flush = True ) 278dump = []if a .dump and not a .no_hs else None 279t0 = time .time () 280logits = r .forward (ids ,dump ) 281"forward %.1fs" % (time .time ()- t0 ),flush = True ) 282lp = torch .log_softmax (logits .float (),- 1 ) 283if len (ids )> 1 : 284tgt = torch .tensor (ids [1 :],device = lp .device ) 285nll = - lp [:- 1 ].gather (1 ,tgt [:,None ]).squeeze (1 ) 286"ppl over %d tokens: %.4f" % (len (ids )- 1 ,math .exp (nll .mean ().item ()))) 287top = lp [- 1 ].topk (8 ) 288"next:" ,list (zip (top .indices .tolist (), [round (v ,3 )for v in top .values .tolist ()]))) 289if a .dump : 290np .savez (a .dump ,ids = np .array (ids ),logits = logits .cpu ().numpy (),hs = np .stack (dump )if dump else np .zeros (0 )) 291out = list (ids ) 292for _ in range (a .gen ): 293nxt = int (lp [- 1 ].argmax ()) 294out .append (nxt ) 295"gen ids:" ,out [len (ids ):],flush = True ) 296if nxt == 1 : 297break 298lp = torch .log_softmax (r .forward (out ).float (),- 1 ) 299return 0 300 301 302if __name__ == "__main__" : 303sys .exit (main ())