File size: 15,274 Bytes
c4fa15f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
"""Shared paths, schema helpers and the vLLM option-letter log-prob client for the
full-item-pool screening run (exp/analysis/pool/TASK.md).

Layout
  exp/results/pool/                      small tabular outputs (csv/md) + parquet/duckdb
      pool_items_base.parquet            pool_schema.py   (all items, TASK schema)
      step0_kept.parquet                 step0_screen.py  (dedup verdict per item)
      screen_counts_full.csv             step0_screen.py
      step1/<bench>[.p<j>].jsonl         step1_blind.py   (one row per item, append-only)
      step2/<bench>[.p<j>].jsonl         step2_single_frame.py
      step3/<bench>[.p<j>].jsonl         step3_v32_2b.py
      pool_items.parquet, pool.duckdb, pool_summary.md, run_accounting.csv  (assemble/accounting)
  bench_exp/work/pool_items_cache/       per-bench enumeration cache (jsonl) for the 88
                                         benchmarks without a T3 full-text export
  bench_exp/work/pool_embeddings/        bge-large-en-v1.5 cache per bench (ids.json + .npy),
                                         same layout as exp/data/embeddings/text
  bench_exp/work/pool_frames/<video_id>/ frame_<k>.jpg (448 px long side) + frames.json

Item id = the pipeline qid (f"{bench}_{pool_index}", or the stage_b adapter qid for
MVBench / LVBench / VideoMMMU). video_id = normalized content_hash, or
"k:" + sha1(video_key)[:16] while the video is not yet normalized.
"""
import fcntl
import hashlib
import json
import math
import os
import random
import re
import sys
import time

HERE = os.path.dirname(os.path.abspath(__file__))           # exp/analysis/pool
EXP = os.path.abspath(os.path.join(HERE, "..", ".."))        # exp
REPO = os.path.dirname(EXP)
PIPE = os.path.join(EXP, "pipeline")
for p in (PIPE, os.path.join(EXP, "t3")):
    if p not in sys.path:
        sys.path.insert(0, p)
os.environ.setdefault("FINEBENCH_ROUTE", "yt")   # FineBench samples were drawn with the YouTube route

# Off-cluster runs (exp/analysis/pool/REMOTE_README.md, HF dataset GMLRVigil/BenchCheck-Pool): POOL_BASE
# replaces the cluster data root (the store / manifest / caches under it are optional for steps 1-3),
# POOL_FRAMES_DIR points at the unpacked frame cache, POOL_RESULTS_ROOT at the items + step outputs.
BASE = os.environ.get("POOL_BASE") or "/vast/projects/jgu32/lab/enxin/bench_exp"
STORE = f"{BASE}/store"
WORK = f"{BASE}/work"
NORMALIZED = f"{STORE}/normalized"
MANIFEST_JSONL = f"{BASE}/logs/manifest.jsonl"
T3_FULL = f"{BASE}/t3_export_n1_fulltext/full"
ITEMS_CACHE = f"{WORK}/pool_items_cache"
EMB_DIR = f"{WORK}/pool_embeddings"
FRAMES_DIR = os.environ.get("POOL_FRAMES_DIR") or f"{WORK}/pool_frames"
LOG_DIR = f"{BASE}/logs"

RESULTS = os.environ.get("POOL_RESULTS_ROOT") or os.path.join(EXP, "results", "pool")   # override for smoke tests
BASE_PARQUET = os.path.join(RESULTS, "pool_items_base.parquet")
SCHEMA_MANIFEST = os.path.join(RESULTS, "pool_schema_manifest.csv")
STEP0_KEPT = os.path.join(RESULTS, "step0_kept.parquet")
STEP0_REMOVED = os.path.join(RESULTS, "step0_removed.jsonl")
SCREEN_CSV = os.path.join(RESULTS, "screen_counts_full.csv")
POOL_PARQUET = os.path.join(RESULTS, "pool_items.parquet")
POOL_DUCKDB = os.path.join(RESULTS, "pool.duckdb")
POOL_SUMMARY_MD = os.path.join(RESULTS, "pool_summary.md")
POOL_SUMMARY_CSV = os.path.join(RESULTS, "pool_summary.csv")
ACCOUNTING_CSV = os.path.join(RESULTS, "run_accounting.csv")

VB_CSV = os.path.join(EXP, "video_benchmarks.csv")
REGISTRY_CSV = os.path.join(REPO, "meta", "benchmark_registry.csv")
SAMPLE_DIRS = [os.path.join(EXP, "data", "samples"), os.path.join(EXP, "data", "samples_n1")]

HF_HUB = "/vast/projects/jgu32/lab/enxin/cache/hf/hub"
MODELS = {
    # step -> (served model name, snapshot dir)
    "8b": ("Qwen/Qwen3-VL-8B-Instruct",
           f"{HF_HUB}/models--Qwen--Qwen3-VL-8B-Instruct/snapshots/0c351dd01ed87e9c1b53cbc748cba10e6187ff3b"),
    "2b": ("Qwen/Qwen3-VL-2B-Instruct",
           f"{HF_HUB}/models--Qwen--Qwen3-VL-2B-Instruct/snapshots/89644892e4d85e24eaac8bacfd4f463576704203"),
}
BGE_SNAPSHOT = f"{HF_HUB}/models--BAAI--bge-large-en-v1.5/snapshots/d4aa6901d3a41ba39fb536a557fa166f842b0e09"

STEPS = {1: "blind", 2: "single_frame", 3: "v32_2b"}
STEP_MODEL = {1: "8b", 2: "8b", 3: "2b"}
STEP_DIR = {k: os.path.join(RESULTS, f"step{k}") for k in STEPS}

SEED = 42
N_PERM = 4
LOG2 = math.log(2.0)
LP_FLOOR = math.log(1e-6)          # letter absent from the top-20 log-probs
TOP_LOGPROBS = 20
MAX_OPTIONS = 26                   # letters A..Z; more options -> format=open
LETTERS = [chr(65 + i) for i in range(MAX_OPTIONS)]
FRAME_LONG_SIDE = 448
N_FRAMES_V32 = 32
MID_POS = 16                       # stage_p1_runner v_1: grid32[16]
JPEG_QUALITY = 85
MAX_ERRORS_PER_ITEM = 3            # error rows before an item is treated as permanently failed

# one prompt skeleton for all three steps (intro strings reused from stage_p1_runner)
PROMPT = "{intro}\n\nQuestion: {q}\nOptions:\n{opts}\nAnswer with the option letter only."
ASSISTANT_PREFIX = "Answer:"      # continue_final_message -> the next token is the letter
_TOKEN_LETTER = re.compile(r"^\s*[\(\[]?([A-Z])[\)\]\.:]?\s*$")


def log(msg, tag="pool"):
    print(f"[{tag}] {time.strftime('%H:%M:%S')} {msg}", file=sys.stderr, flush=True)


def ensure_dirs():
    for d in (RESULTS, ITEMS_CACHE, EMB_DIR, FRAMES_DIR, LOG_DIR, *STEP_DIR.values()):
        os.makedirs(d, exist_ok=True)


# ------------------------------------------------------------------ benches
def bench_list():
    """Stems of exp/data/samples/*.jsonl + exp/data/samples_n1/*.jsonl (139 onboarded)."""
    import glob
    names = set()
    for d in SAMPLE_DIRS:
        for p in glob.glob(os.path.join(d, "*.jsonl")):
            if os.path.exists(p):
                names.add(os.path.basename(p)[:-6])
    return sorted(names)


def sample_path(bench):
    for d in SAMPLE_DIRS:
        p = os.path.join(d, f"{bench}.jsonl")
        if os.path.exists(p):
            return p
    return None


def read_jsonl(path):
    out = []
    with open(path, encoding="utf-8") as f:
        for line in f:
            if line.strip():
                try:
                    out.append(json.loads(line))
                except json.JSONDecodeError:
                    continue   # torn final line of a killed writer
    return out


def key_of(ref):
    return f"{ref['repo']}::{ref.get('zip_path', '')}::{ref['member']}"


def manifest_hashes():
    """video_key -> content_hash for logs/manifest.jsonl status=done rows (last wins)."""
    m = {}
    if not os.path.exists(MANIFEST_JSONL):
        return m
    with open(MANIFEST_JSONL, encoding="utf-8") as f:
        for line in f:
            try:
                r = json.loads(line)
            except Exception:
                continue
            if r.get("status") == "done" and r.get("content_hash") and "::" in str(r.get("key", "")):
                m[r["key"]] = r["content_hash"]
    return m


def key_video_id(key):
    return "k:" + hashlib.sha1(key.encode("utf-8")).hexdigest()[:16]


def normalized_path(h):
    return f"{NORMALIZED}/{h}/video.mp4"


def meta_of(h):
    try:
        return json.load(open(f"{NORMALIZED}/{h}/meta.json"))
    except Exception:
        return None


# ------------------------------------------------------------------ options
_SEQ_PREFIX = re.compile(r"^\s*[\(\[]?([A-Za-z])[\)\]\.:]\s*(.*)$", re.S)


def strip_sequential_prefix(opts):
    """['A. x', 'B. y'] -> (['x', 'y'], True) when every option carries the letter of
    its position (A, B, C, ...); otherwise the list is returned unchanged."""
    texts = []
    for i, o in enumerate(opts):
        m = _SEQ_PREFIX.match(str(o))
        if not m or m.group(1).upper() != chr(65 + i):
            return [str(o) for o in opts], False
        texts.append(m.group(2).strip())
    return texts, True


def render_options(texts):
    return "\n".join(f"{LETTERS[i]}. {t}" for i, t in enumerate(texts))


def item_text(question, options):
    """Text embedded for the near-duplicate check: question + options."""
    q = " ".join(str(question or "").split())
    if isinstance(options, list) and options:
        return q + "\n" + "\n".join(str(o) for o in options)
    return q


def permutations_for(item_id, k, n_perm=N_PERM, seed=SEED):
    """TASK.md step 1: n_perm option shuffles, seed 42, per item. perm[j] = original
    option index shown at position j."""
    rng = random.Random(f"{seed}|{item_id}")
    return [rng.sample(range(k), k) for _ in range(n_perm)]


# ------------------------------------------------------------------ log-probs
def letter_logprobs(top_logprobs, k):
    """top_logprobs: list of {token, logprob} for the first generated position.
    -> (lp list over the k presented letters, missing letters, matched variants).
    Tokenization variants ('A', ' A', '(A', 'A.') are merged by log-sum-exp."""
    acc = {}
    variants = {}
    for e in top_logprobs or []:
        m = _TOKEN_LETTER.match(e.get("token") or "")
        if not m:
            continue
        L = m.group(1)
        if L not in acc:
            acc[L] = e["logprob"]
        else:
            a, b = acc[L], e["logprob"]
            acc[L] = max(a, b) + math.log1p(math.exp(-abs(a - b)))
        variants.setdefault(L, []).append(e.get("token"))
    lp, missing = [], []
    for i in range(k):
        L = LETTERS[i]
        if L in acc:
            lp.append(float(acc[L]))
        else:
            lp.append(LP_FLOOR)
            missing.append(L)
    return lp, missing, variants


def margin_of(lp, correct_pos):
    others = [v for i, v in enumerate(lp) if i != correct_pos]
    return lp[correct_pos] - (sum(others) / len(others) if others else 0.0)


def argmax_pos(lp):
    best = max(lp)
    return lp.index(best)


class ContextTooLong(Exception):
    pass


def logprob_request(endpoint, model, prompt, images_b64=None, timeout=(10, 600)):
    """One forward: max_tokens=1, logprobs=true, top_logprobs=20; the assistant turn is
    prefilled with ASSISTANT_PREFIX (continue_final_message) so the next token is the
    letter. -> dict(top=[{token, logprob}], top1_token, prompt_tokens, latency_s)."""
    import requests
    content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + b}}
               for b in (images_b64 or [])]
    content.append({"type": "text", "text": prompt})
    body = {"model": model, "temperature": 0.0, "max_tokens": 1,
            "logprobs": True, "top_logprobs": TOP_LOGPROBS,
            "messages": [{"role": "user", "content": content},
                         {"role": "assistant", "content": ASSISTANT_PREFIX}],
            "continue_final_message": True, "add_generation_prompt": False}
    t0 = time.time()
    r = requests.post(f"{endpoint}/chat/completions", json=body, timeout=timeout)
    if r.status_code == 400 and ("maximum" in r.text or "longer than" in r.text
                                 or "context length" in r.text):
        raise ContextTooLong(r.text[:200])
    r.raise_for_status()
    d = r.json()
    ch = d["choices"][0]
    lpc = (ch.get("logprobs") or {}).get("content") or []
    if not lpc:
        raise RuntimeError("no logprobs in response")
    top = [{"token": e.get("token"), "logprob": e.get("logprob")} for e in (lpc[0].get("top_logprobs") or [])]
    return dict(top=top, top1_token=lpc[0].get("token"),
                prompt_tokens=(d.get("usage") or {}).get("prompt_tokens", 0),
                latency_s=round(time.time() - t0, 4))


# ------------------------------------------------------------------ result files
def bench_files(step, bench):
    """All jsonl files of a benchmark under step<k>/ (part files included)."""
    d = STEP_DIR[step]
    if not os.path.isdir(d):
        return []
    out = []
    for f in os.listdir(d):
        if f == f"{bench}.jsonl" or (f.startswith(f"{bench}.p") and f.endswith(".jsonl")
                                     and f[len(bench) + 2:-6].isdigit()):
            out.append(os.path.join(d, f))
    return sorted(out)


def unit_file(step, bench, part, n_parts):
    return os.path.join(STEP_DIR[step], f"{bench}.jsonl" if n_parts == 1 else f"{bench}.p{part}.jsonl")


def load_step_rows(step, benches=None):
    """item_id -> last successful row; plus item_id -> error count.
    Rows with status != ok are errors (never counted as done)."""
    ok, errs = {}, {}
    d = STEP_DIR[step]
    if not os.path.isdir(d):
        return ok, errs
    files = []
    for f in sorted(os.listdir(d)):
        if not f.endswith(".jsonl"):
            continue
        if benches is not None:
            b = f[:-6]
            if "." in b and b.rsplit(".", 1)[1][1:].isdigit() and b.rsplit(".", 1)[1].startswith("p"):
                b = b.rsplit(".", 1)[0]
            if b not in benches:
                continue
        files.append(os.path.join(d, f))
    for p in files:
        for r in read_jsonl(p):
            iid = r.get("item_id")
            if iid is None:
                continue
            if r.get("status", "ok") == "ok":
                ok[iid] = r
            else:
                errs[iid] = errs.get(iid, 0) + 1
    return ok, errs


def append_rows(path, rows):
    """Append json rows under an exclusive flock (several array tasks may touch a file
    across re-runs; the lock keeps rows whole)."""
    os.makedirs(os.path.dirname(path), exist_ok=True)
    data = "".join(json.dumps(r, ensure_ascii=False, default=str) + "\n" for r in rows)
    with open(path, "a", encoding="utf-8") as f:
        fcntl.flock(f, fcntl.LOCK_EX)
        try:
            f.write(data)
            f.flush()
        finally:
            fcntl.flock(f, fcntl.LOCK_UN)


# ------------------------------------------------------------------ sharding
def plan_units(work, max_unit=20000):
    """work: list of (bench, [item_ids sorted]) -> units [(bench, part, n_parts, ids)].
    Big benchmarks are split into parts of <= max_unit items (deterministic by sorted
    item_id) so one array task never owns more than max_unit items of one file."""
    units = []
    for bench, ids in work:
        ids = sorted(ids)
        n_parts = max(1, math.ceil(len(ids) / max_unit)) if ids else 1
        size = math.ceil(len(ids) / n_parts) if ids else 0
        for part in range(n_parts):
            units.append((bench, part, n_parts, ids[part * size:(part + 1) * size]))
    return units


def assign_units(units, n_tasks, task_id, weight=lambda u: len(u[3])):
    """Deterministic LPT (largest first to the least loaded task)."""
    loads = [0.0] * n_tasks
    mine = []
    for u in sorted(units, key=lambda u: (-weight(u), u[0], u[1])):
        t = min(range(n_tasks), key=lambda i: (loads[i], i))
        loads[t] += weight(u)
        if t == task_id:
            mine.append(u)
    return mine, loads


def slurm_task():
    """(task_id, n_tasks) from the Slurm array environment; (0, 1) outside Slurm."""
    tid = int(os.environ.get("SLURM_ARRAY_TASK_ID", 0))
    n = os.environ.get("SLURM_ARRAY_TASK_COUNT")
    if n is None:
        lo, hi = os.environ.get("SLURM_ARRAY_TASK_MIN"), os.environ.get("SLURM_ARRAY_TASK_MAX")
        n = int(hi) - int(lo) + 1 if lo is not None and hi is not None else 1
        if lo is not None:
            tid -= int(lo)
    return tid, int(n)