okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
5993c50a5
main
1#!/usr/bin/env python3 2"""force_check.py: the token-forcing check (round 0217), after SpecPilot (arXiv 2611.02501, Li et al., Apache-2.0, "token forcing"). 3 4A candidate engine/build/setting is judged on a FIXED text: the engine scores prompt + continuation teacher-forced (every position's head logits come 5out of the verify windows with the head in FP32: STRATA_LOGPOS / STRATA_LOGPOS_TOPK, the prompt cache off), and the checker counts where the scorer's 6argmax is not the forced token. Nothing here depends on a drafter; it serves any class N change (Q5_0 experts, tree verify, a new kernel ...). 7 8force_check.py gen CFG SET.json --corpus held.jsonl [--kinds code,json] [--per-kind 4] [--offset 8] [--new 300] [--env K=V ...] 9one engine with CFG's normal decode flags; greedy continuations of the corpus prompts (rows with "ids") -> SET.json 10force_check.py score CFG SET.json OUT.tsv [--path decode|prompt] [--env K=V ...] [--arg "--flag v" ...] 11--path decode (default): one engine with CFG's own flags (drafter, spec windows, adaptive tiers ...), prompt cache off; every request decodes the 12forced continuation: the verify windows take the forced token in place of the argmax (STRATA_FOLLOW), so drafts are accepted when they match it, 13and the FP32 head logits of every valid row come out (STRATA_FOLLOW_LOGPOS, top-2). --path prompt: the whole text is read as a prompt through the 14windows (STRATA_LOGPOS, --short-read), no decode features. OUT.tsv.meta.json = per item line ranges. 15--env STRATA_FORCE_FAULT=7:0.3 is the test fault (adds 0.3 to every 7th token's logit in the scored rows). 16force_check.py check --stock A.tsv B.tsv [...] --cand C.tsv [--delta D] [--json out.json] 17the two rules of the paper against the stock arms (>= 2 stock arms: the noise): exit 0 pass, 1 reject, 2 inconclusive 18force_check.py selftest the statistics on synthetic rows (no engine) 19 20THE GATE FOR A CHANGE OF THE PROMPT ARITHMETIC (a prompt kernel, an expert format's prompt path; owner 11-10), a neutral writer: 21force_check.py cut IDS.txt CORPUS.jsonl [--sizes 4096,8192,20000] [--n 16] 22prompt cuts of one long id file (N windows per size at fixed offsets) -> a corpus 23force_check.py gen-neutral SET.json --corpus CORPUS.jsonl --writer /path/llama-server --writer-model SHARD1.gguf [--writer-args "-ngl 99 --cpu-moe"] 24[--writer-lib DIR ...] [--per-kind 16] [--new 128] 25the continuations written by a program that is NEITHER arm: llama.cpp's llama-server on the same GGUF, greedy, the prompt passed as token ids 26(the ids `score` feeds the engine), the generated ids read back (return_tokens) -> SET.json marked "writer": "neutral" 27force_check.py gate CFG SET.json OUTDIR --cand-env K=V [--cand-env ...] [--env K=V ...] [--arg "..."] 28scores the neutral set through stock twice (stockA, stockB) and the candidate twice (candA, candB), --path decode, then: 29PASS = each candidate arm against the two stock arms PASSES the rate rule and the event rule (check below); REJECT if any arm is rejected; 30otherwise INCONCLUSIVE. The reversed direction (each stock arm against the candidate arms) is reported in gate.json, not required. 31Exit 0 pass, 1 reject, 2 inconclusive. Size: 48 prompts (16 each at 4K / 8K / 20K) x 128 tokens = ~6,000 scored tokens an arm. 32Why (11-10, UD-IQ4_XS-v31 on an R9700 and an RTX A6000, IQ3_XXS on the R9700): with the STOCK engine writing the text, the 33rule measures the distance from the writer, not quality: (1) the FP16 prompt path, the reference of the KL gates, failed it on stock's 34text by more than the kernel under test (+1.66 points, 90% CI [+1.17, +2.15], against the kernel's +1.14 [+0.62, +1.69], 12 prompts); 35(2) with the CANDIDATE writing the text the stock engine failed by the same margin (+1.69 [+0.52, +2.93] and +1.56, REJECT, while the 36candidate passed against stock); (3) with llama.cpp writing, the candidate passed in every pairing (R9700 v31 -0.39 [-0.85, +0.07] and 37-0.33; R9700 IQ3_XXS -0.16 [-0.75, +0.42] twice; A6000 v31 48 prompts +0.21 [-0.05, +0.49] and +0.16), stock vs candidate reversed 38PASS or INCONCLUSIVE. Stock A and stock B are never byte-identical through the decode windows. 39The stock-written form (gen with the stock engine, score, check) stays as a DIAGNOSTIC: it measures how far a candidate's arithmetic is 40from the engine that wrote the text, and is not the gate for prompt-arithmetic changes. 41 42An "arm" = one scored TSV. Which engine produced the continuation and which scored it is the caller's choice: 43- a change of the prompt arithmetic (a prompt kernel, an expert format's prompt path): `gate` on a `gen-neutral` set (above); 44- a change of the decode path (tree verify, a drafter): `gen` with the candidate, `score` with the STOCK scorer (the paper's way). 45Stock arms = the same procedure with the stock build, at least twice (a second `gen`, or a second `score`). 46 47Rules (paper): mismatch = the scorer's argmax is not the forced token; margin = log p(argmax) - log p(forced token). 48rate rule : candidate mismatch rate within +0.5 points of stock at 95% (one-sided bootstrap over requests, paired on the same positions). 49REJECT if the 95% lower bound of (cand - stock) > 0.5 points; PASS if the 95% upper bound <= 0.5 points; else INCONCLUSIVE (more tokens). 50event rule: delta = the largest margin among stock's first departures per request, rounded UP to a multiple of 1/8; a large-margin event is a 51mismatch with margin > 2 delta. REJECT if the candidate has more events than stock by an exact one-sided binomial test (p < 0.05, 52exposure-weighted). (The paper also audits events stock reproduces on its own paths; that audit is not done here, events are counted raw.) 53""" 54import argparse ,json ,math ,os ,random ,signal ,subprocess ,sys ,pathlib 55 56SCORER_DROP_VALUE = {"--draft" ,"--draft-model" ,"--draft-fallback" ,"--mtp-draft-vocab" ,"--spec" ,"--draft-conf" ,"--draft-cap" ,"--mtp" ,"--spec-min-p" , 57"--prompt-cache" ,"--max-context" ,"--prefill" ,"--short-read" ,"--prompt-cache-every" ,"--conversation-cache-mib" ,"--suffix-draft" } 58SCORER_DROP_FLAG = {"--serve" ,"--vision" } 59 60 61def mem_available_gb (): 62try : 63for line in open ("/proc/meminfo" ): 64if line .startswith ("MemAvailable:" ): 65return int (line .split ()[1 ])/ 1048576 66except OSError : 67pass 68return float ("inf" ) 69 70 71# ------------------------------------------------------------------------------------------------ engine 72class Engine : 73def __init__ (self ,cfg ,args ,env_extra ,log ): 74env = dict (os .environ ) 75for k in list (env ): 76if k .startswith ("STRATA_" ): 77env .pop (k ) 78env .update (cfg .get ("env" , {})) 79env .update (env_extra ) 80if cfg .get ("lib_dirs" ): 81env ["LD_LIBRARY_PATH" ]= ":" .join (cfg ["lib_dirs" ]+ [env .get ("LD_LIBRARY_PATH" ,"" )]) 82self .errf = open (log ,"wb" ) 83self .p = subprocess .Popen ([cfg ["exe" ],"--serve" ]+ args ,stdin = subprocess .PIPE ,stdout = subprocess .PIPE ,stderr = self .errf ,text = True , 84cwd = cfg .get ("cwd" ),env = env ,bufsize = 1 ,start_new_session = True ) 85 86def ready (self ): 87for line in self .p .stdout : 88if line .startswith ("READY" ): 89return True 90return False 91 92def gen (self ,ids ,n ): 93self .p .stdin .write ("GEN %d %s\n" % (n ,"," .join (map (str ,ids )))) 94self .p .stdin .flush () 95toks = [] 96for line in self .p .stdout : 97if line .startswith ("T " ): 98toks .append (int (line .split ()[1 ])) 99elif line .startswith ("DONE" ): 100return toks ,line .split () 101elif line .startswith ("ERR" ): 102raise SystemExit ("engine: " + line .strip ()) 103raise SystemExit ("the engine closed its output" ) 104 105def close (self ): 106try : 107self .p .stdin .write ("QUIT\n" ) 108self .p .stdin .flush () 109self .p .wait (timeout = 300 ) 110except Exception : 111try : 112os .killpg (self .p .pid ,signal .SIGKILL )# only our own session 113except Exception : 114self .p .kill () 115self .errf .close () 116 117 118def fresh_profile (cfg ,args ,tag ): 119"""cfg "profile_src": a fresh copy of the expert profile per engine start (the engine may rewrite it) -> args with the copy's path""" 120src = cfg .get ("profile_src" ) 121if not src or "--expert-profile" not in args : 122return args 123import shutil 124dst = os .path .abspath (tag )+ ".profile.bin" 125shutil .copyfile (src ,dst ) 126args = list (args ) 127args [args .index ("--expert-profile" )+ 1 ]= dst 128return args 129 130 131def scorer_args (cfg ,total_tokens ,extra ): 132base ,out ,i = list (cfg ["args" ]), [],0 133while i < len (base ): 134x = base [i ] 135if x in SCORER_DROP_FLAG : 136i += 1 137elif x in SCORER_DROP_VALUE : 138i += 2 139else : 140out .append (x ) 141i += 1 142return out + ["--prompt-cache" ,"0" ,"--max-context" ,str (total_tokens + 512 ),"--short-read" ,str (total_tokens + 64 ),"--prefill" ,"512" ]+ extra 143 144 145def kv_env (lst ): 146d = {} 147for kv in lst or []: 148k ,_ ,v = kv .partition ("=" ) 149d [k ]= v 150return d 151 152 153# ------------------------------------------------------------------------------------------------ gen / score 154def cmd_gen (a ): 155cfg = json .load (open (a .config ,encoding = "utf-8-sig" )) 156rows = [json .loads (l )for l in open (a .corpus )if l .strip ()] 157rows = [r for r in rows if r .get ("split" ,"held" )== "held" ] 158kinds = a .kinds .split ("," )if a .kinds else sorted ({r ["kind" ]for r in rows }) 159sel = [] 160for k in kinds : 161sel += [r for r in rows if r ["kind" ]== k ][a .offset :a .offset + a .per_kind ] 162if mem_available_gb ()< a .min_free_gb : 163raise SystemExit ("only %.0f GB available (< %d): not starting an engine" % (mem_available_gb (),a .min_free_gb )) 164eng = Engine (cfg ,fresh_profile (cfg ,list (cfg ["args" ]),a .out ),kv_env (a .env ),a .out + ".engine.log" ) 165items = [] 166try : 167if not eng .ready (): 168raise SystemExit ("the engine ended before READY, see %s.engine.log" % a .out ) 169for r in sel : 170toks ,f = eng .gen (r ["ids" ],a .new ) 171items .append ({"id" :r ["id" ],"kind" :r ["kind" ],"prompt" :r ["ids" ],"cont" :toks }) 172"%s: %d prompt, %d forced tokens" % (r ["id" ],len (r ["ids" ]),len (toks )),flush = True ) 173finally : 174eng .close () 175json .dump ({"config" :a .config ,"env" :a .env or [],"items" :items },open (a .out ,"w" )) 176return 0 177 178 179def cmd_score (a ): 180cfg = json .load (open (a .config ,encoding = "utf-8-sig" )) 181st = json .load (open (a .set )) 182items = st ["items" ] 183total = max (len (i ["prompt" ])+ len (i ["cont" ])for i in items ) 184out = pathlib .Path (a .out ).resolve () 185if out .exists (): 186out .unlink () 187env = kv_env (a .env ) 188extra = [x for s in (a .arg or [])for x in s .split ()] 189if a .path == "decode" : 190# the real decode/verify windows (drafter, spec windows, adaptive tiers, whatever the config has) with the forced continuation standing in 191# for the argmax (STRATA_FOLLOW, one line per request in decode order); rows come from STRATA_FOLLOW_LOGPOS 192follow = str (out )+ ".follow.txt" 193with open (follow ,"w" )as ff : 194for it in items : 195ff .write ("," .join (map (str ,it ["cont" ]))+ chr (10 )) 196env .update ({"STRATA_FOLLOW" :follow ,"STRATA_FOLLOW_LOGPOS" :str (out ),"STRATA_LOGPOS_TOPK" :"2" }) 197args = list (cfg ["args" ]) 198if "--prompt-cache" in args : 199i = args .index ("--prompt-cache" ) 200del args [i :i + 2 ] 201args += ["--prompt-cache" ,"0" ]+ extra 202else : 203env .update ({"STRATA_LOGPOS" :str (out ),"STRATA_LOGPOS_TOPK" :"2" ,"STRATA_ROUTE_TAIL_SKIP" :env .get ("STRATA_ROUTE_TAIL_SKIP" ,"0" )}) 204args = scorer_args (cfg ,total ,extra ) 205if mem_available_gb ()< a .min_free_gb : 206raise SystemExit ("only %.0f GB available (< %d): not starting an engine" % (mem_available_gb (),a .min_free_gb )) 207args = fresh_profile (cfg ,args ,str (out )) 208eng = Engine (cfg ,args ,env ,str (out )+ ".engine.log" ) 209 210def nlines (): 211return sum (1 for _ in open (out ))if out .exists ()else 0 212meta = [] 213try : 214if not eng .ready (): 215raise SystemExit ("the engine ended before READY, see %s.engine.log" % out ) 216for it in items : 217ids = it ["prompt" ]+ it ["cont" ] 218n0 = nlines () 219if a .path == "decode" : 220toks ,f = eng .gen (it ["prompt" ],len (it ["cont" ])) 221if toks != it ["cont" ]: 222"%s: WARNING the engine emitted %d tokens, %d differ from the forced continuation" % ( 223it ["id" ],len (toks ),sum (1 for x ,y in zip (toks ,it ["cont" ])if x != y )+ abs (len (toks )- len (it ["cont" ]))),flush = True ) 224else : 225toks ,f = eng .gen (ids ,1 ) 226n1 = nlines () 227if n1 - n0 < len (it ["cont" ])// 2 : 228raise SystemExit ("%s: only %d positions scored (the prompt took the batched path? raise --short-read; decode path: STRATA_FOLLOW not in this build?)" % (it ["id" ],n1 - n0 )) 229meta .append ({"id" :it ["id" ],"kind" :it ["kind" ],"first_line" :n0 ,"end_line" :n1 ,"prompt_len" :len (it ["prompt" ]),"ids" :ids }) 230"%s: %d positions" % (it ["id" ],n1 - n0 ),flush = True ) 231finally : 232eng .close () 233json .dump ({"set" :a .set ,"config" :a .config ,"path" :a .path ,"env" :a .env or [],"args" :args ,"items" :meta },open (str (out )+ ".meta.json" ,"w" )) 234return 0 235 236 237# ------------------------------------------------------------------------------------------------ check 238def load_arm (tsv ): 239"""-> {request id: [(is_mismatch, margin, top2_margin), ...]} over the continuation positions""" 240meta = json .load (open (tsv + ".meta.json" )) 241lines = open (tsv ).read ().splitlines () 242out = {} 243for it in meta ["items" ]: 244ids ,P = it ["ids" ],it ["prompt_len" ] 245rows = [] 246for ln in lines [it ["first_line" ]:it ["end_line" ]]: 247f = ln .split ("\t" ) 248pos ,tgt = int (f [0 ]),int (f [1 ]) 249if pos < P - 1 or pos + 1 >= len (ids ): 250continue 251if ids [pos + 1 ]!= tgt : 252raise SystemExit ("%s: line for position %d scores token %d, the set has %d" % (it ["id" ],pos ,tgt ,ids [pos + 1 ])) 253lp_t ,am ,lp_am = float (f [2 ]),int (f [3 ]),float (f [4 ]) 254lp2 = None 255for x in f [8 :10 ]: 256i ,_ ,v = x .partition (":" ) 257if int (i )!= am : 258lp2 = float (v ) 259break 260rows .append ((am != tgt ,max (0.0 ,lp_am - lp_t ), (lp_am - lp2 )if lp2 is not None else float ("nan" ))) 261out [it ["id" ]]= rows 262return out 263 264 265def ceil8 (x ): 266return max (0.125 ,math .ceil (x * 8.0 - 1e-12 )/ 8.0 ) 267 268 269def binom_tail_ge (k ,n ,p ): 270return sum (math .comb (n ,i )* p ** i * (1 - p )** (n - i )for i in range (k ,n + 1 )) 271 272 273def check (stock ,cand ,delta = None ,seed = 1 ,boots = 4000 ): 274"""stock: list of arms, cand: one arm (each {request: rows}); the requests are the same. -> dict""" 275ids = [i for i in cand if all (i in s for s in stock )] 276# delta: largest margin at stock's first departure per request (every stock arm), rounded up to 1/8 277if delta is None : 278firsts = [] 279for s in stock : 280for i in ids : 281for mm ,mg ,_ in s [i ]: 282if mm : 283firsts .append (mg ) 284break 285delta = ceil8 (max (firsts ))if firsts else 0.125 286 287def counts (arm ): 288return [(len (arm [i ]),sum (1 for r in arm [i ]if r [0 ]),sum (1 for r in arm [i ]if r [0 ]and r [1 ]> 2 * delta ))for i in ids ] 289sc = [counts (s )for s in stock ] 290cc = counts (cand ) 291n_s = [sum (c [0 ]for c in a )for a in sc ] 292n_c = sum (c [0 ]for c in cc ) 293 294def rate (cs ): 295return 100.0 * sum (c [1 ]for c in cs )/ max (1 ,sum (c [0 ]for c in cs )) 296r_stock = [rate (a )for a in sc ] 297r_cand = rate (cc ) 298r_s = sum (r_stock )/ len (r_stock ) 299rng = random .Random (seed ) 300diffs = [] 301for _ in range (boots ): 302pick = [rng .randrange (len (ids ))for _ in ids ] 303dn = sum (cc [j ][0 ]for j in pick ) 304dc = 100.0 * sum (cc [j ][1 ]for j in pick )/ max (1 ,dn ) 305ds = sum (100.0 * sum (a [j ][1 ]for j in pick )/ max (1 ,sum (a [j ][0 ]for j in pick ))for a in sc )/ len (sc ) 306diffs .append (dc - ds ) 307diffs .sort () 308lo ,hi = diffs [int (0.05 * boots )],diffs [int (0.95 * boots )- 1 ] 309if lo > 0.5 : 310rate_v = "REJECT" 311elif hi <= 0.5 : 312rate_v = "PASS" 313else : 314rate_v = "INCONCLUSIVE" 315ev_c = sum (c [2 ]for c in cc ) 316ev_s = sum (sum (c [2 ]for c in a )for a in sc ) 317N_s = sum (n_s ) 318p0 = n_c / (n_c + N_s ) 319n = ev_c + ev_s 320p = binom_tail_ge (ev_c ,n ,p0 )if n > 0 else 1.0 321event_v = "REJECT" if p < 0.05 else "PASS" 322# stock-vs-stock spread (the noise): per-arm rates and large-margin events 323return {"requests" :len (ids ),"tokens_cand" :n_c ,"tokens_stock_arms" :n_s ,"delta" :delta ,"mismatch_rate_stock_arms_pct" : [round (x ,3 )for x in r_stock ], 324"mismatch_rate_cand_pct" :round (r_cand ,3 ),"diff_pts" :round (r_cand - r_s ,3 ),"diff_ci90_pts" : [round (lo ,3 ),round (hi ,3 )], 325"rate_rule" :rate_v ,"events_cand" :ev_c ,"events_stock_arms" : [sum (c [2 ]for c in a )for a in sc ],"events_p" :round (p ,5 ), 326"event_rule" :event_v ,"verdict" :"REJECT" if "REJECT" in (rate_v ,event_v )else ("PASS" if rate_v == "PASS" else "INCONCLUSIVE" )} 327 328 329def cmd_check (a ): 330stock = [load_arm (t )for t in a .stock ] 331cand = load_arm (a .cand ) 332if len (stock )< 2 : 333"warning: one stock arm only: the noise between stock runs is not measured" ,file = sys .stderr ) 334r = check (stock ,cand ,a .delta ) 335json .dumps (r ,indent = 1 )) 336if a .json : 337json .dump (r ,open (a .json ,"w" ),indent = 1 ) 338return {"PASS" :0 ,"REJECT" :1 ,"INCONCLUSIVE" :2 }[r ["verdict" ]] 339 340 341def cmd_selftest (a ): 342rng = random .Random (7 ) 343 344def arm (p_mis ,p_big ,nreq = 60 ,n = 300 ): 345d = {} 346for q in range (nreq ): 347rows = [] 348for _ in range (n ): 349if rng .random ()< p_mis : 350big = rng .random ()< p_big 351rows .append ((True ,rng .uniform (1.0 ,3.0 )if big else rng .uniform (0.0 ,0.4 ),1.0 )) 352else : 353rows .append ((False ,0.0 ,2.0 )) 354d ["r%d" % q ]= rows 355return d 356s1 ,s2 ,s3 = arm (0.007 ,0.0 ),arm (0.007 ,0.0 ),arm (0.007 ,0.0 ) 357ok = check ([s1 ,s2 ],s3 ) 358bad = check ([s1 ,s2 ],arm (0.02 ,0.0 )) 359ev = check ([s1 ,s2 ],arm (0.0075 ,0.5 )) 360"stock vs stock:" ,ok ["verdict" ],ok ["diff_pts" ],ok ["diff_ci90_pts" ],"events p" ,ok ["events_p" ]) 361"rate +1.3 pts:" ,bad ["verdict" ],bad ["diff_pts" ],bad ["diff_ci90_pts" ]) 362"more large-margin events:" ,ev ["verdict" ],ev ["events_cand" ],ev ["events_stock_arms" ],ev ["events_p" ]) 363assert ok ["verdict" ]!= "REJECT" and bad ["verdict" ]== "REJECT" and ev ["event_rule" ]== "REJECT" ,"selftest failed" 364"selftest ok" ) 365return 0 366 367 368# ------------------------------------------------------------------------------------------------ the neutral writer (the gate, owner 11-10) 369def cmd_cut (a ): 370"""prompt cuts of one long id file (comma-separated token ids): N windows of each size at fixed offsets (the cuts kl_ab.py and the 37111-10 gate runs used: offset = (i * 7919 + size) mod (len - size - 1)) -> a corpus for gen / gen-neutral""" 372big = [int (x )for x in open (a .ids ).read ().strip ().split ("," )if x .strip ()] 373n = 0 374with open (a .out ,"w" )as f : 375for size in [int (s )for s in a .sizes .split ("," )if s ]: 376if size >= len (big ): 377raise SystemExit ("cut: the id file has %d ids, a cut of %d does not fit" % (len (big ),size )) 378for i in range (a .n ): 379off = (i * 7919 + size )% max (1 ,len (big )- size - 1 ) 380f .write (json .dumps ({"id" :"p%d-%d" % (size ,i ),"kind" :"p%d" % size ,"split" :"held" ,"ids" :big [off :off + size ]})+ "\n" ) 381n += 1 382"cut: %d prompts -> %s" % (n ,a .out )) 383return 0 384 385 386def http_json (url ,obj = None ,timeout = 60.0 ): 387import urllib .request 388data = None if obj is None else json .dumps (obj ).encode () 389req = urllib .request .Request (url ,data = data ,headers = {"Content-Type" :"application/json" }if data else {}) 390return json .loads (urllib .request .urlopen (req ,timeout = timeout ).read ()) 391 392 393def cmd_gen_neutral (a ): 394"""greedy continuations written by a NEUTRAL program (neither arm): llama.cpp's llama-server on the same GGUF. The prompt goes in as token 395ids (the ids `score` feeds the engine), temperature 0 / top_k 1, no prompt cache, the generated ids back with return_tokens.""" 396import shlex ,time 397rows = [json .loads (l )for l in open (a .corpus )if l .strip ()] 398rows = [r for r in rows if r .get ("split" ,"held" )== "held" ] 399kinds = a .kinds .split ("," )if a .kinds else sorted ({r ["kind" ]for r in rows }) 400sel = [] 401for k in kinds : 402sel += [r for r in rows if r ["kind" ]== k ][a .offset :a .offset + a .per_kind ] 403def split (s ):# (Windows: shlex's non-POSIX mode keeps the quotes around a token) 404return [x [1 :- 1 ]if len (x )> 1 and x [0 ]== x [- 1 ]== '"' else x for x in shlex .split (s ,posix = os .name != "nt" )] 405cmd = split (a .writer )+ ["-m" ,a .writer_model ,"--port" ,str (a .writer_port ),"--host" ,"127.0.0.1" , 406"-c" ,str (a .writer_ctx ),"-np" ,"1" ]+ split (a .writer_args or "" ) 407env = dict (os .environ ) 408env .update (kv_env (a .writer_env )) 409if a .writer_lib : 410k = "PATH" if os .name == "nt" else "LD_LIBRARY_PATH" 411env [k ]= os .pathsep .join (a .writer_lib + [env .get (k ,"" )]) 412log = open (a .out + ".writer.log" ,"w" ) 413log .write ("# " + " " .join (cmd )+ "\n" ) 414log .flush () 415kw = {"creationflags" :0x00000200 }if os .name == "nt" else {"start_new_session" :True } 416p = subprocess .Popen (cmd ,stdout = log ,stderr = subprocess .STDOUT ,env = env ,** kw ) 417url = "http://127.0.0.1:%d" % a .writer_port 418items = [] 419try : 420t0 = time .time () 421while True : 422if p .poll ()is not None : 423raise SystemExit ("gen-neutral: the writer ended before it was ready, see %s.writer.log" % a .out ) 424try : 425if http_json (url + "/health" ,timeout = 5 ).get ("status" )== "ok" : 426break 427except Exception : 428pass 429if time .time ()- t0 > a .writer_wait : 430raise SystemExit ("gen-neutral: the writer was not ready after %d s" % a .writer_wait ) 431time .sleep (1.0 ) 432for r in sel : 433res = http_json (url + "/completion" , {"prompt" :r ["ids" ],"n_predict" :a .new ,"temperature" :0.0 ,"top_k" :1 ,"cache_prompt" :False , 434"return_tokens" :True ,"stream" :False },timeout = 3600 ) 435toks = [int (x )for x in res .get ("tokens" , [])] 436if not toks : 437raise SystemExit ("gen-neutral: %s: the writer returned no token ids (a llama-server without return_tokens?)" % r ["id" ]) 438items .append ({"id" :r ["id" ],"kind" :r ["kind" ],"prompt" :r ["ids" ],"cont" :toks }) 439"%s: %d prompt, %d forced tokens (writer)" % (r ["id" ],len (r ["ids" ]),len (toks )),flush = True ) 440finally : 441try : 442if os .name == "nt" : 443p .terminate () 444else : 445os .killpg (p .pid ,signal .SIGTERM ) 446p .wait (timeout = 60 ) 447except Exception : 448try : 449p .kill () 450except Exception : 451pass 452log .close () 453json .dump ({"config" :"writer: " + " " .join (cmd ),"writer" :"neutral" ,"env" : [],"items" :items },open (a .out ,"w" )) 454return 0 455 456 457def gate_report (stock ,cand ,delta = None ): 458"""stock, cand: two (or more) scored arms each, on a NEUTRAL writer's text. The gate: every candidate arm against the stock arms (check()); 459REJECT if any is REJECT, PASS if all PASS, else INCONCLUSIVE. The reversed direction (every stock arm against the candidate arms) is 460reported beside it, not required.""" 461fwd = [check (stock ,c ,delta )for c in cand ] 462rev = [check (cand ,s ,delta )for s in stock ] 463vs = [r ["verdict" ]for r in fwd ] 464verdict = "REJECT" if "REJECT" in vs else ("PASS" if all (v == "PASS" for v in vs )else "INCONCLUSIVE" ) 465return {"verdict" :verdict ,"cand_vs_stock" :fwd ,"stock_vs_cand_reported" :rev } 466 467 468def cmd_gate (a ): 469st = json .load (open (a .set )) 470if st .get ("writer" )!= "neutral" and not a .allow_engine_writer : 471raise SystemExit ("gate: %s was not written by gen-neutral; the gate needs a neutral writer's text (an engine-written set measures the " 472"distance from that engine: use score + check as a diagnostic, or --allow-engine-writer)" % a .set ) 473os .makedirs (a .outdir ,exist_ok = True ) 474arms = {"stockA" :a .env or [],"stockB" :a .env or [],"candA" : (a .env or [])+ a .cand_env ,"candB" : (a .env or [])+ a .cand_env } 475for name ,env in arms .items (): 476out = os .path .join (a .outdir ,name + ".tsv" ) 477if os .path .exists (out )and os .path .exists (out + ".meta.json" ): 478"%s: kept (%s exists)" % (name ,out ),flush = True ) 479continue 480cmd_score (argparse .Namespace (config = a .config ,set = a .set ,out = out ,path = a .path ,env = env ,arg = a .arg ,min_free_gb = a .min_free_gb )) 481load = lambda n :load_arm (os .path .join (a .outdir ,n + ".tsv" )) 482r = gate_report ([load ("stockA" ),load ("stockB" )], [load ("candA" ),load ("candB" )],a .delta ) 483json .dumps (r ,indent = 1 )) 484json .dump (r ,open (os .path .join (a .outdir ,"gate.json" ),"w" ),indent = 1 ) 485return {"PASS" :0 ,"REJECT" :1 ,"INCONCLUSIVE" :2 }[r ["verdict" ]] 486 487 488def main (): 489ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 490sp = ap .add_subparsers (dest = "cmd" ,required = True ) 491g = sp .add_parser ("gen" );g .add_argument ("config" );g .add_argument ("out" );g .add_argument ("--corpus" ,required = True ) 492g .add_argument ("--kinds" ,default = "" );g .add_argument ("--per-kind" ,type = int ,default = 4 );g .add_argument ("--offset" ,type = int ,default = 8 ) 493g .add_argument ("--new" ,type = int ,default = 300 );g .add_argument ("--env" ,action = "append" );g .add_argument ("--min-free-gb" ,type = int ,default = 20 ) 494s = sp .add_parser ("score" );s .add_argument ("config" );s .add_argument ("set" );s .add_argument ("out" ) 495s .add_argument ("--path" ,choices = ["decode" ,"prompt" ],default = "decode" ,help = "decode: the real verify windows with the forced tokens (STRATA_FOLLOW); prompt: the text read as a prompt (STRATA_LOGPOS)" ) 496s .add_argument ("--env" ,action = "append" );s .add_argument ("--arg" ,action = "append" );s .add_argument ("--min-free-gb" ,type = int ,default = 20 ) 497c = sp .add_parser ("check" );c .add_argument ("--stock" ,nargs = "+" ,required = True );c .add_argument ("--cand" ,required = True ) 498c .add_argument ("--delta" ,type = float );c .add_argument ("--json" ) 499sp .add_parser ("selftest" ) 500u = sp .add_parser ("cut" );u .add_argument ("ids" );u .add_argument ("out" );u .add_argument ("--sizes" ,default = "4096,8192,20000" ) 501u .add_argument ("--n" ,type = int ,default = 16 ) 502w = sp .add_parser ("gen-neutral" );w .add_argument ("out" );w .add_argument ("--corpus" ,required = True ) 503w .add_argument ("--writer" ,required = True ,help = "the writer's command line, e.g. /path/llama-server (its -m/--port/--host/-c/-np are added)" ) 504w .add_argument ("--writer-model" ,required = True ,help = "the GGUF the engine reads (shard 1 of a split set)" ) 505w .add_argument ("--writer-args" ,default = "" ,help = "more writer arguments, e.g. \"-ngl 99 --cpu-moe -fa on\"" ) 506w .add_argument ("--writer-env" ,action = "append" );w .add_argument ("--writer-lib" ,action = "append" ,default = []) 507w .add_argument ("--writer-port" ,type = int ,default = 18471 );w .add_argument ("--writer-ctx" ,type = int ,default = 32768 ) 508w .add_argument ("--writer-wait" ,type = int ,default = 900 ) 509w .add_argument ("--kinds" ,default = "" );w .add_argument ("--per-kind" ,type = int ,default = 16 );w .add_argument ("--offset" ,type = int ,default = 0 ) 510w .add_argument ("--new" ,type = int ,default = 128 ) 511t = sp .add_parser ("gate" );t .add_argument ("config" );t .add_argument ("set" );t .add_argument ("outdir" ) 512t .add_argument ("--cand-env" ,action = "append" ,required = True ,help = "the candidate's setting(s), K=V" ) 513t .add_argument ("--env" ,action = "append" ,help = "settings of both arms" );t .add_argument ("--arg" ,action = "append" ) 514t .add_argument ("--path" ,choices = ["decode" ,"prompt" ],default = "decode" );t .add_argument ("--delta" ,type = float ) 515t .add_argument ("--min-free-gb" ,type = int ,default = 20 );t .add_argument ("--allow-engine-writer" ,action = "store_true" ) 516a = ap .parse_args () 517return {"gen" :cmd_gen ,"score" :cmd_score ,"check" :cmd_check ,"selftest" :cmd_selftest ,"cut" :cmd_cut ,"gen-neutral" :cmd_gen_neutral , 518"gate" :cmd_gate }[a .cmd ](a ) 519 520 521if __name__ == "__main__" : 522sys .exit (main ())