okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2b36e8a02
main
1"""Real HTTP chat validation, with emitted token IDs captured at the engine boundary.""" 2import argparse ,json ,sys ,time ,urllib .error ,urllib .request 3from pathlib import Path 4ap = argparse .ArgumentParser (description = __doc__ ) 5for name in ['source' ,'config' ,'baseline' ,'candidate' ,'mtp' ,'output' ]: 6ap .add_argument ('--' + name ,type = Path ,required = True ) 7a = ap .parse_args () 8source = a .source .resolve () 9sys .path [:0 ]= [str (source ),str (source / 'tools' )] 10from serve .server import StrataEngine ,Service ,engine_args ,child_env ,serve 11from serve .frontend import ChatTemplate 12import strata_tokenizer as ST 13 14cfg = json .loads (a .config .read_text ()) 15cfg = {k :v for k ,v in cfg .items ()if k in ['args' ,'tokenizer' ,'gpu' ,'lib_dirs' ,'env' ]} 16args = list (cfg ['args' ]) 17for flag in ['--conversation-cache-spill-dir' ,'--conversation-cache-disk-mib' ,'--mtp' ]: 18if flag in args :i = args .index (flag );del args [i :i + 2 ] 19args = [a for a in args if a != '--conversation-cache-disk-only' ] 20tp = Path (cfg ['tokenizer' ]);vocab = json .loads ((tp / 'vocab.json' ).read_text ());tokens = [None ]* len (vocab ) 21for t ,i in vocab .items ():tokens [i ]= t 22tok = ST .Tokenizer (tokens ,(tp / 'merges.txt' ).read_text ().split ('\n' ),json .loads ((tp / 'token_type.json' ).read_text ())) 23template = ChatTemplate (tp / 'chat_template.jinja' ) 24rows = [] 25out = a .output ;out .mkdir (parents = True ,exist_ok = True ) 26class AuditEngine (StrataEngine ): 27def generate (self ,* a ,** kw ): 28self .emitted = [] 29for token in super ().generate (* a ,** kw ): 30if token is not None :self .emitted .append (token ) 31yield token 32 33for mode in ['baseline' ,'off' ,'mtp' ]: 34exe = (a .baseline if mode == 'baseline' else a .candidate ).resolve () 35current = list (args ) 36if mode == 'mtp' :current += ['--mtp' ,str (a .mtp .resolve ())];current [current .index ('--spec' )+ 1 ]= '4' 37local = dict (cfg ,args = current ,exe = str (exe ),cwd = str (source ),log = str (out / (mode + '.log' ))) 38engine = AuditEngine (local ['exe' ],engine_args (local ),cwd = local ['cwd' ],log = local ['log' ],env = child_env (local )) 39service = Service (engine ,tok ,template ,model_name = 'bias-validation' ) 40server = serve (service ,port = 0 ) 41def call (label ,prompt = 'Write the Chinese word for hello. Only the word.' ,expect = 200 ,** kw ): 42req = {'model' :'bias-validation' ,'messages' :[{'role' :'user' ,'content' :prompt }],'max_tokens' :8 ,'temperature' :0 ,'reasoning_effort' :'none' ,** kw } 43data = json .dumps (req ).encode ();started = time .perf_counter () 44http = urllib .request .Request (f'http://127.0.0.1: { server . server_address [ 1 ] } /v1/chat/completions' ,data = data ,headers = {'Content-Type' :'application/json' }) 45try : 46with urllib .request .urlopen (http ,timeout = 180 )as response :status = response .status ;raw = response .read ().decode () 47except urllib .error .HTTPError as e : 48with e :status = e .code ;raw = e .read ().decode () 49row = {'mode' :mode ,'label' :label ,'status' :status ,'seconds' :time .perf_counter ()- started ,'request_bytes' :len (data ), 50'token_ids' :list (engine .emitted )if status == 200 else [],'response' :raw ,'engine' :dict (engine .last )if status == 200 else {}} 51rows .append (row );(out / 'rows.json' ).write_text (json .dumps (rows ,indent = 2 ,ensure_ascii = False )) 52mode ,label ,status ,row ['token_ids' ],flush = True ) 53assert status == expect ,(label ,status ,raw ) 54return row 55try : 56first = call ('unchanged-greedy' ) 57sampled = call ('unchanged-sampled' ,prompt = 'Write one sentence about Python.' ,temperature = 0.7 ,top_k = 20 ,seed = 42 ) 58if mode == 'baseline' :continue 59assert engine .info .get ('logit_bias' )== 1 60banned = first ['token_ids' ][0 ] 61one = call ('ban-object' ,logit_bias = {str (banned ):- 100 }) 62two = call ('ban-pairs' ,logit_bias = [[banned ,False ]]) 63assert banned not in one ['token_ids' ]and banned not in two ['token_ids' ] 64assert one ['token_ids' ]== two ['token_ids' ] 65boosted = tok .encode (' banana' ,parse_special = False )[0 ] 66positive = call ('positive-bias' ,logit_bias = {str (boosted ):100 },max_tokens = 3 ) 67assert positive ['token_ids' ][0 ]== boosted 68# Changing requests must not inherit a prior mask, including after a rejected request. 69call ('invalid-id' ,expect = 400 ,logit_bias = {str (len (tokens )):1 },stream = True ) 70call ('invalid-value' ,expect = 400 ,logit_bias = {'0' :101 },stream = True ) 71again = call ('cleared-bias' ) 72assert again ['token_ids' ]== first ['token_ids' ] 73empty = call ('empty-bias' ,logit_bias = {}) 74assert empty ['token_ids' ]== first ['token_ids' ] 75large = set (range (103214 ));large .add (banned ) 76if len (large )< 103215 :large .add (103214 ) 77bulk = call ('103215-bans' ,logit_bias = [[i ,False ]for i in sorted (large )],max_tokens = 8 ) 78assert not set (bulk ['token_ids' ])& large 79streamed = call ('stream-ban' ,logit_bias = {str (banned ):- 100 },stream = True ) 80assert banned not in streamed ['token_ids' ] 81sampled_ban = call ('sampled-ban' ,logit_bias = {str (banned ):- 100 },temperature = 0.8 ,seed = 123 ) 82assert banned not in sampled_ban ['token_ids' ] 83finally : 84server .shutdown ();server .server_close ();engine .close () 85 86for label in ['unchanged-greedy' ,'unchanged-sampled' ]: 87before = next (x for x in rows if x ['mode' ]== 'baseline' and x ['label' ]== label ) 88after = next (x for x in rows if x ['mode' ]== 'off' and x ['label' ]== label ) 89assert before ['token_ids' ]== after ['token_ids' ],('default-output-changed' ,label ) 90(out / 'complete.json' ).write_text (json .dumps ({'status' :'passed' ,'requests' :len (rows ),'token_109266' :tok .decode ([109266 ]), 91'baseline' :str (a .baseline ),'candidate' :str (a .candidate ),'config' :str (a .config )},indent = 2 ,ensure_ascii = False ))