okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-clean-3 (321794636): docs and history (cleanup step 3, items 3.0-3.10); release manifest and capability table with checks, history/ with pointers, link check, tools/ split, bench index; owner OK'd the wording 11-082b36e8a02

main
5.1 KiB91 linesraw
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']:
6 ap.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']:
18 if 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):
27 def generate(self,*a,**kw):
28  self.emitted=[]
29  for token in super().generate(*a,**kw):
30   if token is not None:self.emitted.append(token)
31   yield token
32
33for mode in ['baseline','off','mtp']:
34 exe=(a.baseline if mode=='baseline' else a.candidate).resolve()
35 current=list(args)
36 if mode=='mtp':current+=['--mtp',str(a.mtp.resolve())];current[current.index('--spec')+1]='4'
37 local=dict(cfg,args=current,exe=str(exe),cwd=str(source),log=str(out/(mode+'.log')))
38 engine=AuditEngine(local['exe'],engine_args(local),cwd=local['cwd'],log=local['log'],env=child_env(local))
39 service=Service(engine,tok,template,model_name='bias-validation')
40 server=serve(service,port=0)
41 def call(label,prompt='Write the Chinese word for hello. Only the word.',expect=200,**kw):
42  req={'model':'bias-validation','messages':[{'role':'user','content':prompt}],'max_tokens':8,'temperature':0,'reasoning_effort':'none',**kw}
43  data=json.dumps(req).encode();started=time.perf_counter()
44  http=urllib.request.Request(f'http://127.0.0.1:{server.server_address[1]}/v1/chat/completions',data=data,headers={'Content-Type':'application/json'})
45  try:
46   with urllib.request.urlopen(http,timeout=180) as response:status=response.status;raw=response.read().decode()
47  except urllib.error.HTTPError as e:
48   with e:status=e.code;raw=e.read().decode()
49  row={'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 {}}
51  rows.append(row);(out/'rows.json').write_text(json.dumps(rows,indent=2,ensure_ascii=False))
52  print(mode,label,status,row['token_ids'],flush=True)
53  assert status==expect,(label,status,raw)
54  return row
55 try:
56  first=call('unchanged-greedy')
57  sampled=call('unchanged-sampled',prompt='Write one sentence about Python.',temperature=0.7,top_k=20,seed=42)
58  if mode=='baseline':continue
59  assert engine.info.get('logit_bias')==1
60  banned=first['token_ids'][0]
61  one=call('ban-object',logit_bias={str(banned):-100})
62  two=call('ban-pairs',logit_bias=[[banned,False]])
63  assert banned not in one['token_ids'] and banned not in two['token_ids']
64  assert one['token_ids']==two['token_ids']
65  boosted=tok.encode(' banana',parse_special=False)[0]
66  positive=call('positive-bias',logit_bias={str(boosted):100},max_tokens=3)
67  assert positive['token_ids'][0]==boosted
68  # Changing requests must not inherit a prior mask, including after a rejected request.
69  call('invalid-id',expect=400,logit_bias={str(len(tokens)):1},stream=True)
70  call('invalid-value',expect=400,logit_bias={'0':101},stream=True)
71  again=call('cleared-bias')
72  assert again['token_ids']==first['token_ids']
73  empty=call('empty-bias',logit_bias={})
74  assert empty['token_ids']==first['token_ids']
75  large=set(range(103214));large.add(banned)
76  if len(large)<103215:large.add(103214)
77  bulk=call('103215-bans',logit_bias=[[i,False] for i in sorted(large)],max_tokens=8)
78  assert not set(bulk['token_ids']) & large
79  streamed=call('stream-ban',logit_bias={str(banned):-100},stream=True)
80  assert banned not in streamed['token_ids']
81  sampled_ban=call('sampled-ban',logit_bias={str(banned):-100},temperature=0.8,seed=123)
82  assert banned not in sampled_ban['token_ids']
83 finally:
84  server.shutdown();server.server_close();engine.close()
85
86for label in ['unchanged-greedy','unchanged-sampled']:
87 before=next(x for x in rows if x['mode']=='baseline' and x['label']==label)
88 after=next(x for x in rows if x['mode']=='off' and x['label']==label)
89 assert 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))