steps456: add code/exp/pipeline (chance.py + scoring.py + stage_d_blind.py) needed by pool_steps.eligible (MCQ yes/no rule); fixes ModuleNotFoundError 'chance'
Browse files
steps456_20260910/code/exp/pipeline/chance.py
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""One chance definition for every table (user plan item 3, 2026-09-06).
|
| 2 |
+
|
| 3 |
+
item_chance(row, bench_meta, k_inferred=None, digit_index=False) -> (c, source)
|
| 4 |
+
Per-item chance c and its source, in this precedence:
|
| 5 |
+
list 1/k, k = length of the sample row's option list
|
| 6 |
+
(scoring.coerce_options; lists with k >= 2)
|
| 7 |
+
question 1/k, k = number of lettered option lines embedded in the question
|
| 8 |
+
text (stage_d_blind.embedded_options: >= 2 lines A, B, ... in order)
|
| 9 |
+
declared 1/num_options of exp/video_benchmarks.csv, only for benchmarks with
|
| 10 |
+
question_format == MCQ; has_chance_level is NOT consulted (that flag
|
| 11 |
+
produced the NA cells of the earlier tables); several integers
|
| 12 |
+
("4 or 6") give the mean of 1/n
|
| 13 |
+
inferred 1/k_inferred, k inferred from the letter-form golds of the
|
| 14 |
+
benchmark's items without an option list (infer_k: the smallest
|
| 15 |
+
number of leading positions that holds >= 95 % of those golds, at
|
| 16 |
+
least 2); passed in by the caller (bench_chance computes it)
|
| 17 |
+
yesno 0.5 for golds yes / no / true / false
|
| 18 |
+
open 0 (everything else: free text, numbers, intervals)
|
| 19 |
+
Multi-select golds use 1/k of their option count like single-select items.
|
| 20 |
+
|
| 21 |
+
bench_chance(samples, bench_meta) -> dict
|
| 22 |
+
c benchmark chance = mean of the item chances over the MULTIPLE-CHOICE
|
| 23 |
+
items only (is_mcq_item; user decision 2026-09-10: every statistic uses
|
| 24 |
+
multiple-choice items, yes/no and open items excluded); c_all keeps the
|
| 25 |
+
earlier all-item mean; n_mcq / n_excluded / mcq_qids report the split
|
| 26 |
+
cvec {qid: c_item}
|
| 27 |
+
csrc Counter of sources
|
| 28 |
+
c_source "declared:8;list:292" (sorted source:count pairs)
|
| 29 |
+
k_inf inferred k (0 when no item needed it)
|
| 30 |
+
n_items, n_open, digit_index, pos ({qid: gold letter}, see gold_position)
|
| 31 |
+
|
| 32 |
+
item_chances(samples, bench_meta) -> (cvec, pos, csrc, k_inf)
|
| 33 |
+
Compatibility wrapper for exp/analysis/apex/breaking_levels.py.
|
| 34 |
+
|
| 35 |
+
gold_position(row, opts, fmt, digit_index) -> letter | None
|
| 36 |
+
Letter of the gold option (fixed-position attacker of breaking_levels).
|
| 37 |
+
|
| 38 |
+
Consumers: stage_e1_stats.py (e1_table chance), e1_n1_stats.py (N1 e1_table),
|
| 39 |
+
stage_p2_profiles.py (chance / lang_prior), exp/t3/export_t2_tables.py (T2
|
| 40 |
+
threshold), exp/analysis/apex/breaking_levels.py, exp/report/build_tex.py.
|
| 41 |
+
|
| 42 |
+
CLI (writes exp/results/chance_by_benchmark.csv and chance_notes.md):
|
| 43 |
+
python chance.py [--samples-dir D --samples-n1-dir D --bench-csv F --out-dir D]
|
| 44 |
+
The notes compare c against the *.pre_chance_v2.csv snapshots of the earlier
|
| 45 |
+
tables (e1_table, n1/e1_table, t2 s300 export, apex/breaking_levels) when
|
| 46 |
+
those files exist, and list every benchmark whose c moved by more than 0.01.
|
| 47 |
+
"""
|
| 48 |
+
import argparse
|
| 49 |
+
import csv
|
| 50 |
+
import glob
|
| 51 |
+
import json
|
| 52 |
+
import math
|
| 53 |
+
import os
|
| 54 |
+
import re
|
| 55 |
+
import sys
|
| 56 |
+
from collections import Counter
|
| 57 |
+
|
| 58 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 59 |
+
EXP = os.path.abspath(os.path.join(HERE, ".."))
|
| 60 |
+
sys.path.insert(0, HERE)
|
| 61 |
+
from scoring import _MULTI, _pre, coerce_options, mcq_letter # noqa: E402
|
| 62 |
+
from stage_d_blind import item_options # noqa: E402
|
| 63 |
+
|
| 64 |
+
BENCH_CSV = os.path.join(EXP, "video_benchmarks.csv")
|
| 65 |
+
SOURCES = ["list", "question", "declared", "inferred", "yesno", "open"]
|
| 66 |
+
# gold in letter form: "C", "(C)", "C.", "C. text", "[C] text"
|
| 67 |
+
_LETTER_GOLD = re.compile(r"^\s*[\(\[]?([A-P])(?:[\)\]\.:]\s*(?:\S.*)?|\s*)$")
|
| 68 |
+
_YESNO = {"yes", "no", "true", "false"}
|
| 69 |
+
INFER_SHARE = 0.95
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# ------------------------------------------------------------------ meta
|
| 73 |
+
def load_bench_meta(path=BENCH_CSV):
|
| 74 |
+
"""{name: row} of exp/video_benchmarks.csv."""
|
| 75 |
+
return {r["name"]: r for r in csv.DictReader(open(path))}
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def bench_meta(meta, bench):
|
| 79 |
+
"""Row for a sample-file stem ('/' in the CSV name is '_' in file names)."""
|
| 80 |
+
return meta.get(bench) or meta.get(bench.replace("_", "/")) or {}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def declared_chance(m):
|
| 84 |
+
"""1/num_options (mean over the integers found) for an MCQ-format
|
| 85 |
+
benchmark; None otherwise. has_chance_level is not consulted."""
|
| 86 |
+
if (m.get("question_format") or "").strip().upper() != "MCQ":
|
| 87 |
+
return None
|
| 88 |
+
ns = [int(x) for x in re.findall(r"\d+", str(m.get("num_options") or "")) if int(x) > 1]
|
| 89 |
+
if not ns:
|
| 90 |
+
return None
|
| 91 |
+
return sum(1.0 / n for n in ns) / len(ns)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def declared_counts(m):
|
| 95 |
+
"""Sorted integers of num_options (any format), for option-count checks."""
|
| 96 |
+
return sorted({int(x) for x in re.findall(r"\d+", str(m.get("num_options") or "")) if int(x) > 1})
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
# ------------------------------------------------------------------ items
|
| 100 |
+
def is_yesno(ans):
|
| 101 |
+
return str(ans if ans is not None else "").strip().lower() in _YESNO
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def gold_position(row, opts, fmt, digit_index=False):
|
| 105 |
+
"""Letter of the gold option, or None (multi-select, open, unresolvable).
|
| 106 |
+
digit_index: the benchmark stores gold as a bare option index (NExT-QA style)."""
|
| 107 |
+
ans = row.get("answer")
|
| 108 |
+
if ans is None:
|
| 109 |
+
return None
|
| 110 |
+
if _MULTI.match(_pre(ans)):
|
| 111 |
+
return None
|
| 112 |
+
if opts:
|
| 113 |
+
return mcq_letter(ans, opts)
|
| 114 |
+
fmt = (fmt or "").strip().upper()
|
| 115 |
+
if fmt not in ("MCQ", "MIXED"):
|
| 116 |
+
return None
|
| 117 |
+
m = _LETTER_GOLD.match(_pre(ans))
|
| 118 |
+
if m:
|
| 119 |
+
return m.group(1).upper()
|
| 120 |
+
if fmt == "MCQ":
|
| 121 |
+
L = mcq_letter(ans)
|
| 122 |
+
if L:
|
| 123 |
+
return L
|
| 124 |
+
s = str(ans).strip()
|
| 125 |
+
if digit_index and re.fullmatch(r"\d", s):
|
| 126 |
+
return chr(65 + int(s))
|
| 127 |
+
return None
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def item_chance(row, m, k_inferred=None, digit_index=False):
|
| 131 |
+
"""(c, source) for one sample row; m = video_benchmarks.csv row (or {})."""
|
| 132 |
+
opts, src = item_options(row)
|
| 133 |
+
if opts:
|
| 134 |
+
return 1.0 / len(opts), src
|
| 135 |
+
dec = declared_chance(m)
|
| 136 |
+
if dec:
|
| 137 |
+
return dec, "declared"
|
| 138 |
+
if k_inferred and gold_position(row, None, m.get("question_format", ""), digit_index):
|
| 139 |
+
return 1.0 / k_inferred, "inferred"
|
| 140 |
+
if is_yesno(row.get("answer")):
|
| 141 |
+
return 0.5, "yesno"
|
| 142 |
+
return 0.0, "open"
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def infer_k(samples, m, opts_of=None):
|
| 146 |
+
"""(k_inferred, pos, digit_index) for a benchmark: k = smallest count of
|
| 147 |
+
leading positions holding >= 95 % of the letter-form golds of the items
|
| 148 |
+
without an option list (at least 2); 0 when no such gold exists. pos maps
|
| 149 |
+
every item (with or without options) to its gold letter when resolvable."""
|
| 150 |
+
fmt = m.get("question_format", "")
|
| 151 |
+
is_mcq = (fmt or "").strip().upper() == "MCQ"
|
| 152 |
+
if opts_of is None:
|
| 153 |
+
opts_of = {qid: item_options(r)[0] for qid, r in samples.items()}
|
| 154 |
+
unc_golds = [str(r.get("answer", "")).strip() for qid, r in samples.items() if not opts_of[qid]]
|
| 155 |
+
digit_index = bool(is_mcq and unc_golds and all(re.fullmatch(r"\d", g) for g in unc_golds if g))
|
| 156 |
+
pos = {}
|
| 157 |
+
for qid, r in samples.items():
|
| 158 |
+
L = gold_position(r, opts_of[qid], fmt, digit_index)
|
| 159 |
+
if L:
|
| 160 |
+
pos[qid] = L
|
| 161 |
+
unc_pos = sorted(ord(L) - 64 for q, L in pos.items() if not opts_of[q])
|
| 162 |
+
k_inf = 0
|
| 163 |
+
if unc_pos:
|
| 164 |
+
k_inf = max(2, unc_pos[min(len(unc_pos) - 1, int(math.ceil(INFER_SHARE * len(unc_pos))) - 1)])
|
| 165 |
+
return k_inf, pos, digit_index
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
MCQ_SOURCES = ("list", "question", "declared", "inferred")
|
| 169 |
+
_YN_SET = {"yes", "no", "true", "false"}
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _yes_no_options(opts):
|
| 173 |
+
"""True when the option texts are only yes/no (or true/false), e.g. ['A. Yes', 'B. No']."""
|
| 174 |
+
texts = set()
|
| 175 |
+
for o in opts or []:
|
| 176 |
+
t = re.sub(r"^\s*[\(\[]?[A-Za-z][\)\]\.:]\s*", "", str(o)).strip().lower().rstrip(".")
|
| 177 |
+
texts.add(t)
|
| 178 |
+
return bool(texts) and texts <= _YN_SET
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def is_mcq_item(row, m, k_inferred=None, digit_index=False):
|
| 182 |
+
"""Statistics rule (user decision 2026-09-10): every statistic uses multiple-choice items only.
|
| 183 |
+
An item counts when its chance source is list / question / declared / inferred (an option list,
|
| 184 |
+
options embedded in the question text, a declared MCQ benchmark with a letter gold, or an inferred
|
| 185 |
+
option count) AND its options are not a bare yes/no (true/false) pair. Yes/no items and open items
|
| 186 |
+
(free text, numbers, intervals) are excluded."""
|
| 187 |
+
c, src = item_chance(row, m, k_inferred, digit_index)
|
| 188 |
+
if src not in MCQ_SOURCES or c <= 0:
|
| 189 |
+
return False
|
| 190 |
+
opts, _ = item_options(row)
|
| 191 |
+
if opts and _yes_no_options(opts):
|
| 192 |
+
return False
|
| 193 |
+
if not opts and is_yesno(row.get("answer")):
|
| 194 |
+
return False
|
| 195 |
+
return True
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def mcq_items(samples, m):
|
| 199 |
+
"""{qid: row} of the multiple-choice items of a sample (see is_mcq_item)."""
|
| 200 |
+
m = m or {}
|
| 201 |
+
opts_of = {qid: item_options(r)[0] for qid, r in samples.items()}
|
| 202 |
+
k_inf, _, digit_index = infer_k(samples, m, opts_of)
|
| 203 |
+
return {qid: r for qid, r in samples.items() if is_mcq_item(r, m, k_inf, digit_index)}
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def bench_chance(samples, m):
|
| 207 |
+
"""See module docstring. samples = {qid: row}; m = CSV row or {}.
|
| 208 |
+
2026-09-10: c is the mean item chance over the MULTIPLE-CHOICE items only (is_mcq_item); open and
|
| 209 |
+
yes/no items are reported in n_open / n_yesno / n_excluded and carry no weight. cvec keeps every
|
| 210 |
+
item's chance (excluded items keep 0 or 0.5) so callers can still look items up; mcq_qids lists the
|
| 211 |
+
items that statistics should use."""
|
| 212 |
+
m = m or {}
|
| 213 |
+
opts_of = {qid: item_options(r)[0] for qid, r in samples.items()}
|
| 214 |
+
k_inf, pos, digit_index = infer_k(samples, m, opts_of)
|
| 215 |
+
cvec, csrc, mcq = {}, Counter(), []
|
| 216 |
+
for qid, r in samples.items():
|
| 217 |
+
c, src = item_chance(r, m, k_inf, digit_index)
|
| 218 |
+
cvec[qid], csrc[src] = c, csrc[src] + 1
|
| 219 |
+
if is_mcq_item(r, m, k_inf, digit_index):
|
| 220 |
+
mcq.append(qid)
|
| 221 |
+
n = len(cvec)
|
| 222 |
+
c_mcq = (sum(cvec[q] for q in mcq) / len(mcq)) if mcq else None
|
| 223 |
+
return dict(c=c_mcq, cvec=cvec, csrc=csrc, c_source=source_string(csrc), k_inf=k_inf, n_items=n,
|
| 224 |
+
n_mcq=len(mcq), n_excluded=n - len(mcq), mcq_qids=mcq,
|
| 225 |
+
n_open=csrc.get("open", 0), n_yesno=csrc.get("yesno", 0), digit_index=digit_index, pos=pos,
|
| 226 |
+
c_all=(sum(cvec.values()) / n) if n else None)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def item_chances(samples, m):
|
| 230 |
+
"""breaking_levels.py compatibility: (cvec, pos, csrc, k_inf)."""
|
| 231 |
+
d = bench_chance(samples, m)
|
| 232 |
+
return d["cvec"], d["pos"], d["csrc"], d["k_inf"]
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def source_string(csrc):
|
| 236 |
+
return ";".join(f"{k}:{v}" for k, v in sorted(csrc.items()))
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def load_samples(path):
|
| 240 |
+
out = {}
|
| 241 |
+
if not path or not os.path.exists(path):
|
| 242 |
+
return out
|
| 243 |
+
for l in open(path):
|
| 244 |
+
if l.strip():
|
| 245 |
+
r = json.loads(l)
|
| 246 |
+
out[r["qid"]] = r
|
| 247 |
+
return out
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
# ------------------------------------------------------------------ CLI
|
| 251 |
+
def _f(v):
|
| 252 |
+
try:
|
| 253 |
+
return float(v)
|
| 254 |
+
except (TypeError, ValueError):
|
| 255 |
+
return None
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def _prev_table(path, bench_col, val_col, pick_first=True):
|
| 259 |
+
"""{bench: value or None} from a snapshot; first non-NA per bench."""
|
| 260 |
+
out = {}
|
| 261 |
+
if not os.path.exists(path):
|
| 262 |
+
return None
|
| 263 |
+
for r in csv.DictReader(l for l in open(path) if not l.startswith("#")):
|
| 264 |
+
b = r.get(bench_col)
|
| 265 |
+
if b is None:
|
| 266 |
+
continue
|
| 267 |
+
v = _f(r.get(val_col))
|
| 268 |
+
if b not in out or (out[b] is None and v is not None):
|
| 269 |
+
out[b] = v
|
| 270 |
+
return out
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def reason_for(row):
|
| 274 |
+
"""Short reason text derived from the source counts of a benchmark."""
|
| 275 |
+
src = dict(kv.split(":") for kv in row["c_source_counts"].split(";") if kv)
|
| 276 |
+
src = {k: int(v) for k, v in src.items()}
|
| 277 |
+
n = int(row["n_items"])
|
| 278 |
+
parts = []
|
| 279 |
+
if src.get("declared"):
|
| 280 |
+
parts.append(f"declared num_options={row['num_options_csv']} applied to {src['declared']} items "
|
| 281 |
+
f"without an option list (has_chance_level={row['has_chance_level_csv']} no longer gates c)")
|
| 282 |
+
if src.get("question"):
|
| 283 |
+
parts.append(f"{src['question']} items carry lettered options inside the question text (1/k each)")
|
| 284 |
+
if src.get("inferred"):
|
| 285 |
+
parts.append(f"k={row['k_inferred']} inferred from letter-form golds for {src['inferred']} items")
|
| 286 |
+
if src.get("yesno"):
|
| 287 |
+
parts.append(f"{src['yesno']} yes/no golds count 0.5")
|
| 288 |
+
if src.get("open"):
|
| 289 |
+
parts.append(f"{src['open']}/{n} open items count 0 (item average, not MCQ-only mean)")
|
| 290 |
+
if src.get("list"):
|
| 291 |
+
parts.append(f"1/k over the option lists of {src['list']} items (k: {row['k_dist']})")
|
| 292 |
+
return "; ".join(parts) or "item-average over the sampled option lists"
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def main():
|
| 296 |
+
ap = argparse.ArgumentParser()
|
| 297 |
+
ap.add_argument("--samples-dir", default=os.path.join(EXP, "data", "samples"))
|
| 298 |
+
ap.add_argument("--samples-n1-dir", default=os.path.join(EXP, "data", "samples_n1"))
|
| 299 |
+
ap.add_argument("--bench-csv", default=BENCH_CSV)
|
| 300 |
+
ap.add_argument("--out-dir", default=os.path.join(EXP, "results"))
|
| 301 |
+
a = ap.parse_args()
|
| 302 |
+
meta = load_bench_meta(a.bench_csv)
|
| 303 |
+
rows = []
|
| 304 |
+
for set_name, d in (("main", a.samples_dir), ("n1", a.samples_n1_dir)):
|
| 305 |
+
for p in sorted(glob.glob(os.path.join(d, "*.jsonl"))):
|
| 306 |
+
bench = os.path.basename(p)[:-6]
|
| 307 |
+
m = bench_meta(meta, bench)
|
| 308 |
+
samples = load_samples(p)
|
| 309 |
+
r = bench_chance(samples, m)
|
| 310 |
+
kd = Counter(len(item_options(x)[0]) for x in samples.values() if item_options(x)[0])
|
| 311 |
+
rows.append(dict(bench=bench, set=set_name, c=f"{r['c']:.4f}" if r["c"] is not None else "NA",
|
| 312 |
+
c_source_counts=r["c_source"], n_items=r["n_items"], n_open=r["n_open"],
|
| 313 |
+
k_inferred=r["k_inf"], k_dist=";".join(f"{k}:{v}" for k, v in sorted(kd.items())),
|
| 314 |
+
question_format=m.get("question_format", ""),
|
| 315 |
+
num_options_csv=m.get("num_options", ""),
|
| 316 |
+
has_chance_level_csv=m.get("has_chance_level", ""),
|
| 317 |
+
n_mcq=r["n_mcq"], n_excluded=r["n_excluded"], n_yesno=r["n_yesno"],
|
| 318 |
+
c_all=f"{r['c_all']:.4f}" if r["c_all"] is not None else "NA"))
|
| 319 |
+
# 2026-09-10: n_mcq / n_excluded / n_yesno / c_all appended (n_mcq = multiple-choice items = the n of every
|
| 320 |
+
# statistic; benchmarks with n_mcq = 0 leave the main-set tables; c_all = the earlier all-item mean)
|
| 321 |
+
cols = ["bench", "set", "c", "c_source_counts", "n_items", "n_open", "k_inferred", "k_dist",
|
| 322 |
+
"question_format", "num_options_csv", "has_chance_level_csv", "n_mcq", "n_excluded", "n_yesno", "c_all"]
|
| 323 |
+
out_csv = os.path.join(a.out_dir, "chance_by_benchmark.csv")
|
| 324 |
+
with open(out_csv, "w", newline="") as f:
|
| 325 |
+
w = csv.DictWriter(f, fieldnames=cols)
|
| 326 |
+
w.writeheader()
|
| 327 |
+
w.writerows(rows)
|
| 328 |
+
print(f"[chance] wrote {out_csv} ({len(rows)} rows)")
|
| 329 |
+
for set_name in ("main", "n1"):
|
| 330 |
+
z = [r["bench"] for r in rows if r["set"] == set_name and r["n_mcq"] == 0]
|
| 331 |
+
lo = [f"{r['bench']} ({r['n_mcq']})" for r in rows if r["set"] == set_name and 0 < r["n_mcq"] < 30]
|
| 332 |
+
print(f"[chance] {set_name}: {len(z)} benchmark(s) with n_mcq = 0 (excluded from every statistic): {z}")
|
| 333 |
+
print(f"[chance] {set_name}: {len(lo)} benchmark(s) with 0 < n_mcq < 30: {lo}")
|
| 334 |
+
|
| 335 |
+
# ---- notes: compare with the earlier tables (snapshots *.pre_chance_v2.csv)
|
| 336 |
+
R = a.out_dir
|
| 337 |
+
prev = {
|
| 338 |
+
"e1_table.csv (stage_e1_stats; has_chance_level-gated 1/num_options)":
|
| 339 |
+
_prev_table(os.path.join(R, "e1_table.pre_chance_v2.csv"), "bench", "chance"),
|
| 340 |
+
"n1/e1_table.csv (e1_n1_stats; csv else mean 1/k over option lists when >= half the items)":
|
| 341 |
+
_prev_table(os.path.join(R, "n1", "e1_table.pre_chance_v2.csv"), "bench", "chance"),
|
| 342 |
+
"t2/t2_eps_by_benchmark_s300.csv (export chance = 1/len(options), 0 without a list)":
|
| 343 |
+
_prev_table(os.path.join(R, "t2", "t2_eps_by_benchmark_s300.pre_chance_v2.csv"), "benchmark", "chance"),
|
| 344 |
+
"apex/breaking_levels.csv (item average over the reference model's validly scored items; "
|
| 345 |
+
"declared only when has_chance_level)":
|
| 346 |
+
_prev_table(os.path.join(R, "apex", "breaking_levels.pre_chance_v2.csv"), "bench", "c"),
|
| 347 |
+
}
|
| 348 |
+
extra_note = {
|
| 349 |
+
"apex": ("The apex value averages over the items the reference model scored validly (free-text golds "
|
| 350 |
+
"are NA there), the new benchmark c averages over all sampled items with open items at 0; "
|
| 351 |
+
"differences on benchmarks with open items come from that denominator. Inside "
|
| 352 |
+
"breaking_levels.py the profile c is still computed on the reference items (same chance.py "
|
| 353 |
+
"item values)."),
|
| 354 |
+
"e1_table": ("Previously NA = has_chance_level False in exp/video_benchmarks.csv (the old gate); the "
|
| 355 |
+
"value now comes from the sampled items."),
|
| 356 |
+
"n1/e1": ("Previously NA = fewer than half the items carried an option list and the CSV had no "
|
| 357 |
+
"has_chance_level; the value now comes from the sampled items."),
|
| 358 |
+
"t2": ("The export's chance is 1/len(options) of the sample list and 0 when the sample has no list "
|
| 359 |
+
"(question-embedded, declared, inferred and yes/no items); those benchmarks move from 0."),
|
| 360 |
+
}
|
| 361 |
+
by_bench = {r["bench"]: r for r in rows}
|
| 362 |
+
L = ["# Chance correction: changes against the earlier tables", "",
|
| 363 |
+
"Definition (exp/pipeline/chance.py): per item 1/k from the option list, else 1/k from lettered "
|
| 364 |
+
"option lines embedded in the question, else 1/declared num_options for MCQ-format benchmarks "
|
| 365 |
+
"(has_chance_level not consulted), else 1/k inferred from letter-form golds (k = smallest number of "
|
| 366 |
+
"leading positions holding >= 95 % of such golds), else 0.5 for yes/no golds, else 0 (open). "
|
| 367 |
+
"Benchmark c = mean over the multiple-choice items only (user decision 2026-09-10: yes/no and open items "
|
| 368 |
+
"are excluded from every statistic; n_mcq / n_excluded in exp/results/chance_by_benchmark.csv). "
|
| 369 |
+
"Source counts per benchmark: exp/results/chance_by_benchmark.csv.",
|
| 370 |
+
"", f"Benchmarks: {len(rows)} ({sum(r['set'] == 'main' for r in rows)} main, "
|
| 371 |
+
f"{sum(r['set'] == 'n1' for r in rows)} N1).", ""]
|
| 372 |
+
src_kinds = Counter()
|
| 373 |
+
for r in rows:
|
| 374 |
+
for k in {kv.split(":")[0] for kv in r["c_source_counts"].split(";") if kv}:
|
| 375 |
+
src_kinds[k] += 1
|
| 376 |
+
L.append("Benchmarks with at least one item per source: " + ", ".join(
|
| 377 |
+
f"{k} {src_kinds.get(k, 0)}" for k in SOURCES) + ".")
|
| 378 |
+
L.append("")
|
| 379 |
+
for name, tab in prev.items():
|
| 380 |
+
L.append(f"## Versus {name}")
|
| 381 |
+
L.append("")
|
| 382 |
+
for key, txt in extra_note.items():
|
| 383 |
+
if name.startswith(key):
|
| 384 |
+
L.append(txt)
|
| 385 |
+
L.append("")
|
| 386 |
+
if tab is None:
|
| 387 |
+
L.append("Snapshot not found; no comparison.")
|
| 388 |
+
L.append("")
|
| 389 |
+
continue
|
| 390 |
+
changed, from_na, unchanged, absent = [], [], 0, 0
|
| 391 |
+
for b, old in sorted(tab.items()):
|
| 392 |
+
r = by_bench.get(b)
|
| 393 |
+
if r is None or r["c"] == "NA":
|
| 394 |
+
absent += 1
|
| 395 |
+
continue
|
| 396 |
+
new = float(r["c"])
|
| 397 |
+
if old is None:
|
| 398 |
+
from_na.append((b, new, r))
|
| 399 |
+
elif abs(new - old) > 0.01:
|
| 400 |
+
changed.append((b, old, new, r))
|
| 401 |
+
else:
|
| 402 |
+
unchanged += 1
|
| 403 |
+
L.append(f"Benchmarks in the snapshot: {len(tab)}; unchanged (|delta| <= 0.01): {unchanged}; "
|
| 404 |
+
f"changed by more than 0.01: {len(changed)}; previously NA / undefined: {len(from_na)}; "
|
| 405 |
+
f"not among the current samples: {absent}.")
|
| 406 |
+
L.append("")
|
| 407 |
+
if changed:
|
| 408 |
+
L.append("| benchmark | before | after | reason |")
|
| 409 |
+
L.append("|---|---|---|---|")
|
| 410 |
+
for b, old, new, r in sorted(changed, key=lambda x: -abs(x[2] - x[1])):
|
| 411 |
+
L.append(f"| {b} | {old:.4f} | {new:.4f} | {reason_for(r)} |")
|
| 412 |
+
L.append("")
|
| 413 |
+
if from_na:
|
| 414 |
+
L.append("| benchmark | before | after | reason |")
|
| 415 |
+
L.append("|---|---|---|---|")
|
| 416 |
+
for b, new, r in sorted(from_na, key=lambda x: -x[1]):
|
| 417 |
+
L.append(f"| {b} | NA | {new:.4f} | {reason_for(r)} |")
|
| 418 |
+
L.append("")
|
| 419 |
+
out_md = os.path.join(a.out_dir, "chance_notes.md")
|
| 420 |
+
open(out_md, "w").write("\n".join(L) + "\n")
|
| 421 |
+
print(f"[chance] wrote {out_md}")
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
if __name__ == "__main__":
|
| 425 |
+
main()
|
steps456_20260910/code/exp/pipeline/scoring.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Scoring rules shared by stages D/E/F.
|
| 2 |
+
|
| 3 |
+
score(pred, answer, options, question_format) -> bool | None
|
| 4 |
+
* MCQ (question_format == "MCQ", or options is a list with >= 2 entries):
|
| 5 |
+
extract the leading option letter from pred (regex ^\\s*\\(?([A-J])[).\\s:]
|
| 6 |
+
plus bare-letter / "Answer: X" fallbacks); normalize the gold answer the
|
| 7 |
+
same way (it may be "A", "(A)", "A. text", or the full option text -> the
|
| 8 |
+
letter comes from its index in options). Compare letters; if either side
|
| 9 |
+
yields no letter, fall back to normalized-text comparison against the
|
| 10 |
+
resolved option text. A bare numeric answer ("0") resolves as an index
|
| 11 |
+
into options (text match has priority). A comma-separated multi-select
|
| 12 |
+
gold ("A,B,C") is scored as letter-set equality with the prediction.
|
| 13 |
+
str-typed options are coerced to a list when the format is recognizable
|
| 14 |
+
(JSON dict/list, python list repr, "A. ..." lines).
|
| 15 |
+
* temporal grounding (gold parses as EXACTLY two floats, e.g. "[ 0. 12.6]"
|
| 16 |
+
or "21 39"): extract the first two non-negative floats from pred and score
|
| 17 |
+
by interval IoU >= 0.5 (industry-standard R@0.5). Pred without two floats
|
| 18 |
+
falls back to normalized exact match.
|
| 19 |
+
* counting / numeric (gold parses as ONE number): if pred is not itself a
|
| 20 |
+
pure number sequence, extract the number from pred ("is/are/answer: N"
|
| 21 |
+
pattern preferred, else the last standalone number) and compare.
|
| 22 |
+
* free text (non-MCQ gold with >= FREETEXT_MIN_WORDS words): NOT rule-
|
| 23 |
+
scorable -> returns None. Callers must treat None as NA (exclude from
|
| 24 |
+
accuracy), never as wrong.
|
| 25 |
+
* other non-MCQ: normalized exact match (lowercase, punctuation stripped,
|
| 26 |
+
whitespace collapsed). If BOTH sides parse entirely as number sequences,
|
| 27 |
+
compare numerically ("5" == "5.0").
|
| 28 |
+
|
| 29 |
+
chance_level(num_options, has_chance_level) -> float | None
|
| 30 |
+
None unless has_chance_level is truthy ("True"/"true"/True/1). num_options
|
| 31 |
+
may be junk from the CSV ('', 'NA', '4', '4 or 6'); every integer found
|
| 32 |
+
contributes 1/n and the mean is returned ("4 or 6" -> (1/4+1/6)/2).
|
| 33 |
+
|
| 34 |
+
Run `python scoring.py` for the self-test.
|
| 35 |
+
"""
|
| 36 |
+
import ast
|
| 37 |
+
import json
|
| 38 |
+
import re
|
| 39 |
+
|
| 40 |
+
# leading option letter: "B", "(B)", "B.", "B) text", "[b]", "b: text"
|
| 41 |
+
_LEAD = re.compile(r"^\s*[\(\[]?([A-Ja-j])[\)\]\.,:]?(?:\s|$)")
|
| 42 |
+
# comma-separated multi-select gold: "A,B,C" / "a, c"
|
| 43 |
+
_MULTI = re.compile(r"^\s*[A-Ja-j](\s*,\s*[A-Ja-j])+\s*$")
|
| 44 |
+
# "answer is (B)" / "Answer: B." / "option B" (the LAST occurrence wins:
|
| 45 |
+
# predictions often discuss wrong options before stating the answer)
|
| 46 |
+
_STATED = re.compile(
|
| 47 |
+
r"(?:answer|option|choice)\s*(?:is|would\s+be)?\s*[:\-]?\s*[\(\[]?([A-Ja-j])[\)\]\.,:]?(?:\s|$)",
|
| 48 |
+
re.IGNORECASE)
|
| 49 |
+
_STATED_CN = re.compile(r"答案\s*(?:是|为)?\s*[::]?\s*[\(\[]?([A-Ja-j])(?![A-Za-z])")
|
| 50 |
+
# extended alphabet K-P for benches with MORE than 10 options (N1 intake:
|
| 51 |
+
# UCF101-AD 11, iSafetyBench 16). Selected only when len(options) > 10, so
|
| 52 |
+
# every bench with <=10 options keeps the exact A-J behaviour above.
|
| 53 |
+
_LEAD_X = re.compile(r"^\s*[\(\[]?([A-Pa-p])[\)\]\.,:]?(?:\s|$)")
|
| 54 |
+
_MULTI_X = re.compile(r"^\s*[A-Pa-p](\s*,\s*[A-Pa-p])+\s*$")
|
| 55 |
+
_STATED_X = re.compile(
|
| 56 |
+
r"(?:answer|option|choice)\s*(?:is|would\s+be)?\s*[:\-]?\s*[\(\[]?([A-Pa-p])[\)\]\.,:]?(?:\s|$)",
|
| 57 |
+
re.IGNORECASE)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _wide(options):
|
| 61 |
+
return isinstance(options, (list, tuple)) and len(options) > 10
|
| 62 |
+
# non-negative decimal number (timestamps/counts); '-' is treated as a
|
| 63 |
+
# separator ("10-20"), not a sign
|
| 64 |
+
_NUM = re.compile(r"\d+(?:\.\d+)?")
|
| 65 |
+
# "is/are/answer(ed)/total/count ... N" — preferred counting extraction
|
| 66 |
+
_NUM_STATED = re.compile(
|
| 67 |
+
r"(?:\bis\b|\bare\b|\banswer\b|\banswered\b|\btotal\b|\bcount\b)"
|
| 68 |
+
r"[^0-9\n]{0,20}?(\d+(?:\.\d+)?)", re.IGNORECASE)
|
| 69 |
+
# standalone number (not part of a word/identifier like "f16" or "1st")
|
| 70 |
+
_NUM_ALONE = re.compile(r"(?<![\w.])(\d+(?:\.\d+)?)(?![\w])")
|
| 71 |
+
|
| 72 |
+
FREETEXT_MIN_WORDS = 10 # gold this long cannot be scored by exact match
|
| 73 |
+
IOU_THRESHOLD = 0.5 # temporal grounding R@0.5
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _pre(s):
|
| 77 |
+
"""Light normalization before letter extraction: full-width punctuation
|
| 78 |
+
and markdown emphasis defeat the regexes ('(C)', '**C**', 'C。')."""
|
| 79 |
+
s = str(s)
|
| 80 |
+
s = s.replace("(", "(").replace(")", ")").replace(":", ":")
|
| 81 |
+
s = s.replace("。", ".").replace(",", ",")
|
| 82 |
+
return s.replace("*", "").replace("#", "")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def norm_text(s):
|
| 86 |
+
s = str(s).strip().lower()
|
| 87 |
+
s = re.sub(r"[‘’“”`]", "'", s)
|
| 88 |
+
s = re.sub(r"[^\w\s.\-]", " ", s) # keep word chars, '.', '-' (numbers)
|
| 89 |
+
s = re.sub(r"\s+", " ", s).strip()
|
| 90 |
+
return s.strip(".").strip()
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def num_seq(s):
|
| 94 |
+
"""Parse s as a pure sequence of numbers, else None."""
|
| 95 |
+
toks = re.sub(r"[\[\](){},;:]", " ", str(s)).split()
|
| 96 |
+
if not toks:
|
| 97 |
+
return None
|
| 98 |
+
out = []
|
| 99 |
+
for t in toks:
|
| 100 |
+
try:
|
| 101 |
+
out.append(float(t))
|
| 102 |
+
except ValueError:
|
| 103 |
+
return None
|
| 104 |
+
return out
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def coerce_options(options):
|
| 108 |
+
"""Normalize an options field to a list (or None). The data contract
|
| 109 |
+
allows list|str|null; live str shapes: JSON dict '{"A": "Yes", ...}',
|
| 110 |
+
python-list repr, and newline 'A. ...' blocks."""
|
| 111 |
+
if options is None:
|
| 112 |
+
return None
|
| 113 |
+
if isinstance(options, (list, tuple)):
|
| 114 |
+
return list(options)
|
| 115 |
+
s = str(options).strip()
|
| 116 |
+
if not s:
|
| 117 |
+
return None
|
| 118 |
+
for parser in (json.loads, ast.literal_eval):
|
| 119 |
+
try:
|
| 120 |
+
v = parser(s)
|
| 121 |
+
except Exception:
|
| 122 |
+
continue
|
| 123 |
+
if isinstance(v, dict) and v:
|
| 124 |
+
# {'A': 'Yes', 'B': 'No'} -> values ordered by (letter) key
|
| 125 |
+
return [f"{k}. {v[k]}" for k in sorted(v, key=lambda x: str(x))]
|
| 126 |
+
if isinstance(v, (list, tuple)) and v:
|
| 127 |
+
return [str(x) for x in v]
|
| 128 |
+
lines = [l.strip() for l in s.splitlines() if l.strip()]
|
| 129 |
+
if len(lines) >= 2 and sum(
|
| 130 |
+
bool(re.match(r"^\(?[A-J][).:\.]\s*", l)) for l in lines) >= 2:
|
| 131 |
+
return lines
|
| 132 |
+
return None
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _strip_letter_prefix(opt):
|
| 136 |
+
return re.sub(r"^\s*[\(\[]?[A-Ja-j][\)\]\.,:]\s+", "", str(opt)).strip()
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def mcq_letter(s, options=None):
|
| 140 |
+
"""Extract an option letter from a prediction / gold answer."""
|
| 141 |
+
if s is None:
|
| 142 |
+
return None
|
| 143 |
+
s = _pre(s).strip()
|
| 144 |
+
options = coerce_options(options)
|
| 145 |
+
wide = _wide(options)
|
| 146 |
+
m = (_LEAD_X if wide else _LEAD).match(s)
|
| 147 |
+
if m:
|
| 148 |
+
letter = m.group(1).upper()
|
| 149 |
+
# bare 'A '/'I ' followed by more words is usually the article/pronoun
|
| 150 |
+
# ('A man walks...', 'I think...'), not the option letter: only accept
|
| 151 |
+
# it with an explicit delimiter or when the pred is the letter alone.
|
| 152 |
+
has_delim = any(ch in m.group(0) for ch in "()[].,:")
|
| 153 |
+
if has_delim or letter not in ("A", "I") or len(s.split()) == 1:
|
| 154 |
+
return letter
|
| 155 |
+
ms = (list((_STATED_X if wide else _STATED).finditer(s))
|
| 156 |
+
or list(_STATED_CN.finditer(s)))
|
| 157 |
+
if ms:
|
| 158 |
+
return ms[-1].group(1).upper()
|
| 159 |
+
if options:
|
| 160 |
+
ns = norm_text(s)
|
| 161 |
+
for i, opt in enumerate(options):
|
| 162 |
+
if ns and ns in (norm_text(opt), norm_text(_strip_letter_prefix(opt))):
|
| 163 |
+
return chr(65 + i)
|
| 164 |
+
# option text stated followed by explanation: containment, but only
|
| 165 |
+
# when EXACTLY ONE option matches (ambiguous containment stays None)
|
| 166 |
+
flat = lambda t: re.sub(r"\s+", " ", re.sub(r"[.\-]", " ", t)).strip()
|
| 167 |
+
nsf = flat(ns)
|
| 168 |
+
hits = []
|
| 169 |
+
for i, opt in enumerate(options):
|
| 170 |
+
ot = flat(norm_text(_strip_letter_prefix(opt)))
|
| 171 |
+
if ot and len(ot) >= 3 and f" {ot} " in f" {nsf} ":
|
| 172 |
+
hits.append(i)
|
| 173 |
+
if len(hits) == 1:
|
| 174 |
+
return chr(65 + hits[0])
|
| 175 |
+
# bare numeric index into options ("0" -> A); text match takes priority
|
| 176 |
+
if re.fullmatch(r"\d{1,2}", s) and int(s) < len(options):
|
| 177 |
+
return chr(65 + int(s))
|
| 178 |
+
return None
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _letter_set(s, wide=False):
|
| 182 |
+
"""Letters of a multi-select answer. Strict comma form first; otherwise
|
| 183 |
+
uppercase standalone letters ("The artifacts are A and C" -> {A, C}).
|
| 184 |
+
In the loose fallback 'I' is excluded (almost always the pronoun).
|
| 185 |
+
wide=True widens the alphabet to A-P (benches with >10 options)."""
|
| 186 |
+
s = _pre(s)
|
| 187 |
+
if (_MULTI_X if wide else _MULTI).match(s):
|
| 188 |
+
return {c.upper() for c in re.findall(r"[A-Pa-p]" if wide else r"[A-Ja-j]", s)}
|
| 189 |
+
toks = [t for t in re.findall(r"\b([A-P])\b" if wide else r"\b([A-J])\b", s)
|
| 190 |
+
if t != "I"]
|
| 191 |
+
return set(toks) if toks else None
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def parse_interval(s):
|
| 195 |
+
"""(start, end) when s parses as exactly two numbers, else None."""
|
| 196 |
+
ns = num_seq(s)
|
| 197 |
+
if ns is not None and len(ns) == 2:
|
| 198 |
+
return (ns[0], ns[1])
|
| 199 |
+
return None
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def extract_pred_interval(pred):
|
| 203 |
+
"""First two non-negative floats in pred ('from 10.5 to 20s' -> (10.5, 20))."""
|
| 204 |
+
nums = _NUM.findall(str(pred))
|
| 205 |
+
if len(nums) < 2:
|
| 206 |
+
return None
|
| 207 |
+
return (float(nums[0]), float(nums[1]))
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def interval_iou(a, b):
|
| 211 |
+
"""Temporal IoU of two (start, end) intervals (order-normalized)."""
|
| 212 |
+
a = (min(a), max(a))
|
| 213 |
+
b = (min(b), max(b))
|
| 214 |
+
inter = max(0.0, min(a[1], b[1]) - max(a[0], b[0]))
|
| 215 |
+
union = max(a[1], b[1]) - min(a[0], b[0])
|
| 216 |
+
if union <= 0: # both degenerate points
|
| 217 |
+
return 1.0 if abs(a[0] - b[0]) <= 1e-6 else 0.0
|
| 218 |
+
return inter / union
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def extract_pred_number(pred):
|
| 222 |
+
"""Number stated in a verbose prediction; 'is/are/answer: N' pattern
|
| 223 |
+
preferred (last such match), else the last standalone number."""
|
| 224 |
+
s = str(pred).replace(",", "") # '1,234' -> '1234'
|
| 225 |
+
ms = _NUM_STATED.findall(s)
|
| 226 |
+
if ms:
|
| 227 |
+
return float(ms[-1])
|
| 228 |
+
ms = _NUM_ALONE.findall(s)
|
| 229 |
+
if ms:
|
| 230 |
+
return float(ms[-1])
|
| 231 |
+
return None
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def score(pred, answer, options=None, question_format=None):
|
| 235 |
+
"""True/False = rule-scored; None = NOT rule-scorable (free-text gold).
|
| 236 |
+
Callers must treat None as NA — excluded from accuracy, never 'wrong'."""
|
| 237 |
+
if pred is None or answer is None:
|
| 238 |
+
return False
|
| 239 |
+
options = coerce_options(options)
|
| 240 |
+
wide = _wide(options)
|
| 241 |
+
if (_MULTI_X if wide else _MULTI).match(_pre(answer)): # multi-select gold "A,B,C"
|
| 242 |
+
return _letter_set(pred, wide) == _letter_set(answer, wide)
|
| 243 |
+
is_mcq = ((question_format or "").strip().upper() == "MCQ"
|
| 244 |
+
or (isinstance(options, (list, tuple)) and len(options) >= 2))
|
| 245 |
+
if is_mcq and isinstance(options, (list, tuple)) and options:
|
| 246 |
+
pl = mcq_letter(pred, options)
|
| 247 |
+
al = mcq_letter(answer, options)
|
| 248 |
+
if pl and al:
|
| 249 |
+
return pl == al
|
| 250 |
+
# one side unresolvable -> compare texts (resolve letters to option text)
|
| 251 |
+
ptxt = (norm_text(_strip_letter_prefix(options[ord(pl) - 65]))
|
| 252 |
+
if pl and ord(pl) - 65 < len(options) else norm_text(pred))
|
| 253 |
+
atxt = (norm_text(_strip_letter_prefix(options[ord(al) - 65]))
|
| 254 |
+
if al and ord(al) - 65 < len(options) else norm_text(answer))
|
| 255 |
+
return bool(ptxt) and ptxt == atxt
|
| 256 |
+
if is_mcq: # MCQ without an options list: letter-vs-letter if possible
|
| 257 |
+
pl, al = mcq_letter(pred), mcq_letter(answer)
|
| 258 |
+
if pl and al:
|
| 259 |
+
return pl == al
|
| 260 |
+
# ---- temporal grounding: gold is exactly two floats -> IoU >= 0.5
|
| 261 |
+
gold_iv = parse_interval(answer)
|
| 262 |
+
if gold_iv is not None:
|
| 263 |
+
pred_iv = (parse_interval(pred) if num_seq(pred) is not None
|
| 264 |
+
else extract_pred_interval(pred))
|
| 265 |
+
if pred_iv is not None:
|
| 266 |
+
return interval_iou(pred_iv, gold_iv) >= IOU_THRESHOLD
|
| 267 |
+
return bool(norm_text(pred)) and norm_text(pred) == norm_text(answer)
|
| 268 |
+
pn, an = num_seq(pred), num_seq(answer)
|
| 269 |
+
if pn is not None and an is not None:
|
| 270 |
+
return len(pn) == len(an) and all(abs(a - b) <= 1e-6 for a, b in zip(pn, an))
|
| 271 |
+
# ---- counting/numeric gold with a verbose prediction: extract the number
|
| 272 |
+
if an is not None and len(an) == 1:
|
| 273 |
+
pv = extract_pred_number(pred)
|
| 274 |
+
if pv is not None:
|
| 275 |
+
return abs(pv - an[0]) <= 1e-6
|
| 276 |
+
return bool(norm_text(pred)) and norm_text(pred) == norm_text(answer)
|
| 277 |
+
# ---- long free-text gold: not rule-scorable -> NA
|
| 278 |
+
if len(norm_text(answer).split()) >= FREETEXT_MIN_WORDS:
|
| 279 |
+
return None
|
| 280 |
+
return bool(norm_text(pred)) and norm_text(pred) == norm_text(answer)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def chance_level(num_options, has_chance_level):
|
| 284 |
+
flag = str(has_chance_level).strip().lower()
|
| 285 |
+
if flag not in ("true", "1", "yes"):
|
| 286 |
+
return None
|
| 287 |
+
ns = [int(x) for x in re.findall(r"\d+", str(num_options or "")) if int(x) > 0]
|
| 288 |
+
if not ns:
|
| 289 |
+
return None
|
| 290 |
+
return sum(1.0 / n for n in ns) / len(ns)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
# ---------------------------------------------------------------- self-test
|
| 294 |
+
def _selftest():
|
| 295 |
+
OPTS = ["Holding something", "Releasing something", "Not sure"]
|
| 296 |
+
LOPTS = ["A. Turn right and walk.", "B. Turn left and walk.", "C. Stay put."]
|
| 297 |
+
cases = [
|
| 298 |
+
# (pred, answer, options, fmt, expected)
|
| 299 |
+
("B", "B", LOPTS, "MCQ", True), # bare letter
|
| 300 |
+
("(B)", "B", LOPTS, "MCQ", True), # parenthesized
|
| 301 |
+
("b) Turn left and walk.", "B", LOPTS, "MCQ", True), # lowercase + text
|
| 302 |
+
("B.", "C", LOPTS, "MCQ", False), # wrong letter
|
| 303 |
+
("The answer is (C)", "C", LOPTS, "MCQ", True), # stated answer
|
| 304 |
+
("Answer: A", "A. Turn right and walk.", LOPTS, "MCQ", True), # gold has text
|
| 305 |
+
("Turn left and walk.", "B", LOPTS, "MCQ", True), # pred is option text
|
| 306 |
+
("Releasing something", "Releasing something", OPTS, "mixed", True), # unlabeled opts
|
| 307 |
+
("A", "Holding something", OPTS, "MCQ", True), # letter vs option text
|
| 308 |
+
("B", "Holding something", OPTS, "MCQ", False),
|
| 309 |
+
("As shown, people run.", "C", LOPTS, "MCQ", False), # 'As' is not letter A
|
| 310 |
+
("Not sure.", "Not sure", OPTS, "MCQ", True), # trailing period
|
| 311 |
+
# numeric index answers ("0" -> options[0]); text match has priority
|
| 312 |
+
("A", "0", OPTS, "MCQ", True), # gold is index
|
| 313 |
+
("Holding something", "0", OPTS, "MCQ", True), # pred text vs gold index
|
| 314 |
+
("B", "0", OPTS, "MCQ", False),
|
| 315 |
+
("1", "B", ["cat", "dog", "fox"], "MCQ", True), # pred is index
|
| 316 |
+
("3", "5", ["5", "3", "1"], "MCQ", False), # "3" is option text (B), not index
|
| 317 |
+
# multi-select "A,B,C": normalized letter-set equality
|
| 318 |
+
("A,C", "C, A", LOPTS, "MCQ", True),
|
| 319 |
+
("B, A and C", "A,B,C", None, "MCQ", True),
|
| 320 |
+
("The artifacts are A and C.", "A,C", None, "MCQ", True),
|
| 321 |
+
("A", "A,B", None, "MCQ", False),
|
| 322 |
+
("A,B,C", "A,B", None, "MCQ", False),
|
| 323 |
+
# non-MCQ text
|
| 324 |
+
(" Yes. ", "yes", None, "open", True),
|
| 325 |
+
("A dog", "a dog!", None, "open", True),
|
| 326 |
+
("dog", "cat", None, "open", False),
|
| 327 |
+
("", "cat", None, "open", False), # empty pred never correct
|
| 328 |
+
# numeric equivalence
|
| 329 |
+
("5", "5.0", None, "numeric", True),
|
| 330 |
+
("5", "6", None, "numeric", False),
|
| 331 |
+
# ---- letter-extraction robustness (review fixes) -----------------
|
| 332 |
+
("I think the answer is B", "B", LOPTS, "MCQ", True), # 'I' not letter I
|
| 333 |
+
("A man walks by; the answer is C", "C", LOPTS, "MCQ", True),
|
| 334 |
+
("A man walks in the park.", "A", LOPTS, "MCQ", False), # article, no signal
|
| 335 |
+
("**C**", "C", LOPTS, "MCQ", True), # markdown bold
|
| 336 |
+
("(C)", "C", LOPTS, "MCQ", True), # full-width parens
|
| 337 |
+
("C。", "C", LOPTS, "MCQ", True), # full-width period
|
| 338 |
+
("答案是C", "C", LOPTS, "MCQ", True), # Chinese stated
|
| 339 |
+
("Option A is wrong. The answer is B.", "B", LOPTS, "MCQ", True), # last stated wins
|
| 340 |
+
("Turn left and walk. That matches what happens.", "B", LOPTS, "MCQ", True), # opt text + explanation
|
| 341 |
+
("The artifacts I see are A and C.", "A,C", None, "MCQ", True), # 'I' in multi-select prose
|
| 342 |
+
# str-typed options are coerced
|
| 343 |
+
("A", "A", '{"A": "Yes", "B": "No"}', "MCQ", True),
|
| 344 |
+
("Yes", "A", '{"A": "Yes", "B": "No"}', "MCQ", True),
|
| 345 |
+
("B", "A", "['Yes', 'No']", None, False),
|
| 346 |
+
# ---- temporal grounding: IoU >= 0.5 (R@0.5) ----------------------
|
| 347 |
+
("0, 12.6", "[ 0. 12.6]", None, "grounding", True), # exact interval
|
| 348 |
+
("0.0 12.0", "[ 0. 12.6]", None, "grounding", True), # IoU 0.95
|
| 349 |
+
("From 10.2 to 20.5 seconds.", "[10, 21]", None, "grounding", True),
|
| 350 |
+
("5 - 8", "[20, 30]", None, "grounding", False), # IoU 0
|
| 351 |
+
("10-20", "[12, 22]", None, "grounding", True), # '-' as separator, IoU 0.67
|
| 352 |
+
("around 14", "[10, 20]", None, "grounding", False), # one float -> exact fallback
|
| 353 |
+
("2702 2715", "[2702. 2715.]", None, "grounding", True), # numpy repr gold
|
| 354 |
+
("[21, 39]", "[21, 39]", None, "open", True),
|
| 355 |
+
("22 38", "[21, 39]", None, "open", True), # IoU 16/18
|
| 356 |
+
# ---- counting: extract the number from a sentence ----------------
|
| 357 |
+
("There are 13 repetitions.", "13", None, "numeric", True),
|
| 358 |
+
("The person does 12 push-ups in total, so the answer is 12.", "12", None, "numeric", True),
|
| 359 |
+
("I counted 5 pull-ups and then 7 squats.", "7", None, "numeric", True), # last standalone
|
| 360 |
+
("The count is 27.", "27", None, "open", True),
|
| 361 |
+
("approximately 14.1 meters", "14.10", None, "open", True),
|
| 362 |
+
("There are 5 people.", "6", None, "numeric", False),
|
| 363 |
+
("many repetitions", "13", None, "numeric", False), # no number -> exact fallback
|
| 364 |
+
("13", "13", None, "numeric", True),
|
| 365 |
+
# ---- long free-text gold -> None (NA, not rule-scorable) ---------
|
| 366 |
+
("some answer", "A woman wearing a white coat and black pants attacks "
|
| 367 |
+
"a public trash can with her feet on the street", None, "open", None),
|
| 368 |
+
("the man opens the door", "the man opens the door", None, "open", True),
|
| 369 |
+
]
|
| 370 |
+
for i, (p, a, o, f, want) in enumerate(cases):
|
| 371 |
+
got = score(p, a, o, f)
|
| 372 |
+
assert got is want if want is None else got == want, \
|
| 373 |
+
f"case {i}: score({p!r}, {a!r}) = {got}, want {want}"
|
| 374 |
+
assert chance_level("4", "True") == 0.25
|
| 375 |
+
assert chance_level("4 or 6", "True") == (0.25 + 1 / 6) / 2
|
| 376 |
+
assert chance_level("NA", "True") is None
|
| 377 |
+
assert chance_level("4", "False") is None
|
| 378 |
+
assert chance_level("", True) is None
|
| 379 |
+
assert abs(chance_level(5, True) - 0.2) < 1e-9
|
| 380 |
+
# coerce_options shapes
|
| 381 |
+
assert coerce_options('{"A": "Yes", "B": "No"}') == ["A. Yes", "B. No"]
|
| 382 |
+
assert coerce_options("['x', 'y']") == ["x", "y"]
|
| 383 |
+
assert coerce_options("A. foo\nB. bar\nC. baz") == ["A. foo", "B. bar", "C. baz"]
|
| 384 |
+
assert coerce_options("free text blob") is None
|
| 385 |
+
assert coerce_options(None) is None
|
| 386 |
+
assert coerce_options(["a", "b"]) == ["a", "b"]
|
| 387 |
+
# interval helpers
|
| 388 |
+
assert parse_interval("[ 0. 12.6]") == (0.0, 12.6)
|
| 389 |
+
assert parse_interval("12") is None
|
| 390 |
+
assert extract_pred_interval("from 3.5s to 9s") == (3.5, 9.0)
|
| 391 |
+
assert abs(interval_iou((0, 10), (5, 15)) - 1 / 3) < 1e-9
|
| 392 |
+
assert extract_pred_number("the answer is 42.") == 42.0
|
| 393 |
+
assert extract_pred_number("no digits here") is None
|
| 394 |
+
print(f"scoring selftest: {len(cases)} score cases + option/interval/"
|
| 395 |
+
f"number helper cases OK")
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
if __name__ == "__main__":
|
| 399 |
+
_selftest()
|
steps456_20260910/code/exp/pipeline/stage_d_blind.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stage D — blind condition: question+options only, NO video. Runs locally
|
| 2 |
+
(API keys in env). Results: exp/results/blind/<bench>__<model>.jsonl, resumable.
|
| 3 |
+
Usage: python stage_d_blind.py --model goldmane [--bench NAME] [--limit N]
|
| 4 |
+
|
| 5 |
+
--options-only (N0.2, option-level attacker of the paper): the prompt carries
|
| 6 |
+
ONLY the option list of the item — no question, no video — and asks for the
|
| 7 |
+
letter of the most likely correct option. Items without an option list are
|
| 8 |
+
skipped (counted per bench). The option list is taken from the sample's
|
| 9 |
+
`options` field (scoring.coerce_options); when that field is absent the
|
| 10 |
+
lettered option lines embedded in the question text are used (>= 2 lines
|
| 11 |
+
"(A) ..." / "A. ..." / "A: ..." / "A) ..." with consecutive letters from A) and
|
| 12 |
+
the row records opts_source="question". Options without a letter prefix are
|
| 13 |
+
rendered as "A. ...", "B. ...". Same client/routing/retry as the blind mode.
|
| 14 |
+
Results: <E1_RESULTS_DIR or exp/results>/options_only/<bench>__<model>.jsonl,
|
| 15 |
+
same row schema (qid, pred, answer) plus opts_source and n_options.
|
| 16 |
+
|
| 17 |
+
Routing: "claude" in model -> Anthropic Messages API, else Gemini
|
| 18 |
+
generateContent (covers gemini-* and internal model names like goldmane).
|
| 19 |
+
Gemini thinking models: skip parts flagged "thought", join the rest; on
|
| 20 |
+
MAX_TOKENS with no visible text retry once with a larger budget.
|
| 21 |
+
429/5xx/network errors back off exponentially (honoring retry-after).
|
| 22 |
+
"""
|
| 23 |
+
import argparse
|
| 24 |
+
import glob
|
| 25 |
+
import json
|
| 26 |
+
import os
|
| 27 |
+
import random
|
| 28 |
+
import re
|
| 29 |
+
import sys
|
| 30 |
+
import time
|
| 31 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 32 |
+
|
| 33 |
+
import requests
|
| 34 |
+
|
| 35 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 36 |
+
from scoring import coerce_options # noqa: E402
|
| 37 |
+
|
| 38 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 39 |
+
SAMPLES = os.environ.get("E1_SAMPLES_DIR") or os.path.join(HERE, "..", "data", "samples") # override: N1 new-benchmark E1 runs
|
| 40 |
+
RESULTS = os.environ.get("E1_RESULTS_DIR") or os.path.join(HERE, "..", "results")
|
| 41 |
+
OUT = os.path.join(RESULTS, "blind") # replaced by main() for --options-only
|
| 42 |
+
|
| 43 |
+
PROMPT = ("You will answer a question about a video WITHOUT seeing the video. "
|
| 44 |
+
"Guess the most likely answer from the question and options alone.\n\n"
|
| 45 |
+
"Question: {q}\n{opts}\n"
|
| 46 |
+
"Reply with ONLY the option letter (or the exact short answer if no options).")
|
| 47 |
+
|
| 48 |
+
PROMPT_OPTIONS_ONLY = (
|
| 49 |
+
"You will see ONLY the answer options of a multiple-choice question about a video. "
|
| 50 |
+
"The question and the video are not shown. Choose the option that is most likely "
|
| 51 |
+
"to be the correct answer.\n\nOptions:\n{opts}\n\n"
|
| 52 |
+
"Reply with ONLY the option letter.")
|
| 53 |
+
|
| 54 |
+
MAX_ATTEMPTS = 5
|
| 55 |
+
|
| 56 |
+
# lettered option line: "(A) text" / "A. text" / "A: text" / "A) text" / "[A] text"
|
| 57 |
+
_OPT_LINE = re.compile(r"^\s*[\(\[]?([A-P])[\)\]\.:]\s*(\S.*)?$")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def embedded_options(question):
|
| 61 |
+
"""Option lines embedded in the question text, in order, or None.
|
| 62 |
+
Requires >= 2 lines whose letters run consecutively from A."""
|
| 63 |
+
out = []
|
| 64 |
+
for line in str(question or "").splitlines():
|
| 65 |
+
m = _OPT_LINE.match(line)
|
| 66 |
+
if m and m.group(1) == chr(65 + len(out)):
|
| 67 |
+
out.append(line.strip())
|
| 68 |
+
elif m and out:
|
| 69 |
+
break
|
| 70 |
+
return out if len(out) >= 2 else None
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def item_options(row):
|
| 74 |
+
"""(option list, source) for an item; source in {"list", "question"}; (None, None)
|
| 75 |
+
when the item carries no option list anywhere."""
|
| 76 |
+
opts = coerce_options(row.get("options"))
|
| 77 |
+
if opts and len(opts) >= 2:
|
| 78 |
+
return opts, "list"
|
| 79 |
+
emb = embedded_options(row.get("question"))
|
| 80 |
+
if emb:
|
| 81 |
+
return emb, "question"
|
| 82 |
+
return None, None
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def lettered(opts):
|
| 86 |
+
"""Render options one per line with a letter prefix; keep existing prefixes."""
|
| 87 |
+
if all(_OPT_LINE.match(str(o)) for o in opts):
|
| 88 |
+
return "\n".join(str(o).strip() for o in opts)
|
| 89 |
+
return "\n".join(f"{chr(65 + i)}. {str(o).strip()}" for i, o in enumerate(opts))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def log(msg):
|
| 93 |
+
print(f"[D-blind] {msg}", file=sys.stderr, flush=True)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class Retryable(Exception):
|
| 97 |
+
"""429 / 5xx / network — worth backing off and retrying."""
|
| 98 |
+
|
| 99 |
+
def __init__(self, msg, wait=None):
|
| 100 |
+
super().__init__(msg)
|
| 101 |
+
self.wait = wait
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def fmt_opts(o):
|
| 105 |
+
if not o:
|
| 106 |
+
return ""
|
| 107 |
+
if isinstance(o, str):
|
| 108 |
+
return o
|
| 109 |
+
return "\n".join(str(x) for x in o)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _check_http(r):
|
| 113 |
+
if r.status_code == 429 or r.status_code >= 500:
|
| 114 |
+
wait = None
|
| 115 |
+
ra = r.headers.get("retry-after")
|
| 116 |
+
if ra:
|
| 117 |
+
try:
|
| 118 |
+
wait = min(120.0, float(ra))
|
| 119 |
+
except ValueError:
|
| 120 |
+
pass
|
| 121 |
+
raise Retryable(f"HTTP {r.status_code}: {r.text[:150]}", wait=wait)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _gemini_call(model, prompt, budget):
|
| 125 |
+
try:
|
| 126 |
+
r = requests.post(
|
| 127 |
+
f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent",
|
| 128 |
+
headers={"x-goog-api-key": os.environ["GEMINI_API_KEY"]},
|
| 129 |
+
json={"contents": [{"parts": [{"text": prompt}]}],
|
| 130 |
+
"generationConfig": {"maxOutputTokens": budget}},
|
| 131 |
+
timeout=120)
|
| 132 |
+
except requests.RequestException as e:
|
| 133 |
+
raise Retryable(f"net: {type(e).__name__}")
|
| 134 |
+
_check_http(r)
|
| 135 |
+
d = r.json()
|
| 136 |
+
if "candidates" not in d:
|
| 137 |
+
raise RuntimeError(f"no candidates: {str(d.get('error', d))[:250]}")
|
| 138 |
+
c = d["candidates"][0]
|
| 139 |
+
parts = (c.get("content") or {}).get("parts") or []
|
| 140 |
+
# thinking models: parts may open with {"thought": true} segments — skip
|
| 141 |
+
# them and join the visible remainder.
|
| 142 |
+
text = "".join(p.get("text", "") for p in parts if not p.get("thought")).strip()
|
| 143 |
+
return text, c.get("finishReason", "")
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def ask_gemini(model, prompt):
|
| 147 |
+
text, fin = _gemini_call(model, prompt, 4096)
|
| 148 |
+
if not text and fin == "MAX_TOKENS":
|
| 149 |
+
# thinking ate the whole budget -> no visible parts; give it headroom
|
| 150 |
+
text, fin = _gemini_call(model, prompt, 8192)
|
| 151 |
+
if not text:
|
| 152 |
+
raise RuntimeError(f"empty answer (finishReason={fin})")
|
| 153 |
+
return text
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _claude_call(model, prompt, max_tokens):
|
| 157 |
+
try:
|
| 158 |
+
r = requests.post(
|
| 159 |
+
"https://api.anthropic.com/v1/messages",
|
| 160 |
+
headers={"x-api-key": os.environ["ANTHROPIC_API_KEY"],
|
| 161 |
+
"anthropic-version": "2023-06-01"},
|
| 162 |
+
json={"model": model, "max_tokens": max_tokens,
|
| 163 |
+
"output_config": {"effort": "low"},
|
| 164 |
+
"messages": [{"role": "user", "content": prompt}]},
|
| 165 |
+
timeout=180)
|
| 166 |
+
except requests.RequestException as e:
|
| 167 |
+
raise Retryable(f"net: {type(e).__name__}")
|
| 168 |
+
_check_http(r)
|
| 169 |
+
d = r.json()
|
| 170 |
+
if "content" not in d:
|
| 171 |
+
raise RuntimeError(str(d.get("error", d))[:250])
|
| 172 |
+
# content blocks: skip "thinking" blocks, take the text block
|
| 173 |
+
text = next((b.get("text", "") for b in d["content"]
|
| 174 |
+
if b.get("type") == "text"), "").strip()
|
| 175 |
+
return text, d.get("stop_reason", "")
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def ask_claude(model, prompt):
|
| 179 |
+
text, stop = _claude_call(model, prompt, 1024)
|
| 180 |
+
if not text and stop == "max_tokens":
|
| 181 |
+
# thinking + answer exceeded the cap -> no text block; raise the cap
|
| 182 |
+
text, stop = _claude_call(model, prompt, 4096)
|
| 183 |
+
if not text:
|
| 184 |
+
raise RuntimeError(f"empty answer (stop_reason={stop})")
|
| 185 |
+
return text
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def make_prompt(row, options_only=False):
|
| 189 |
+
"""Prompt for one item; None when --options-only and the item has no option list."""
|
| 190 |
+
if not options_only:
|
| 191 |
+
return PROMPT.format(q=row["question"], opts=fmt_opts(row.get("options")))
|
| 192 |
+
opts, _ = item_options(row)
|
| 193 |
+
if not opts:
|
| 194 |
+
return None
|
| 195 |
+
return PROMPT_OPTIONS_ONLY.format(opts=lettered(opts))
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def ask_with_retry(ask, model, row, bench, errlog, options_only=False):
|
| 199 |
+
"""Returns pred text or None (after logging) — never raises."""
|
| 200 |
+
prompt = make_prompt(row, options_only)
|
| 201 |
+
if prompt is None:
|
| 202 |
+
return None
|
| 203 |
+
for attempt in range(MAX_ATTEMPTS):
|
| 204 |
+
try:
|
| 205 |
+
return ask(model, prompt)
|
| 206 |
+
except Retryable as e:
|
| 207 |
+
if attempt == MAX_ATTEMPTS - 1:
|
| 208 |
+
errlog(f"{bench}/{row['qid']}: gave up after {MAX_ATTEMPTS} tries: {e}")
|
| 209 |
+
return None
|
| 210 |
+
wait = e.wait if e.wait else min(60.0, 2.0 ** attempt + random.uniform(0, 2))
|
| 211 |
+
if attempt >= 1:
|
| 212 |
+
log(f"{bench}/{row['qid']}: retry {attempt + 1} in {wait:.0f}s ({str(e)[:80]})")
|
| 213 |
+
time.sleep(wait)
|
| 214 |
+
except Exception as e:
|
| 215 |
+
if attempt >= 1: # parse/4xx: one flake allowance, then surface
|
| 216 |
+
errlog(f"{bench}/{row['qid']}: {type(e).__name__}: {str(e)[:200]}")
|
| 217 |
+
return None
|
| 218 |
+
time.sleep(2)
|
| 219 |
+
return None
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def run_bench(path, model, limit, options_only=False):
|
| 223 |
+
bench = os.path.basename(path)[:-6]
|
| 224 |
+
os.makedirs(OUT, exist_ok=True)
|
| 225 |
+
outp = os.path.join(OUT, f"{bench}__{model.replace('/', '_')}.jsonl")
|
| 226 |
+
done = set()
|
| 227 |
+
if os.path.exists(outp):
|
| 228 |
+
for l in open(outp):
|
| 229 |
+
try:
|
| 230 |
+
done.add(json.loads(l)["qid"])
|
| 231 |
+
except Exception:
|
| 232 |
+
pass
|
| 233 |
+
rows = [json.loads(l) for l in open(path) if l.strip()]
|
| 234 |
+
if limit:
|
| 235 |
+
rows = rows[:limit]
|
| 236 |
+
todo = [r for r in rows if r["qid"] not in done]
|
| 237 |
+
n_skip = 0
|
| 238 |
+
if options_only: # items without any option list cannot be probed
|
| 239 |
+
n_skip = sum(1 for r in todo if item_options(r)[0] is None)
|
| 240 |
+
todo = [r for r in todo if item_options(r)[0] is not None]
|
| 241 |
+
if n_skip:
|
| 242 |
+
log(f"{bench}: {n_skip} item(s) without an option list skipped")
|
| 243 |
+
if not todo:
|
| 244 |
+
return bench, 0, 0, len(rows)
|
| 245 |
+
ask = ask_claude if "claude" in model else ask_gemini
|
| 246 |
+
|
| 247 |
+
n_logged = [0]
|
| 248 |
+
|
| 249 |
+
def errlog(msg):
|
| 250 |
+
n_logged[0] += 1
|
| 251 |
+
if n_logged[0] <= 8:
|
| 252 |
+
log(msg)
|
| 253 |
+
elif n_logged[0] == 9:
|
| 254 |
+
log(f"{bench}: more errors — suppressing further per-row logs")
|
| 255 |
+
|
| 256 |
+
n_new = n_err = 0
|
| 257 |
+
with open(outp, "a") as f:
|
| 258 |
+
for i, r in enumerate(todo):
|
| 259 |
+
pred = ask_with_retry(ask, model, r, bench, errlog, options_only)
|
| 260 |
+
if pred is None:
|
| 261 |
+
n_err += 1
|
| 262 |
+
else:
|
| 263 |
+
out = dict(qid=r["qid"], pred=pred[:300], answer=r.get("answer", ""))
|
| 264 |
+
if options_only:
|
| 265 |
+
opts, src = item_options(r)
|
| 266 |
+
out.update(opts_source=src, n_options=len(opts))
|
| 267 |
+
f.write(json.dumps(out, ensure_ascii=False) + "\n")
|
| 268 |
+
f.flush()
|
| 269 |
+
n_new += 1
|
| 270 |
+
if (i + 1) % 50 == 0:
|
| 271 |
+
log(f"{bench}: {i + 1}/{len(todo)} (ok={n_new} err={n_err})")
|
| 272 |
+
return bench, n_new, n_err, len(rows)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def select_files(files, spec):
|
| 276 |
+
"""--bench selector: "|"-separated names; exact sample basenames win, and only when
|
| 277 |
+
no token matches exactly does the historical substring rule apply."""
|
| 278 |
+
if not spec:
|
| 279 |
+
return files
|
| 280 |
+
toks = [t.strip() for t in spec.split("|") if t.strip()]
|
| 281 |
+
exact = [f for f in files if os.path.basename(f)[:-6] in toks]
|
| 282 |
+
return exact or [f for f in files if any(t in f for t in toks)]
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def main():
|
| 286 |
+
ap = argparse.ArgumentParser()
|
| 287 |
+
ap.add_argument("--model", required=True)
|
| 288 |
+
ap.add_argument("--bench", default=None)
|
| 289 |
+
ap.add_argument("--limit", type=int, default=None)
|
| 290 |
+
ap.add_argument("--workers", type=int, default=6)
|
| 291 |
+
ap.add_argument("--options-only", action="store_true",
|
| 292 |
+
help="N0.2 option-level attacker: options list only, no question "
|
| 293 |
+
"(-> <results>/options_only/)")
|
| 294 |
+
a = ap.parse_args()
|
| 295 |
+
global OUT
|
| 296 |
+
if a.options_only:
|
| 297 |
+
OUT = os.path.join(RESULTS, "options_only")
|
| 298 |
+
key = "ANTHROPIC_API_KEY" if "claude" in a.model else "GEMINI_API_KEY"
|
| 299 |
+
if not os.environ.get(key):
|
| 300 |
+
sys.exit(f"[D-blind] {key} not set")
|
| 301 |
+
files = select_files(sorted(glob.glob(f"{SAMPLES}/*.jsonl")), a.bench)
|
| 302 |
+
print(f"[D-blind] {len(files)} benchmarks, model={a.model}, "
|
| 303 |
+
f"mode={'options_only' if a.options_only else 'blind'}, out={OUT}", flush=True)
|
| 304 |
+
n_done = 0
|
| 305 |
+
with ThreadPoolExecutor(max_workers=a.workers) as ex:
|
| 306 |
+
futs = {ex.submit(run_bench, p, a.model, a.limit, a.options_only): p for p in files}
|
| 307 |
+
for fut in as_completed(futs):
|
| 308 |
+
try:
|
| 309 |
+
bench, n_new, n_err, n_all = fut.result()
|
| 310 |
+
except Exception as e:
|
| 311 |
+
log(f"{os.path.basename(futs[fut])}: bench-level failure "
|
| 312 |
+
f"{type(e).__name__}: {str(e)[:200]}")
|
| 313 |
+
n_done += 1
|
| 314 |
+
continue
|
| 315 |
+
n_done += 1
|
| 316 |
+
print(f"[D-blind] [{n_done}/{len(files)}] {bench}: +{n_new} "
|
| 317 |
+
f"err={n_err} (total {n_all})", flush=True)
|
| 318 |
+
print("[D-blind] all benchmarks finished", flush=True)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
if __name__ == "__main__":
|
| 322 |
+
main()
|