okami.mom/strata

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

Niko1221Merge f-141-fixb: Python, docs and bench fixes and portsef8071303

main
5.3 KiB102 linesraw
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]
7       strata-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):
16    L = open(HS, encoding='utf-8').read().split('\n')
17    out = []
18    for i in range(n):
19        ctx, lab, *ends = L[6 * i:6 * i + 6]
20        q = (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.')
23        out.append({'id': f'hs{i}', 'prompt': q, 'gold': 'ABCD'[int(lab)], 'choices': 'ABCD'})
24    return out
25
26
27def wg_items(n):
28    import csv
29    out = []
30    with open(WG, encoding='utf-8') as f:
31        for i, row in enumerate(csv.reader(f)):
32            if i >= n: break
33            _, sent, o1, o2, ans = row
34            q = (f'Which option correctly fills the blank (_)?\n\nSentence: {sent}\n\nA) {o1}\nB) {o2}\n\n'
35                 'Answer with the letter only.')
36            out.append({'id': f'wg{i}', 'prompt': q, 'gold': 'AB'[int(ans) - 1], 'choices': 'AB'})
37    return out
38
39
40def ask(base, it):
41    body = {'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'}
43    req = urllib.request.Request(base + '/v1/chat/completions', data=json.dumps(body).encode(),
44                                 headers={'Content-Type': 'application/json'})
45    for attempt in range(3):
46        try:
47            with urllib.request.urlopen(req, timeout=600) as r:
48                j = json.loads(r.read())
49            break
50        except Exception as e:
51            if attempt == 2: return {**it, 'answer': None, 'error': str(e)}
52            time.sleep(5)
53    msg = j['choices'][0]['message']
54    text = (msg.get('content') or '').strip()
55    m = re.search(r'\b([%s])\b' % it['choices'], text) or re.search(r'([%s])' % it['choices'], text)
56    if not m:   # thinking leaked into reasoning_content only
57        m = re.search(r'\b([%s])\b' % it['choices'], (msg.get('reasoning_content') or '')[-200:])
58    return {'id': it['id'], 'gold': it['gold'], 'answer': m.group(1) if m else None, 'text': text[:80]}
59
60
61def compare(da, db):
62    A = {json.loads(l)['id']: json.loads(l) for l in open(os.path.join(da, 'answers.jsonl'))}
63    B = {json.loads(l)['id']: json.loads(l) for l in open(os.path.join(db, 'answers.jsonl'))}
64    for task in ('hs', 'wg'):
65        ids = sorted(k for k in A if k.startswith(task) and k in B)
66        if not ids: continue
67        ca = sum(A[k]['answer'] == A[k]['gold'] for k in ids); cb = sum(B[k]['answer'] == B[k]['gold'] for k in ids)
68        agree = sum(A[k]['answer'] == B[k]['answer'] for k in ids)
69        a_only = sum(A[k]['answer'] == A[k]['gold'] and B[k]['answer'] != B[k]['gold'] for k in ids)
70        b_only = sum(B[k]['answer'] == B[k]['gold'] and A[k]['answer'] != A[k]['gold'] for k in ids)
71        n = a_only + b_only   # exact two-sided McNemar (binomial on the discordant pairs)
72        k = min(a_only, b_only)
73        p = min(1.0, 2 * sum(math.comb(n, i) for i in range(k + 1)) / 2 ** n) if n else 1.0
74        inv_a = sum(A[k2]['answer'] is None for k2 in ids); inv_b = sum(B[k2]['answer'] is None for k2 in ids)
75        print(f'{task}: n={len(ids)}  {os.path.basename(da)} {100*ca/len(ids):.1f}%  {os.path.basename(db)} '
76              f'{100*cb/len(ids):.1f}%  diff {100*(cb-ca)/len(ids):+.1f} pp  same answer {100*agree/len(ids):.1f}%  '
77              f'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:
90    compare(*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:
95    for r in ex.map(lambda it: ask(a.base, it), items):
96        f.write(json.dumps(r) + '\n'); f.flush()
97print(f'{a.label}: {len(items)} items in {time.time() - t0:.0f} s', flush=True)
98for task in ('hs', 'wg'):
99    rows = [json.loads(l) for l in open(os.path.join(OUT, 'answers.jsonl')) if json.loads(l)['id'].startswith(task)]
100    if rows:
101        print(f'{a.label} {task}: acc {100*sum(r["answer"] == r["gold"] for r in rows)/len(rows):.1f}% '
102              f'(invalid {sum(r["answer"] is None for r in rows)})', flush=True)