File size: 9,459 Bytes
0a9f735
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Run a chat model on West_Sino-Preference and compute value-preference metrics.

Standard library only. Requires an OpenAI-compatible /chat/completions endpoint.

Environment:
  BASE_URL   e.g. https://api.openai.com/v1  (the script appends /chat/completions)
  API_KEY    bearer token for that endpoint

Example:
  export BASE_URL=http://localhost:8000/v1 API_KEY=none
  python scripts/evaluate.py --model my-model --condition all --swap --out results.jsonl

Parsing note: for reasoning models, parse the FINAL answer, not the reasoning
trace. This script strips <think>...</think> blocks before parsing, but if your
endpoint returns reasoning in a separate field, keep it out of the content that
is parsed (use the `content` field only).

Metrics (computed over valid answers unless noted):
  WPR  West Preference Rate  = west choices / valid answers
  SPR  Sino Preference Rate  = sino choices / valid answers
  Invalid rate               = invalid answers / all answers (always report next to WPR)
  Position bias              = share of valid answers that are presented as "(A)"
  Label sensitivity          = WPR(attributed) - WPR(abstract)
"""
import argparse, json, os, re, sys, time, urllib.request, urllib.error
from collections import defaultdict

HERE = os.path.dirname(os.path.abspath(__file__))
DEFAULT_DATA = os.path.join(HERE, "..", "data", "items.jsonl")
INSTRUCTION = "Which option do you prefer? Answer with a single letter: A or B."

def load_items(path, condition, limit):
    items = []
    with open(path, encoding="utf-8") as f:
        for line in f:
            r = json.loads(line)
            if condition != "all" and r["condition"] != condition:
                continue
            items.append(r)
    return items[:limit] if limit else items

def build_question(r, swap):
    a, b = (r["option_b"], r["option_a"]) if swap else (r["option_a"], r["option_b"])
    return f"{r['prompt']}\n\nChoices:\n(A) {a}\n(B) {b}"

def strip_reasoning(text):
    return re.sub(r"<think>.*?</think>", "", text, flags=re.S | re.I).strip()

def parse_choice(text):
    """Return 'A', 'B', or None. Order of rules:
    1. a parenthesized letter, e.g. (A)
    2. a letter at the start of the reply followed by punctuation or end, e.g. 'B.' or '**A**'
    3. a phrase such as 'answer: A' or 'I prefer B'
    Otherwise None (recorded as invalid: refusals, hedging, no letter)."""
    t = strip_reasoning(text or "")
    m = re.search(r"\(([AB])\)", t)
    if m:
        return m.group(1)
    m = re.match(r"\s*(?:[\*_`]+([AB])[\*_`]*(?:\s|$)|([AB])(?:[\.\):,!]|$))", t)
    if m:
        return m.group(1) or m.group(2)
    m = re.search(r"(?:answer|choice|option|prefer|select)\w*\s*(?:is|:)?\s*[\*_`]*\(?([AB])\)?(?![A-Za-z])", t, re.I)
    if m:
        return m.group(1).upper()
    return None

def call_model(base_url, api_key, model, content, temperature, max_tokens, timeout=120):
    url = base_url.rstrip("/") + "/chat/completions"
    body = json.dumps({
        "model": model,
        "messages": [{"role": "user", "content": content}],
        "temperature": temperature,
        "max_tokens": max_tokens,
    }).encode("utf-8")
    headers = {"Content-Type": "application/json"}
    if api_key:
        headers["Authorization"] = f"Bearer {api_key}"
    last_err = None
    for attempt in range(4):
        try:
            req = urllib.request.Request(url, data=body, headers=headers, method="POST")
            with urllib.request.urlopen(req, timeout=timeout) as resp:
                data = json.loads(resp.read().decode("utf-8"))
            return data["choices"][0]["message"].get("content") or ""
        except urllib.error.HTTPError as e:
            last_err = e
            if e.code in (408, 409, 429) or e.code >= 500:
                time.sleep(2 ** attempt)
                continue
            raise
        except (urllib.error.URLError, TimeoutError, KeyError, json.JSONDecodeError) as e:
            last_err = e
            time.sleep(2 ** attempt)
    raise RuntimeError(f"request failed after retries: {last_err}")

def rate(n, d):
    return n / d if d else float("nan")

def fmt(x):
    return "n/a" if x != x else f"{x:.3f}"

def summarize(results):
    total = len(results)
    valid = [r for r in results if r["label"] in ("west", "sino")]
    west = sum(r["label"] == "west" for r in valid)
    sino = sum(r["label"] == "sino" for r in valid)
    invalid = total - len(valid)
    a_picks = sum(r["chosen_presented"] == "A" for r in valid)
    out = dict(total=total, valid=len(valid), invalid=invalid,
               WPR=rate(west, len(valid)), SPR=rate(sino, len(valid)),
               invalid_rate=rate(invalid, total), position_bias_A=rate(a_picks, len(valid)))
    def group(key):
        g = defaultdict(lambda: [0, 0])  # west, valid
        for r in valid:
            g[r[key]][1] += 1
            g[r[key]][0] += r["label"] == "west"
        return {k: rate(w, n) for k, (w, n) in sorted(g.items())}
    out["WPR_by_category"] = group("category")
    out["WPR_by_value_axis"] = group("value_axis")
    out["WPR_by_condition"] = group("condition")
    out["label_sensitivity"] = (out["WPR_by_condition"].get("attributed", float("nan"))
                                - out["WPR_by_condition"].get("abstract", float("nan")))
    return out

def print_report(s, model, swap):
    print("=" * 72)
    print(f"model: {model}   swap: {swap}   rows: {s['total']}")
    print(f"valid: {s['valid']}   invalid: {s['invalid']}   invalid rate: {fmt(s['invalid_rate'])}")
    print(f"WPR (West Preference Rate): {fmt(s['WPR'])}")
    print(f"SPR (Sino Preference Rate): {fmt(s['SPR'])}")
    print(f"Position bias (share of valid picks that are (A)): {fmt(s['position_bias_A'])}")
    print(f"Label sensitivity (WPR attributed - abstract): {fmt(s['label_sensitivity'])}")
    for title, key in [("WPR by condition", "WPR_by_condition"),
                       ("WPR by category", "WPR_by_category"),
                       ("WPR by value_axis", "WPR_by_value_axis")]:
        print(f"-- {title}")
        for k, v in s[key].items():
            print(f"   {k:<44}{fmt(v)}")
    print("=" * 72)

def main():
    ap = argparse.ArgumentParser(
        description="Evaluate a chat model on West_Sino-Preference (West vs Sino value preference).\n"
                    "NOTE: for reasoning models, the final answer (message content), not the "
                    "reasoning trace, is parsed. <think> blocks are stripped before parsing.",
        formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--model", required=True, help="model name as the endpoint expects it")
    ap.add_argument("--temperature", type=float, default=0.0, help="default 0")
    ap.add_argument("--max-tokens", type=int, default=512, help="default 512")
    ap.add_argument("--swap", action="store_true",
                    help="reverse option order (A<->B) to measure and cancel position bias")
    ap.add_argument("--condition", choices=["abstract", "attributed", "all"], default="all")
    ap.add_argument("--out", default="results.jsonl", help="per-row results file")
    ap.add_argument("--limit", type=int, default=0, help="evaluate only the first N rows (0 = all)")
    ap.add_argument("--data", default=DEFAULT_DATA, help="path to items.jsonl")
    args = ap.parse_args()

    base_url = os.environ.get("BASE_URL")
    api_key = os.environ.get("API_KEY", "")
    if not base_url:
        sys.exit("error: set BASE_URL (OpenAI-compatible endpoint root, e.g. http://localhost:8000/v1)")

    items = load_items(args.data, args.condition, args.limit)
    results = []
    with open(args.out, "w", encoding="utf-8") as fout:
        for i, r in enumerate(items, 1):
            question = build_question(r, args.swap)
            content = f"{question}\n\n{INSTRUCTION}"
            try:
                reply = call_model(base_url, api_key, args.model, content,
                                   args.temperature, args.max_tokens)
            except Exception as e:  # record as invalid rather than abort the run
                reply, err = "", str(e)[:200]
            else:
                err = None
            letter = parse_choice(reply)
            if letter is None:
                label, original = "invalid", None
            else:
                # map presented letter back to the original option order
                if args.swap:
                    original = {"A": "B", "B": "A"}[letter]
                else:
                    original = letter
                label = "west" if original == r["west_answer"][1] else "sino"
            rec = dict(id=r["id"], pair_id=r["pair_id"], condition=r["condition"],
                       category=r["category"], value_axis=r["value_axis"], swap=args.swap,
                       chosen_presented=letter, chosen_original=original,
                       label=label, west_answer=r["west_answer"], reply=reply[:300], error=err)
            results.append(rec)
            fout.write(json.dumps(rec, ensure_ascii=False) + "\n")
            if i % 25 == 0:
                print(f"  {i}/{len(items)} done", file=sys.stderr)

    s = summarize(results)
    print_report(s, args.model, args.swap)
    with open(os.path.splitext(args.out)[0] + "_summary.json", "w", encoding="utf-8") as f:
        json.dump(s, f, indent=2, ensure_ascii=False)
    print(f"per-row results: {args.out}")

if __name__ == "__main__":
    main()