File size: 13,683 Bytes
85097f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
"""盲答样本:每个子任务×组别抽 N 道,20 道一包交 Codex 只看题面作答,按 np_answers 判分(同 receipts)。
用法:sample <导出目录> <出目录> [--per-cell 20];run <出目录> [--workers 4] [--packs K];score <出目录>(写 cells.json);topup <导出目录> <出目录> [--target 80] [--seed 1]。
模型固定 gpt-6.1-sol、只读沙箱;推理档 --effort(默认 high;大批量刷题用 xhigh);单题一次调用 45 s 内回不来,所以 20 道一包。"""
import argparse
import collections
import json
import math
import random
import subprocess
import sys
import tempfile
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import prompts  # noqa: E402
import receipts  # noqa: E402
import runner  # noqa: E402

CODEX = [str(Path.home() / '.local/bin/codex'), 'exec', '-m', 'gpt-6.1-sol', '-c', 'model_reasoning_effort=high',
         '-s', 'read-only', '--skip-git-repo-check', '--ephemeral']
PACK, LIMIT = 20, 0.35   # 白皮书 151–153:盲答命中率不高于 35%
HEAD = ('下面有 {} 道题,各自独立。不提供录像,只凭题面作答;不确定也要给出你最可能的答案。\n'
        '每题按它自己的作答要求给出 answer 的值。最后只输出一行 JSON:{{"answers": [{{"id": 1, "answer": …}}, …]}},每题一项。\n')


def cell(item):
    return item['version_id'].split('/')[0], receipts.group_of(item)


def write(path, rows, mode='w'):
    with open(path, mode, encoding='utf-8') as fh:
        fh.writelines(json.dumps(r, ensure_ascii=False) + '\n' for r in rows)


def cells_of(items):
    by = collections.defaultdict(list)
    for item in items:
        by[cell(item)].append(item)
    return [by[k] for k in sorted(by, key=str)]


def sample_answers(items, truths, size, rng):
    """按私有答案比例取整配额,余数随机;每层至多加一,层内无放回。"""
    size = min(size, len(items))
    if size < 0:
        raise ValueError('sample size must be nonnegative')
    if not size:
        return []
    strata = collections.defaultdict(list)
    for item in items:
        key = json.dumps(truths[item['item_id']], sort_keys=True, ensure_ascii=False)
        strata[key].append(item)
    quotas, remainders = {}, {}
    for key, values in sorted(strata.items()):
        quotas[key], remainder = divmod(size * len(values), len(items))
        if remainder:
            remainders[key] = remainder
    for _ in range(size - sum(quotas.values())):
        key = rng.choices(list(remainders), weights=list(remainders.values()))[0]
        quotas[key] += 1
        del remainders[key]
    chosen = [item for key in quotas for item in rng.sample(strata[key], quotas[key])]
    rng.shuffle(chosen)
    return chosen


def sample(export, out, per_cell, seed=0):
    rng = random.Random(seed)
    truth_rows = runner.read_jsonl(Path(export) / 'truth.jsonl')
    truths = {t['item_id']: t['truth'] for t in truth_rows}
    keep = [i for c in cells_of(runner.read_jsonl(Path(export) / 'items.jsonl'))
            for i in sample_answers(c, truths, per_cell, rng)]
    ids, _ = {i['item_id'] for i in keep}, out.mkdir(parents=True, exist_ok=True)
    write(out / 'items.jsonl', keep)
    write(out / 'truth.jsonl', [t for t in truth_rows if t['item_id'] in ids])


def wilson(hits, n):
    """Wilson 双侧 95% 区间;未测时不假定命中率为零。"""
    if not n:
        return 0.0, 1.0
    z, p = 1.959963984540054, hits / n
    den = 1 + z * z / n
    center = (p + z * z / (2 * n)) / den
    half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / den
    return max(0.0, center - half), min(1.0, center + half)


def topup(export, out, target=80, seed=1):
    """score 后从同一导出补抽跨线格;保留原题顺序和所有响应。"""
    table = json.loads((out / 'cells.json').read_text())
    items = runner.read_jsonl(out / 'items.jsonl')
    counts = collections.Counter('%s | %s' % cell(i) for i in items)
    ids, keep, rng = {i['item_id'] for i in items}, [], random.Random(seed)
    truths = {t['item_id']: t['truth'] for t in runner.read_jsonl(Path(export) / 'truth.jsonl')}
    for c in cells_of(runner.read_jsonl(Path(export) / 'items.jsonl')):
        key = '%s | %s' % cell(c[0])
        if key not in table:
            continue
        v = table[key]
        n = v['n'] - v['not_run']
        low, high = wilson(round(v['blind_rate'] * n), n)
        if not low <= LIMIT <= high:
            continue
        pool = [i for i in c if i['item_id'] not in ids]
        extra = sample_answers(pool, truths, max(0, target - counts[key]), rng)
        keep.extend(extra)
        if extra:
            v['seed'] = seed
        print(f'{key}: +{len(extra)} n={counts[key] + len(extra)} seed={seed}')
    new_ids = {i['item_id'] for i in keep}
    truths = [t for t in runner.read_jsonl(Path(export) / 'truth.jsonl') if t['item_id'] in new_ids]
    if {t['item_id'] for t in truths} != new_ids:
        raise ValueError('补抽题缺少真值')
    write(out / 'items.jsonl', keep, 'a')
    write(out / 'truth.jsonl', truths, 'a')
    (out / 'cells.json').write_text(json.dumps(table, ensure_ascii=False, indent=1))


def ask(pack, timeout, effort='high'):
    t, prompt = time.time(), HEAD.format(len(pack)) + ''.join(
        f"\n【第 {n} 题】{i['question']['zh']}\n{prompts.instructions(i, 'zh')}\n" +
        ('世界状态证据:' + json.dumps(i['evidence'], ensure_ascii=False) + '\n' if 'evidence' in i else '')
        for n, i in enumerate(pack, 1))
    if any('evidence' in i for i in pack):
        if not all('evidence' in i for i in pack):
            raise ValueError('cannot mix blind and evidence items')
        prompt = prompt.replace('不提供录像,只凭题面作答', '不提供录像,根据题面和世界状态证据作答', 1)
    with tempfile.TemporaryDirectory() as tmp:   # 空目录里跑:只给题面,不给仓库和录像
        args = {'input': prompt} if 'evidence' in pack[0] else {}
        try:
            res = subprocess.run([c.replace('effort=high', f'effort={effort}') for c in CODEX] + ['-o', f'{tmp}/a.txt', '-' if args else prompt], cwd=tmp,
                                 capture_output=True, text=True, timeout=timeout, **args)
        except subprocess.TimeoutExpired:   # one slow pack is an ERROR row, not the end of the run
            res = subprocess.CompletedProcess([], 124, '', f'timeout after {timeout} s')
        text = Path(tmp, 'a.txt').read_text(encoding='utf-8') if Path(tmp, 'a.txt').exists() else ''
    try:
        answers = {int(a['id']): a.get('answer') for a in json.JSONDecoder().raw_decode(text[text.rindex('{"answers"'):])[0]['answers']}
    except (ValueError, KeyError, TypeError):
        answers = {}
    parsed = [prompts.parse(json.dumps({'answer': answers[n]}, ensure_ascii=False), i) if n in answers else None for n, i in enumerate(pack, 1)]
    return [{'item_id': i['item_id'], 'version_id': i['version_id'], 'status': 'OK' if p else 'ERROR', 'parsed': p,
             'text': json.dumps(answers.get(n), ensure_ascii=False), 'rc': res.returncode, 'pack_seconds': round(time.time() - t, 1),
             'stderr_tail': res.stderr[-300:] if res.returncode else ''} for n, (i, p) in enumerate(zip(pack, parsed), 1)]


def run(out, workers, packs, timeout, effort='high'):
    done = {i for i, r in runner.latest_responses(out / 'responses.jsonl').items() if r['status'] == 'OK'} if (out / 'responses.jsonl').exists() else set()
    items = runner.read_jsonl(out / 'items.jsonl')
    size = 1 if any('evidence' in i for i in items) else PACK
    chunks = [c[k:k + size] for c in cells_of([i for i in items if i['item_id'] not in done])
              for k in range(0, len(c), size)]
    todo = [c for c in chunks if not {i['item_id'] for i in c} <= done][:packs]
    (out / 'run.json').write_text(json.dumps({'schema': 'model-evaluation-run/1', 'items_path': str((out / 'items.jsonl').resolve()),
                                              'items_sha256': runner.file_sha256(out / 'items.jsonl'), 'endpoint': ' '.join(CODEX[1:]),
                                              'settings': {'text_only': True, 'pack': size}}, ensure_ascii=False, indent=1))
    with ThreadPoolExecutor(workers) as pool:
        for rows in pool.map(lambda c: ask(c, timeout, effort), todo):
            write(out / 'responses.jsonl', rows, 'a')
            print(rows[0]['version_id'], 'rc', rows[0]['rc'], 'OK', sum(r['status'] == 'OK' for r in rows), rows[0]['pack_seconds'], 's', flush=True)


def score(out):
    runner.score(out, out / 'truth.jsonl')
    items, cells = {i['item_id']: i for i in runner.read_jsonl(out / 'items.jsonl')}, collections.defaultdict(lambda: [0, 0, 0])
    replies = runner.latest_responses(out / 'responses.jsonl') if (out / 'responses.jsonl').exists() else {}
    for r in runner.read_jsonl(out / 'scores.jsonl'):
        c = cells['%s | %s' % cell(items[r['item_id']])]
        # 没答上(包超时、解析不了)是未测不是答错:算答错会压低命中率,让闸门假通过。
        missed = (replies.get(r['item_id']) or {}).get('status') != 'OK'
        c[0], c[1], c[2] = c[0] + 1, c[1] + (bool(r.get('passed')) and not missed), c[2] + missed
    rate = lambda n, h, nr: h / (n - nr) if n > nr else 0.0
    table = {k: {'n': n, 'not_run': nr, 'blind_rate': rate(n, h, nr), 'over': rate(n, h, nr) > LIMIT}
             for k, (n, h, nr) in sorted(cells.items())}
    previous = json.loads((out / 'cells.json').read_text()) if (out / 'cells.json').exists() else {}
    for k, (n, h, nr) in sorted(cells.items()):
        table[k]['ci_low'], table[k]['ci_high'] = wilson(h, n - nr)
        if 'seed' in previous.get(k, {}):
            table[k]['seed'] = previous[k]['seed']
    (out / 'cells.json').write_text(json.dumps(table, ensure_ascii=False, indent=1))
    for k, v in table.items():
        print(f"{k}: n={v['n']} blind={v['blind_rate']:.2f}{' 超' if v['over'] else ''} not_run={v['not_run']}")


def evidence_score(out, reviews):
    """Use the unchanged scorer; classify misses only with explicit per-item evidence review."""
    runner.score(out, out / 'truth.jsonl')
    items = runner.read_jsonl(out / 'items.jsonl')
    if not items or not all('evidence' in i for i in items):
        raise ValueError('evidence-score requires evidence items')
    scores = {r['item_id']: r for r in runner.read_jsonl(out / 'scores.jsonl')}
    replies = runner.latest_responses(out / 'responses.jsonl') if (out / 'responses.jsonl').exists() else {}
    review = {r['item_id']: r for r in runner.read_jsonl(reviews)} if reviews else {}
    categories = {'题面歧义': [], '真值或证据错': [], '证据不够': []}
    rows, pending, not_run, uncertain, execution_errors = [], [], [], [], []
    for item in items:
        iid = item['item_id']
        row = {'item_id': iid, 'version': item['version_id'], 'scaffold': item['tags']['scaffold'],
               'passed': bool(scores[iid].get('passed')), 'category': None}
        reply = replies.get(iid, {})
        if reply.get('status') != 'OK':
            row['passed'] = False
            not_run.append(iid)
        if not reply or reply.get('rc', 0) != 0:
            execution_errors.append(iid)
        if not row['passed']:
            r = review.get(iid, {})
            if r.get('category') not in {*categories, '不确定'} or not r.get('reason'):
                pending.append(iid)
            else:
                row.update(category=r['category'], reason=r['reason'])
                (uncertain if r['category'] == '不确定' else categories[r['category']]).append(iid)
        rows.append(row)
    report = {'items': len(items), 'passed': sum(r['passed'] for r in rows), 'not_run': not_run,
              'pending_review': pending, 'categories': categories, 'uncertain': uncertain,
              'execution_errors': execution_errors, 'rows': rows}
    (out / 'evidence-scores.json').write_text(json.dumps(report, ensure_ascii=False, indent=2))
    print(json.dumps({k: v for k, v in report.items() if k != 'rows'}, ensure_ascii=False))
    return bool(execution_errors or pending)


if __name__ == '__main__':
    ap = argparse.ArgumentParser()
    ap.add_argument('cmd', choices=['sample', 'run', 'score', 'topup', 'evidence-export', 'evidence-score']); ap.add_argument('paths', nargs='+')
    ap.add_argument('--per-cell', type=int, default=20); ap.add_argument('--workers', type=int, default=4)
    ap.add_argument('--packs', type=int); ap.add_argument('--timeout', type=int, default=540)
    ap.add_argument('--effort', choices=['high', 'xhigh'], default='high')
    ap.add_argument('--target', type=int, default=80); ap.add_argument('--seed', type=int, default=1)
    ap.add_argument('--segments', type=Path); ap.add_argument('--reviews', type=Path)
    a = ap.parse_args()
    if a.cmd == 'evidence-export':
        import evidence_export
        if not a.segments:
            ap.error('evidence-export requires --segments (JSON list of segment directories)')
        print(json.dumps(evidence_export.export(a.paths[:-1], json.loads(a.segments.read_text()), a.paths[-1], a.seed), ensure_ascii=False))
        sys.exit(0)
    if a.cmd == 'evidence-score':
        sys.exit(evidence_score(Path(a.paths[0]), a.reviews))
    {'sample': lambda: sample(a.paths[0], Path(a.paths[1]), a.per_cell), 'run': lambda: run(Path(a.paths[0]), a.workers, a.packs, a.timeout, a.effort),
     'topup': lambda: topup(a.paths[0], Path(a.paths[1]), a.target, a.seed), 'score': lambda: score(Path(a.paths[0]))}[a.cmd]()