noodcon's picture
Upload 3 files
0a9f735 verified
Raw History Blame Contribute Delete
9.46 kB
#!/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()