File size: 15,704 Bytes
7f9a652
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
"""Run a model over Lilambd Empire Eval prompts and write predictions.jsonl.



Standard library only. Examples:



  # build prompts on the fly from a QA folder, call Claude, score at the end

  ANTHROPIC_API_KEY=... python scripts/run_eval.py --qa data/dev --provider anthropic \

      --out results/sonnet/predictions.jsonl --score



  # any OpenAI-compatible server (vLLM, Ollama, OpenRouter, Together, OpenAI)

  python scripts/run_eval.py --qa data/dev --provider openai \

      --base-url http://localhost:8000/v1 --model my-model --out results/m/predictions.jsonl



  # prompts made by make_prompts.py

  python scripts/make_prompts.py --qa data/test --out prompts.jsonl

  python scripts/run_eval.py --prompts prompts.jsonl --provider anthropic --out preds.jsonl



  # sanity baselines (no network): oracle (dev only), null, random-guess

  python scripts/run_eval.py --qa data/dev --provider oracle --out /tmp/o.jsonl --score



Each output line: {"id", "answer", "raw", "latency_ms"}. Re-running with the same

--out resumes: ids already in the file are skipped. Failed calls are not written,

so a re-run retries them. Note score.py counts missing ids as wrong, so a --limit

or --sets run scored against the full --qa folder gives a low overall accuracy.

"""
import argparse, concurrent.futures, glob, json, os, random, re, subprocess, sys, threading, time
import urllib.error, urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from make_prompts import INSTR  # noqa: E402  same instruction text as make_prompts.py
from package import unflat  # noqa: E402  same answer decoding as score.py

ANTHROPIC_URL = 'https://api.anthropic.com/v1/messages'
ANTHROPIC_VERSION = '2023-06-01'
DEFAULT_MODELS = {'anthropic': 'claude-sonnet-5-5', 'openai': 'gpt-4o-mini'}
RETRY_STATUS = {408, 409, 425, 429, 500, 502, 503, 504, 529}


# ---------------------------------------------------------------- inputs

def qa_files(qa):
    return sorted(glob.glob(os.path.join(qa, '*.jsonl'))) if os.path.isdir(qa) else [qa]


def load_items(qa):
    """QA rows (decoded with package.unflat), with the file stem as `_set`."""
    out = []
    for fn in qa_files(qa):
        stem = os.path.splitext(os.path.basename(fn))[0]
        with open(fn, encoding='utf-8') as fh:
            lines = fh.readlines()
        for line in lines:
            if line.strip():
                it = unflat(json.loads(line))
                it['_set'] = stem
                out.append(it)
    return out


def build_prompt(it, context_hint=False):
    """Byte-for-byte the prompt make_prompts.py writes."""
    p = INSTR + '\n\n'
    if context_hint:
        p += f"Dataset: https://huggingface.co/datasets/{it['dataset']} (revision {it['revision']})\n"
    if it.get('answer_format'):
        p += f"Answer format: {it['answer_format']}\n"
    p += f"Question: {it['question']}"
    return p


def set_of_id(qid):
    return qid.rsplit('-', 1)[0]


def in_sets(qid, set_name, sets):
    if not sets:
        return True
    cands = {set_of_id(qid)}
    if set_name:
        cands.add(set_name)
    return any(c == s or c.endswith('-' + s) for c in cands for s in sets)


def load_done(path):
    done = set()
    if os.path.exists(path):
        with open(path, encoding='utf-8') as fh:
            lines = fh.readlines()
        for line in lines:
            try:
                done.add(json.loads(line)['id'])
            except (json.JSONDecodeError, KeyError, TypeError):
                pass  # e.g. a half-written last line after a crash
    return done


# ---------------------------------------------------------------- extraction

ANS_PREFIX = re.compile(r'^\s*(?:\*\*)?\s*(?:final\s+)?answer\s*(?:\*\*)?\s*[::]\s*(?:\*\*)?', re.I)


def extract_answer(raw):
    """Keep the last non-empty line and strip an 'Answer:' prefix.



    A reply that is valid JSON as a whole (e.g. a multi-line list) is kept whole.

    """
    if raw is None:
        return None
    s = str(raw).strip()
    s = re.sub(r'^```[\w-]*\s*|\s*```$', '', s).strip()
    try:
        v = json.loads(s)
        if isinstance(v, list):
            return s.replace('\n', ' ') if '\n' in s else s
    except (json.JSONDecodeError, ValueError):
        pass
    lines = [l for l in s.splitlines() if l.strip() and l.strip() != '```']
    if not lines:
        return ''
    last = ANS_PREFIX.sub('', lines[-1]).strip()
    last = re.sub(r'^\*\*(.*)\*\*$', r'\1', last).strip()
    return last


# ---------------------------------------------------------------- HTTP

class HTTPFail(Exception):
    pass


def post_json(url, headers, body, timeout, retries, backoff, log=None, _sleep=time.sleep):
    data = json.dumps(body).encode('utf-8')
    attempt = 0
    while True:
        req = urllib.request.Request(url, data=data, method='POST',
                                     headers={'content-type': 'application/json', **headers})
        try:
            with urllib.request.urlopen(req, timeout=timeout) as r:
                return json.loads(r.read().decode('utf-8'))
        except urllib.error.HTTPError as e:
            msg = ''
            try:
                msg = e.read().decode('utf-8', 'replace')[:500]
            except Exception:
                pass
            if e.code not in RETRY_STATUS or attempt >= retries:
                raise HTTPFail(f'HTTP {e.code}: {msg}') from None
            wait = None
            ra = e.headers.get('retry-after') if e.headers else None
            if ra:
                try:
                    wait = float(ra)
                except ValueError:
                    pass
        except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as e:
            if attempt >= retries:
                raise HTTPFail(f'network error: {e}') from None
            wait = None
        if wait is None:
            wait = backoff * (2 ** attempt) * (0.5 + random.random())
        wait = min(wait, 60.0)
        if log:
            log(f'retry {attempt + 1}/{retries} in {wait:.1f}s')
        _sleep(wait)
        attempt += 1


# ---------------------------------------------------------------- providers

def anthropic_request(a, prompt):
    key = os.environ.get('ANTHROPIC_API_KEY')
    if not key:
        raise SystemExit('ANTHROPIC_API_KEY is not set')
    body = {'model': a.model, 'max_tokens': a.max_tokens,
            'messages': [{'role': 'user', 'content': prompt}]}
    if a.temperature is not None:
        body['temperature'] = a.temperature
    if a.system:
        body['system'] = a.system
    headers = {'x-api-key': key, 'anthropic-version': ANTHROPIC_VERSION}
    return (a.base_url or ANTHROPIC_URL), headers, body


def anthropic_text(resp):
    return ''.join(b.get('text', '') for b in resp.get('content', []) if b.get('type') == 'text')


def openai_request(a, prompt):
    base = (a.base_url or 'https://api.openai.com/v1').rstrip('/')
    url = base if base.endswith('/chat/completions') else base + '/chat/completions'
    msgs = ([{'role': 'system', 'content': a.system}] if a.system else []) + [{'role': 'user', 'content': prompt}]
    body = {'model': a.model, 'messages': msgs, 'max_tokens': a.max_tokens}
    if a.temperature is not None:
        body['temperature'] = a.temperature
    headers = {}
    key = os.environ.get('OPENAI_API_KEY')
    if key:  # local servers (vLLM, Ollama) usually need none
        headers['authorization'] = 'Bearer ' + key
    return url, headers, body


def openai_text(resp):
    ch = resp.get('choices') or [{}]
    return (ch[0].get('message') or {}).get('content') or ''


API = {'anthropic': (anthropic_request, anthropic_text), 'openai': (openai_request, openai_text)}

YESNO = re.compile(r'^(is|are|was|were|does|do|did|has|have|had|can|could|will)\b', re.I)


def make_caller(a, gold):
    """Return fn(row) -> raw reply string."""
    if a.provider in API:
        build, text = API[a.provider]

        def call(row):
            url, headers, body = build(a, row['prompt'])
            return text(post_json(url, headers, body, a.timeout, a.retries, a.backoff,
                                  log=lambda m: print(f"[{row['id']}] {m}", file=sys.stderr)))
        return call
    if a.provider == 'oracle':
        def call(row):
            if row['id'] not in gold:
                raise HTTPFail('oracle: no dev answer for this id (oracle needs --qa with answers)')
            g = gold[row['id']]
            return 'null' if g is None else json.dumps(g, ensure_ascii=False) if isinstance(g, list) else str(g)
        return call
    if a.provider == 'null':
        return lambda row: 'null'
    if a.provider == 'random-guess':
        def call(row):
            # Uses only the question text (never answer_type), seeded per id so runs repeat.
            rng = random.Random(f"{a.seed}:{row['id']}")
            q = row.get('question') or row['prompt'].rsplit('Question:', 1)[-1].strip()
            if YESNO.match(q):
                return rng.choice(['true', 'false'])
            return str(rng.randint(0, 1000))
        return call
    raise SystemExit('unknown provider ' + a.provider)


# ---------------------------------------------------------------- main

def parse_args(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    src = ap.add_argument_group('input')
    src.add_argument('--qa', help='QA folder or .jsonl (builds prompts; needed by oracle and --score)')
    src.add_argument('--prompts', help='prompts.jsonl from make_prompts.py (used instead of building)')
    src.add_argument('--with-context-hint', action='store_true', help='as in make_prompts.py, when building')
    src.add_argument('--sets', help='comma list of sets, e.g. world-earth,worlds-021-hibe')
    src.add_argument('--limit', type=int, help='at most N questions (after --sets)')
    m = ap.add_argument_group('model')
    m.add_argument('--provider', required=True, choices=['anthropic', 'openai', 'oracle', 'null', 'random-guess'])
    m.add_argument('--model')
    m.add_argument('--base-url', help='openai: e.g. http://localhost:8000/v1, https://openrouter.ai/api/v1')
    m.add_argument('--system', help='optional system prompt')
    m.add_argument('--max-tokens', type=int, default=512)
    m.add_argument('--temperature', type=float, default=0.0, help='use a negative value to omit it')
    m.add_argument('--seed', type=int, default=0, help='random-guess seed')
    r = ap.add_argument_group('run')
    r.add_argument('--out', required=True, help='predictions.jsonl (appended to; resumes)')
    r.add_argument('--concurrency', type=int, default=4)
    r.add_argument('--retries', type=int, default=5)
    r.add_argument('--backoff', type=float, default=1.0, help='base seconds for exponential backoff')
    r.add_argument('--timeout', type=float, default=120.0)
    r.add_argument('--no-resume', action='store_true', help='overwrite --out instead of resuming')
    r.add_argument('--score', action='store_true', help='run score.py at the end (needs --qa)')
    r.add_argument('--score-out', help='default: score.json next to --out')
    a = ap.parse_args(argv)
    if not a.qa and not a.prompts:
        ap.error('give --qa or --prompts')
    if a.provider == 'oracle' and not a.qa:
        ap.error('oracle needs --qa (a folder with answers, e.g. data/dev)')
    if a.score and not a.qa:
        ap.error('--score needs --qa')
    if a.temperature is not None and a.temperature < 0:
        a.temperature = None
    a.model = a.model or DEFAULT_MODELS.get(a.provider, a.provider)
    return a


def select_rows(a):
    items = load_items(a.qa) if a.qa else []
    gold = {it['id']: it.get('answer') for it in items if 'answer' in it}
    by_id = {it['id']: it for it in items}
    sets = [s.strip() for s in a.sets.split(',') if s.strip()] if a.sets else []
    rows = []
    if a.prompts:
        with open(a.prompts, encoding='utf-8') as fh:
            plines = fh.readlines()
        for line in plines:
            if line.strip():
                o = json.loads(line)
                it = by_id.get(o['id'], {})
                rows.append({'id': o['id'], 'prompt': o['prompt'], 'question': it.get('question'), '_set': it.get('_set')})
    else:
        rows = [{'id': it['id'], 'prompt': build_prompt(it, a.with_context_hint), 'question': it['question'],
                 '_set': it['_set']} for it in items]
    rows = [r for r in rows if in_sets(r['id'], r.get('_set'), sets)]
    if a.limit is not None:
        rows = rows[:a.limit]
    return rows, gold


def run(a):
    rows, gold = select_rows(a)
    os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
    if a.no_resume and os.path.exists(a.out):
        os.remove(a.out)
    done = load_done(a.out)
    todo = [r for r in rows if r['id'] not in done]
    print(f'{len(rows)} selected, {len(rows) - len(todo)} already in {a.out}, {len(todo)} to run '
          f'[{a.provider}:{a.model}]', file=sys.stderr)
    call = make_caller(a, gold)
    lock = threading.Lock()
    stats = {'ok': 0, 'err': 0}
    if os.path.exists(a.out) and os.path.getsize(a.out):
        with open(a.out, 'rb') as fh:
            fh.seek(-1, os.SEEK_END)
            partial = fh.read(1) != b'\n'
        if partial:  # a crash left a half-written last line: drop it so the file stays valid JSONL
            with open(a.out, 'rb') as fh:
                data = fh.read()
            with open(a.out, 'wb') as fh:
                fh.write(data[:data.rfind(b'\n') + 1])
    f = open(a.out, 'a', encoding='utf-8')

    def work(row):
        t0 = time.monotonic()
        try:
            raw = call(row)
        except HTTPFail as e:
            with lock:
                stats['err'] += 1
                print(f"[{row['id']}] FAILED: {e}", file=sys.stderr)
            return
        rec = {'id': row['id'], 'answer': extract_answer(raw), 'raw': raw,
               'latency_ms': int(round((time.monotonic() - t0) * 1000))}
        with lock:
            f.write(json.dumps(rec, ensure_ascii=False) + '\n')
            f.flush()
            stats['ok'] += 1
            n = stats['ok'] + stats['err']
            if n % 100 == 0 or n == len(todo):
                print(f'  {n}/{len(todo)} done ({stats["err"]} failed)', file=sys.stderr)

    try:
        with concurrent.futures.ThreadPoolExecutor(max(1, a.concurrency)) as ex:
            list(ex.map(work, todo))
    finally:
        f.close()
    print(f'wrote {stats["ok"]} predictions to {a.out}; {stats["err"]} failed (re-run to retry)', file=sys.stderr)
    rc = 1 if stats['err'] else 0
    if a.score:
        score_out = a.score_out or os.path.join(os.path.dirname(os.path.abspath(a.out)), 'score.json')
        cmd = [sys.executable, os.path.join(HERE, 'score.py'), '--qa', a.qa, '--pred', a.out, '--out', score_out]
        src = subprocess.call(cmd)
        if src:
            print(f'score.py failed (exit {src}); known case: a numeric reply to a string question whose gold '
                  f'looks numeric after normalising (e.g. world-sound-0216). scripts/score_guarded.py takes the '
                  f'same arguments and counts such pairs as wrong.', file=sys.stderr)
        else:
            print('score ->', score_out, file=sys.stderr)
        rc = src or rc
    return rc


if __name__ == '__main__':
    sys.exit(run(parse_args()))