File size: 3,641 Bytes
611d454
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Example runner: send the prompts from make_prompts.py to a model server and write a predictions file.

Usage:
  run_local.py --prompts prompts_hard.jsonl --model gemma4:26b --out preds.jsonl
               [--api ollama|openai] [--base-url URL] [--temperature 0] [--seed 42]

--api ollama (default) posts to BASE_URL/api/chat with the JSON schema in "format", think off,
num_ctx 8192 and num_predict 160: the settings of the shipped baselines.
--api openai posts to BASE_URL/v1/chat/completions (any OpenAI-compatible server). An API key,
if the server needs one, is read from the environment variable named by --key-env.
Resumable: rows already in --out are skipped. Standard library only.
"""
import argparse
import json
import os
import sys
import urllib.request
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from pocb import PAIRWISE_SCHEMA, POINTWISE_SCHEMA, load_jsonl  # noqa: E402


def call(a, row):
    pairwise = "pair_id" in row
    msgs = [{"role": "system", "content": row["system"]}, {"role": "user", "content": row["prompt"]}]
    if a.api == "ollama":
        url = a.base_url.rstrip("/") + "/api/chat"
        body = {"model": a.model, "stream": False, "think": False, "messages": msgs,
                "format": PAIRWISE_SCHEMA if pairwise else POINTWISE_SCHEMA,
                "options": {"temperature": a.temperature, "seed": a.seed, "num_predict": 160, "num_ctx": 8192}}
    else:
        url = a.base_url.rstrip("/") + "/v1/chat/completions"
        body = {"model": a.model, "messages": msgs, "temperature": a.temperature, "seed": a.seed}
    headers = {"Content-Type": "application/json"}
    if a.key_env and os.environ.get(a.key_env):
        headers["Authorization"] = "Bearer " + os.environ[a.key_env]
    req = urllib.request.Request(url, data=json.dumps(body).encode(), headers=headers)
    with urllib.request.urlopen(req, timeout=a.timeout) as r:
        resp = json.loads(r.read())
    if a.api == "ollama":
        return resp.get("message", {}).get("content", "")
    return resp["choices"][0]["message"]["content"]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--prompts", required=True)
    ap.add_argument("--model", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--api", choices=("ollama", "openai"), default="ollama")
    ap.add_argument("--base-url", default="http://localhost:11434")
    ap.add_argument("--key-env", default="", help="name of the env var holding an API key (optional)")
    ap.add_argument("--temperature", type=float, default=0.0)
    ap.add_argument("--seed", type=int, default=42)
    ap.add_argument("--timeout", type=float, default=600)
    a = ap.parse_args()
    out = Path(a.out)
    done = set()
    if out.exists():
        done = {(r.get("id"), r.get("pair_id"), r.get("order")) for r in load_jsonl(out)}
    todo = [r for r in load_jsonl(a.prompts) if (r.get("id"), r.get("pair_id"), r.get("order")) not in done]
    print(f"{a.model}: {len(todo)} calls", flush=True)
    with open(out, "a") as f:
        for n, row in enumerate(todo):
            text = call(a, row)
            rec = {k: row[k] for k in ("id", "pair_id", "order") if k in row}
            rec.update({"response": text, "model": a.model, "temperature": a.temperature, "seed": a.seed,
                        "prompt_sha256": row["prompt_sha256"]})
            f.write(json.dumps(rec, ensure_ascii=False) + "\n"); f.flush()
            if n % 10 == 0:
                print(f"{n + 1}/{len(todo)}", flush=True)
    print("done", flush=True)


if __name__ == "__main__":
    main()