okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ef8071303
main
1#!/usr/bin/env python3 2"""Paired multiple-choice quality check through the chat API (no logprobs needed, so it runs on any 3OpenAI-compatible server): the first N HellaSwag and Winogrande items, reasoning off, greedy, answer = one letter. 4Run it on two engines serving the same weights, then compare with --compare A_DIR B_DIR. 5 6Usage: strata-quality-eval.py LABEL OUTDIR BASE_URL [--conc 1] [--hs 400] [--wg 400] 7strata-quality-eval.py --compare DIR_A DIR_B 8""" 9import argparse ,concurrent .futures as cf ,json ,math ,os ,re ,sys ,time ,urllib .request 10 11HS = 'hellaswag_val_full.txt' 12WG = 'winogrande-debiased-eval.csv' 13 14 15def hs_items (n ): 16L = open (HS ,encoding = 'utf-8' ).read ().split ('\n' ) 17out = [] 18for i in range (n ): 19ctx ,lab ,* ends = L [6 * i :6 * i + 6 ] 20q = (f'Which ending is the most plausible continuation of the text?\n\nText: { ctx } \n\n' + 21'\n' .join (f' { "ABCD" [ k ] } ) { e } ' for k ,e in enumerate (ends ))+ 22'\n\nAnswer with the letter only.' ) 23out .append ({'id' :f'hs { i } ' ,'prompt' :q ,'gold' :'ABCD' [int (lab )],'choices' :'ABCD' }) 24return out 25 26 27def wg_items (n ): 28import csv 29out = [] 30with open (WG ,encoding = 'utf-8' )as f : 31for i ,row in enumerate (csv .reader (f )): 32if i >= n :break 33_ ,sent ,o1 ,o2 ,ans = row 34q = (f'Which option correctly fills the blank (_)?\n\nSentence: { sent } \n\nA) { o1 } \nB) { o2 } \n\n' 35'Answer with the letter only.' ) 36out .append ({'id' :f'wg { i } ' ,'prompt' :q ,'gold' :'AB' [int (ans )- 1 ],'choices' :'AB' }) 37return out 38 39 40def ask (base ,it ): 41body = {'model' :MODEL ,'messages' : [{'role' :'user' ,'content' :it ['prompt' ]}],'max_tokens' :32 , 42'temperature' :0.0 ,'top_k' :1 ,'top_p' :1.0 ,'reasoning_effort' :'none' } 43req = urllib .request .Request (base + '/v1/chat/completions' ,data = json .dumps (body ).encode (), 44headers = {'Content-Type' :'application/json' }) 45for attempt in range (3 ): 46try : 47with urllib .request .urlopen (req ,timeout = 600 )as r : 48j = json .loads (r .read ()) 49break 50except Exception as e : 51if attempt == 2 :return {** it ,'answer' :None ,'error' :str (e )} 52time .sleep (5 ) 53msg = j ['choices' ][0 ]['message' ] 54text = (msg .get ('content' )or '' ).strip () 55m = re .search (r'\b([%s])\b' % it ['choices' ],text )or re .search (r'([%s])' % it ['choices' ],text ) 56if not m :# thinking leaked into reasoning_content only 57m = re .search (r'\b([%s])\b' % it ['choices' ], (msg .get ('reasoning_content' )or '' )[- 200 :]) 58return {'id' :it ['id' ],'gold' :it ['gold' ],'answer' :m .group (1 )if m else None ,'text' :text [:80 ]} 59 60 61def compare (da ,db ): 62A = {json .loads (l )['id' ]:json .loads (l )for l in open (os .path .join (da ,'answers.jsonl' ))} 63B = {json .loads (l )['id' ]:json .loads (l )for l in open (os .path .join (db ,'answers.jsonl' ))} 64for task in ('hs' ,'wg' ): 65ids = sorted (k for k in A if k .startswith (task )and k in B ) 66if not ids :continue 67ca = sum (A [k ]['answer' ]== A [k ]['gold' ]for k in ids );cb = sum (B [k ]['answer' ]== B [k ]['gold' ]for k in ids ) 68agree = sum (A [k ]['answer' ]== B [k ]['answer' ]for k in ids ) 69a_only = sum (A [k ]['answer' ]== A [k ]['gold' ]and B [k ]['answer' ]!= B [k ]['gold' ]for k in ids ) 70b_only = sum (B [k ]['answer' ]== B [k ]['gold' ]and A [k ]['answer' ]!= A [k ]['gold' ]for k in ids ) 71n = a_only + b_only # exact two-sided McNemar (binomial on the discordant pairs) 72k = min (a_only ,b_only ) 73p = min (1.0 ,2 * sum (math .comb (n ,i )for i in range (k + 1 ))/ 2 ** n )if n else 1.0 74inv_a = sum (A [k2 ]['answer' ]is None for k2 in ids );inv_b = sum (B [k2 ]['answer' ]is None for k2 in ids ) 75f' { task } : n= { len ( ids ) } { os . path . basename ( da ) } { 100 * ca / len ( ids ):.1f } % { os . path . basename ( db ) } ' 76f' { 100 * cb / len ( ids ):.1f } % diff { 100 * ( cb - ca ) / len ( ids ):+.1f } pp same answer { 100 * agree / len ( ids ):.1f } % ' 77f'right only A/B { a_only } / { b_only } McNemar p= { p :.2f } invalid { inv_a } / { inv_b } ' ) 78 79 80ap = argparse .ArgumentParser () 81ap .add_argument ('label' ,nargs = '?' );ap .add_argument ('outdir' ,nargs = '?' );ap .add_argument ('base' ,nargs = '?' ) 82ap .add_argument ('--conc' ,type = int ,default = 1 );ap .add_argument ('--hs' ,type = int ,default = 400 ) 83ap .add_argument ('--wg' ,type = int ,default = 400 );ap .add_argument ('--compare' ,nargs = 2 ) 84ap .add_argument ('--hellaswag' ,default = HS ) 85ap .add_argument ('--winogrande' ,default = WG ) 86ap .add_argument ('--model' ,default = 'default-big' ) 87a = ap .parse_args () 88HS ,WG ,MODEL = a .hellaswag ,a .winogrande ,a .model 89if a .compare : 90compare (* a .compare );sys .exit (0 ) 91OUT = os .path .join (a .outdir ,a .label );os .makedirs (OUT ,exist_ok = True ) 92items = hs_items (a .hs )+ wg_items (a .wg ) 93t0 = time .time () 94with cf .ThreadPoolExecutor (a .conc )as ex ,open (os .path .join (OUT ,'answers.jsonl' ),'w' )as f : 95for r in ex .map (lambda it :ask (a .base ,it ),items ): 96f .write (json .dumps (r )+ '\n' );f .flush () 97f' { a . label } : { len ( items ) } items in { time . time () - t0 :.0f } s' ,flush = True ) 98for task in ('hs' ,'wg' ): 99rows = [json .loads (l )for l in open (os .path .join (OUT ,'answers.jsonl' ))if json .loads (l )['id' ].startswith (task )] 100if rows : 101f' { a . label } { task } : acc { 100 * sum ( r [ "answer" ] == r [ "gold" ] for r in rows ) / len ( rows ):.1f } % ' 102f'(invalid { sum ( r [ "answer" ] is None for r in rows ) } )' ,flush = True )