okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4cfeaa0f4
main
1"""tools/qwen35/parity.py - NEW-MODELS-PLAN.md T1's exit gate for Qwen3.6-35B-A3B: strata-q36ref against llama.cpp 2(tools/qwen35/q36_llama_dump.cpp) on the same GGUF, the same box and the same token ids. 3 4For each prompt (parity_prompts.json, ChatML with thinking off): llama.cpp tokenizes it and runs it (the reference 5ids, layer outputs and greedy tokens); strata-q36ref runs the same ids. Reported per prompt: the greedy tokens that 6agree (of --n), the first divergence with both engines' top-1/top-2 logit margins (a near tie is a margin < 0.05), and 7the per-layer hidden-state error max over positions of ||strata - llama|| / ||llama||. 8 9python tools/qwen35/parity.py --ref BIN --dump BIN --model GGUF --out DIR [--n 64] [--ngl 99] [--lock "flock ..."] 10""" 11from __future__import annotations 12 13import argparse 14import json 15import shlex 16import subprocess 17import sys 18from pathlib import Path 19 20import numpy as np 21 22HERE = Path (__file__ ).resolve ().parent 23TEMPLATE = "<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n" 24N_EMBD ,N_LAYER = 2048 ,40 25EOS = 248046 # <|im_end|> 26 27 28def run (cmd :list [str ],lock :str ,log :Path )-> str : 29full = shlex .split (lock )+ cmd if lock else cmd 30r = subprocess .run (full ,capture_output = True ,text = True ,timeout = 1800 ) 31log .write_text (r .stdout + "\n--- stderr ---\n" + r .stderr ,encoding = "utf-8" ) 32if r .returncode != 0 : 33raise SystemExit (f" { cmd [ 0 ] } failed (rc { r . returncode } ), see { log } " ) 34return r .stdout 35 36 37def ids_of (out :str ,key :str )-> list [int ]: 38for line in out .splitlines (): 39if line .startswith (key + ":" ): 40return [int (x )for x in line .split (":" ,1 )[1 ].split ()] 41raise SystemExit (f"no ' { key } :' line" ) 42 43 44def main ()-> int : 45ap = argparse .ArgumentParser () 46ap .add_argument ("--ref" ,required = True ,help = "strata-q36ref" ) 47ap .add_argument ("--dump" ,required = True ,help = "q36_llama_dump" ) 48ap .add_argument ("--model" ,required = True ) 49ap .add_argument ("--out" ,required = True ) 50ap .add_argument ("--n" ,type = int ,default = 64 ) 51ap .add_argument ("--ngl" ,type = int ,default = 99 ,help = "llama.cpp's GPU layers (0 = its CPU backend)" ) 52ap .add_argument ("--lock" ,default = "" ,help = "a command prefix for the GPU runs (the box's flock)" ) 53ap .add_argument ("--prompts" ,default = str (HERE / "parity_prompts.json" )) 54ap .add_argument ("--skip-ref" ,action = "store_true" ,help = "reuse strata-q36ref's outputs in --out" ) 55ap .add_argument ("--past-eos" ,action = "store_true" ,help = "compare all --n tokens, not only up to the answer's end" ) 56a = ap .parse_args () 57out = Path (a .out ) 58out .mkdir (parents = True ,exist_ok = True ) 59prompts = json .loads (Path (a .prompts ).read_text (encoding = "utf-8" )) 60summary = [] 61for i ,p in enumerate (prompts ): 62tag = f"p { i :02d } " 63lo = run ([a .dump ,"--model" ,a .model ,"--prompt" ,TEMPLATE .format (p = p ),"--n" ,str (a .n ),"--ngl" ,str (a .ngl ), 64"--dump-layers" ,str (out / f" { tag } .llama.layers" ),"--dump-logits" ,str (out / f" { tag } .llama.logits" )], 65a .lock ,out / f" { tag } .llama.log" ) 66prompt_ids ,lgen = ids_of (lo ,"prompt" ),ids_of (lo ,"gen" ) 67if not a .skip_ref : 68so = run ([a .ref ,"--model" ,a .model ,"--tokens" ,"," .join (map (str ,prompt_ids )),"--n" ,str (a .n ), 69"--dump-layers" ,str (out / f" { tag } .strata.layers" ),"--dump-logits" ,str (out / f" { tag } .strata.logits" )], 70a .lock ,out / f" { tag } .strata.log" ) 71 (out / f" { tag } .strata.gen" ).write_text (so ,encoding = "utf-8" ) 72sgen = ids_of ((out / f" { tag } .strata.gen" ).read_text (encoding = "utf-8" ),"gen" ) 73# the answer ends at llama.cpp's first <|im_end|> (included); past it both engines run on in a context no chat 74# ever reaches, so the comparison stops there (--past-eos compares all --n tokens) 75upto = min (len (sgen ),len (lgen )) 76if not a .past_eos and EOS in lgen [:upto ]: 77upto = lgen .index (EOS )+ 1 78same = 0 79while same < upto and sgen [same ]== lgen [same ]: 80same += 1 81sl = np .fromfile (out / f" { tag } .strata.logits" ,dtype = np .float32 ).reshape (- 1 ,4 ) 82ll = np .fromfile (out / f" { tag } .llama.logits" ,dtype = np .float32 ).reshape (- 1 ,4 ) 83div = None 84if same < upto : 85div = {"step" :same ,"strata" : [int (sl [same ,0 ]),float (sl [same ,1 ]- sl [same ,3 ])], 86"llama" : [int (ll [same ,0 ]),float (ll [same ,1 ]- ll [same ,3 ])]} 87# the layer outputs up to the divergence (after it the two engines read different tokens) 88sL = np .fromfile (out / f" { tag } .strata.layers" ,dtype = np .float32 ).reshape (- 1 ,N_LAYER ,N_EMBD ) 89lL = np .fromfile (out / f" { tag } .llama.layers" ,dtype = np .float32 ).reshape (- 1 ,N_LAYER ,N_EMBD ) 90npos = min (len (sL ),len (lL ),len (prompt_ids )+ same ) 91ln = np .linalg .norm (lL [:npos ],axis = 2 ) 92err = np .linalg .norm (sL [:npos ]- lL [:npos ],axis = 2 )/ np .maximum (ln ,1e-30 )# [pos, layer] 93# llama.cpp keeps only the output rows of the last layer of a prompt batch: rows it did not compute are 0 94err = np .where (ln > 0 ,err ,np .nan ) 95per_layer = np .nanmax (err ,axis = 0 ) 96rec = {"prompt" :i ,"tokens" :len (prompt_ids ),"same" :same ,"of" :upto , 97"divergence" :div ,"max_rel_err" :float (np .nanmax (per_layer )),"worst_layer" :int (np .nanargmax (per_layer )), 98"median_rel_err" :float (np .nanmedian (err )),"per_layer_max" : [round (float (x ),5 )for x in per_layer ]} 99summary .append (rec ) 100f" { tag } : { same } / { rec [ 'of' ] } greedy tokens equal; layers max rel err { rec [ 'max_rel_err' ]:.4f } (layer " 101f" { rec [ 'worst_layer' ] } ), median { rec [ 'median_rel_err' ]:.5f } " + (f"; diverges at { div } " if div else "" ), 102flush = True ) 103 (out / "summary.json" ).write_text (json .dumps (summary ,indent = 1 ),encoding = "utf-8" ) 104full = sum (r ["same" ]== r ["of" ]for r in summary ) 105f"identical greedy answers (up to { a . n } tokens { '' if a . past_eos else ' or the end of the answer' } ): { full } of " 106f" { len ( summary ) } prompts; worst layer error " 107f" { max ( r [ 'max_rel_err' ] for r in summary ):.4f } " ) 108return 0 109 110 111if __name__ == "__main__" : 112sys .exit (main ())