Download supplement_20260910/code/exp/analysis/pool/pool_steps.py from GMLRVigil/BenchCheck-Pool-Frames: direct link, hf CLI and curl.
- Browser
- Download file 18.4 kB
-
https://huggingface.co/datasets/GMLRVigil/BenchCheck-Pool-Frames/resolve/main/supplement_20260910/code/exp/analysis/pool/pool_steps.py
- Command line
-
hf download hf://datasets/GMLRVigil/BenchCheck-Pool-Frames/supplement_20260910/code/exp/analysis/pool/pool_steps.py
-
curl -L -o pool_steps.py https://huggingface.co/datasets/GMLRVigil/BenchCheck-Pool-Frames/resolve/main/supplement_20260910/code/exp/analysis/pool/pool_steps.py
18.4 kB
| #!/usr/bin/env python3 | |
| """pool_steps.py — shared vLLM client for the three screening steps (TASK.md). | |
| step 1 blind Qwen3-VL-8B, text only. N_PERM=4 option shuffles per item | |
| (random.Random(f"42|{item_id}")), one forward each, log-probs of the | |
| presented letters. blind_acc_4perm = share of permutations whose | |
| argmax letter is the correct one; blind_margin = mean over permutations | |
| of (log p(correct) - mean log p(others)). Removed when | |
| blind_margin > log 2 AND >= 3 of 4 permutations pick the correct option. | |
| step 2 single_frame Qwen3-VL-8B, the middle grid frame (v_1 position, 448 px long side), | |
| original option order, one forward. sf_correct = argmax is correct; | |
| sf_margin as above. Removed when sf_correct AND sf_margin > log 2. | |
| step 3 v32_2b Qwen3-VL-2B, the 32-frame grid (448 px), one forward. | |
| v32_2b_correct / v32_2b_margin; same removal rule. | |
| Chain: step 1 runs on step-0 kept mcq items; step 2 on step-1 survivors with a normalized | |
| video; step 3 on step-2 survivors. Every step is resumable by item_id (rows with | |
| status != ok are retried up to MAX_ERRORS_PER_ITEM times). Log-probs: max_tokens=1, | |
| logprobs=true, top_logprobs=20, assistant turn prefilled with "Answer:" so the next token | |
| is the letter; token variants ("A", " A", "(A", "A.") are merged; a letter absent from | |
| the top-20 gets log(1e-6) and is listed in `missing`. | |
| Usage (inside the GPU job; step1_blind.py / step2_single_frame.py / step3_v32_2b.py wrap this): | |
| pool_steps.py --step 1 --endpoint http://127.0.0.1:8001/v1 [--workers 32] | |
| [--bench A,B] [--limit N] [--max-minutes M] [--plan-only] [--shard i/k] | |
| """ | |
| import argparse | |
| import base64 | |
| import json | |
| import os | |
| import random | |
| import sys | |
| import threading | |
| import time | |
| from collections import OrderedDict | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| import pyarrow.parquet as pq | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| import pool_common as pc # noqa: E402 | |
| from pool_common import log # noqa: E402 | |
| import frames_decode as fd # noqa: E402 | |
| from pool_prompts import INTRO_BLIND, INTRO_OPT_ONLY, INTRO_VISUAL # noqa: E402 (verbatim copies of stage_p1_runner) | |
| MAX_ATTEMPTS = 5 | |
| DEFAULT_WORKERS = {1: 32, 2: 16, 3: 8, 4: 32, 5: 8, 6: 8} | |
| # ------------------------------------------------------------------ items | |
| def load_items(): | |
| """Base items with video_id/video_path refreshed from the current manifest.""" | |
| cols = ["benchmark", "item_id", "video_key", "video_id", "video_path", "question", "options", | |
| "n_options", "answer_idx", "format"] | |
| df = pq.read_table(pc.BASE_PARQUET, columns=cols).to_pandas() | |
| hashes = pc.manifest_hashes() | |
| pend = df["video_id"].str.startswith("k:") | |
| new = df.loc[pend, "video_key"].map(hashes) | |
| got = new.notna() | |
| df.loc[new[got].index, "video_id"] = new[got].values | |
| df.loc[new[got].index, "video_path"] = [pc.normalized_path(x) for x in new[got].values] | |
| return df | |
| def eligible(step, df): | |
| """Items this step should process (chain rule), plus a note on upstream state. | |
| 2026-09-10: items whose options are a bare yes/no (true/false) pair are not multiple-choice items | |
| under the project rule and are skipped by every step (they stay in the parquet, assemble marks them).""" | |
| df = df[df["format"] == "mcq"] | |
| from chance import _yes_no_options | |
| yn = df["options"].map(lambda o: _yes_no_options(list(o)) if o is not None else False) | |
| df = df[~yn] | |
| notes = [f"yes/no-option items skipped={int(yn.sum())}"] | |
| if os.path.exists(pc.STEP0_KEPT): | |
| kept = pq.read_table(pc.STEP0_KEPT, columns=["item_id", "kept"]).to_pandas() | |
| keep_ids = set(kept.loc[kept["kept"], "item_id"]) | |
| df = df[df["item_id"].isin(keep_ids)] | |
| else: | |
| notes.append("step0_kept.parquet missing: no dedup applied") | |
| if step in (2, 3): | |
| ok1, _ = pc.load_step_rows(1) | |
| surv = {i for i, r in ok1.items() if not r.get("remove")} | |
| df = df[df["item_id"].isin(surv)] | |
| df = df[df["video_path"].notna()] | |
| notes.append(f"step1 done={len(ok1)} survivors={len(surv)}") | |
| if step == 3: | |
| ok2, _ = pc.load_step_rows(2) | |
| surv = {i for i, r in ok2.items() if not r.get("remove")} | |
| df = df[df["item_id"].isin(surv)] | |
| notes.append(f"step2 done={len(ok2)} survivors={len(surv)}") | |
| if step >= 4: | |
| # steps 4-6 run on the step-1 survivors that no other step (with rows) has removed; they do not | |
| # wait for steps 2/3 (removal is "any step"), so machines can share the work; visual steps need frames | |
| ok1, _ = pc.load_step_rows(1) | |
| surv = {i for i, r in ok1.items() if not r.get("remove")} | |
| df = df[df["item_id"].isin(surv)] | |
| notes.append(f"step1 done={len(ok1)} survivors={len(surv)}") | |
| for other in pc.STEPS: | |
| if other in (1, step): | |
| continue | |
| oko, _ = pc.load_step_rows(other) | |
| removed = {i for i, r in oko.items() if r.get("remove")} | |
| if removed: | |
| df = df[~df["item_id"].isin(removed)] | |
| notes.append(f"step{other} removed={len(removed)} excluded") | |
| if step in pc.VISUAL_STEPS: | |
| df = df[df["video_path"].notna()] | |
| return df, notes | |
| # ------------------------------------------------------------------ runner | |
| class Runner: | |
| def __init__(self, step, endpoint, model, workers): | |
| self.step, self.endpoint, self.model, self.workers = step, endpoint, model, workers | |
| self.frames_cache = OrderedDict() # video_id -> (info, {k: b64}) | |
| self.cache_lock = threading.Lock() | |
| self.meta_cache = {} | |
| self.stats = dict(items=0, forwards=0, errors=0, latency_s=0.0, prompt_tokens=0, | |
| removed=0, missing_letter_forwards=0, decode_s=0.0) | |
| self.stats_lock = threading.Lock() | |
| self.variants = {} | |
| def bump(self, **kw): | |
| with self.stats_lock: | |
| for k, v in kw.items(): | |
| self.stats[k] += v | |
| def note_variants(self, variants): | |
| with self.stats_lock: | |
| for L, toks in variants.items(): | |
| for t in toks: | |
| key = repr(t) | |
| self.variants[key] = self.variants.get(key, 0) + 1 | |
| def frames_b64(self, video_id, video_path, keys): | |
| with self.cache_lock: | |
| ent = self.frames_cache.get(video_id) | |
| if ent is not None: | |
| self.frames_cache.move_to_end(video_id) | |
| if ent is None: | |
| t0 = time.time() | |
| meta = self.meta_cache.get(video_id) or pc.meta_of(video_id) | |
| self.meta_cache[video_id] = meta | |
| info = fd.ensure_frames(video_id, video_path, meta) | |
| b64 = {k: base64.b64encode(fd.frame_bytes(video_id, k)).decode() for k in info["keys"]} | |
| ent = (info, b64) | |
| self.bump(decode_s=time.time() - t0) | |
| with self.cache_lock: | |
| self.frames_cache[video_id] = ent | |
| while len(self.frames_cache) > 64: | |
| self.frames_cache.popitem(last=False) | |
| info, b64 = ent | |
| if keys == "mid": | |
| return info, [b64[info["mid_k"]]], [info["mid_k"]] | |
| return info, [b64[k] for k in info["keys"]], list(info["keys"]) | |
| def forward(self, prompt, images, who): | |
| last = None | |
| for attempt in range(MAX_ATTEMPTS): | |
| try: | |
| return pc.logprob_request(self.endpoint, self.model, prompt, images) | |
| except pc.ContextTooLong: | |
| raise | |
| except Exception as e: # connection / 5xx / timeout | |
| last = e | |
| time.sleep(min(20, 2 ** attempt + random.uniform(0, 1))) | |
| raise RuntimeError(f"{who}: {type(last).__name__}: {str(last)[:200]}") | |
| # ---- per item | |
| def run_item(self, row): | |
| iid, bench = row["item_id"], row["benchmark"] | |
| opts = list(row["options"]) | |
| k, aidx = len(opts), int(row["answer_idx"]) | |
| base = dict(item_id=iid, benchmark=bench, step=pc.STEPS[self.step], model=self.model, | |
| n_options=k, ts=time.strftime("%F %T")) | |
| try: | |
| if self.step == 1: | |
| out = self.blind(iid, row["question"], opts, k, aidx) | |
| elif self.step == 4: | |
| out = self.blind(iid, None, opts, k, aidx, opt_only=True) | |
| else: | |
| out = self.visual(iid, row, opts, k, aidx) | |
| out.update(base) | |
| out["status"] = "ok" | |
| self.bump(items=1, removed=int(bool(out["remove"]))) | |
| return out | |
| except Exception as e: | |
| self.bump(errors=1) | |
| return dict(base, status="error", error=f"{type(e).__name__}: {str(e)[:300]}") | |
| def blind(self, iid, question, opts, k, aidx, opt_only=False): | |
| perms = pc.permutations_for(iid, k) | |
| recs, hits, margins, lat, ptok = [], 0, [], 0.0, 0 | |
| for perm in perms: | |
| texts = [opts[i] for i in perm] | |
| cpos = perm.index(aidx) | |
| if opt_only: # step 4: option level of the pyramid -- no frames, no question text | |
| prompt = pc.PROMPT_OPT_ONLY.format(intro=INTRO_OPT_ONLY, opts=pc.render_options(texts)) | |
| else: | |
| prompt = pc.PROMPT.format(intro=INTRO_BLIND, q=question, opts=pc.render_options(texts)) | |
| r = self.forward(prompt, None, f"{iid}/{'opt_only' if opt_only else 'blind'}") | |
| lp, missing, variants = pc.letter_logprobs(r["top"], k) | |
| self.note_variants(variants) | |
| am = pc.argmax_pos(lp) | |
| m = pc.margin_of(lp, cpos) | |
| hit = int(am == cpos and lp[am] > pc.LP_FLOOR) | |
| hits += hit | |
| margins.append(m) | |
| lat += r["latency_s"] | |
| ptok += r["prompt_tokens"] | |
| self.bump(forwards=1, latency_s=r["latency_s"], prompt_tokens=r["prompt_tokens"], | |
| missing_letter_forwards=int(bool(missing))) | |
| recs.append(dict(order=perm, correct_pos=cpos, lp=[round(x, 4) for x in lp], argmax=am, | |
| hit=hit, margin=round(m, 4), missing=missing, top1_token=r["top1_token"])) | |
| acc = hits / len(perms) | |
| margin = sum(margins) / len(margins) | |
| remove = bool(margin > pc.LOG2 and hits >= len(perms) - 1) | |
| pre = "opt" if opt_only else "blind" | |
| out = dict(perms=recs, remove=remove, n_forwards=len(perms), latency_s=round(lat, 4), prompt_tokens=ptok) | |
| out[f"{pre}_acc_4perm"] = round(acc, 4) | |
| out[f"{pre}_margin"] = round(margin, 4) | |
| return out | |
| def visual(self, iid, row, opts, k, aidx): | |
| vid, vpath = row["video_id"], row["video_path"] | |
| info, images, keys = self.frames_b64(vid, vpath, "mid" if self.step == 2 else "all") | |
| perm_seed = None | |
| if self.step == 5: # order level: the same 32 frames, one fixed per-item shuffle (stage_p1_runner v_32_shuffle) | |
| perm_seed = f"42|{iid}" | |
| order = list(range(len(images))) | |
| random.Random(perm_seed).shuffle(order) | |
| images, keys = [images[i] for i in order], [keys[i] for i in order] | |
| prompt = pc.PROMPT.format(intro=INTRO_VISUAL.format(n=len(images)), q=row["question"], | |
| opts=pc.render_options(opts)) | |
| r = self.forward(prompt, images, f"{iid}/{pc.STEPS[self.step]}") | |
| lp, missing, variants = pc.letter_logprobs(r["top"], k) | |
| self.note_variants(variants) | |
| am = pc.argmax_pos(lp) | |
| m = pc.margin_of(lp, aidx) | |
| correct = bool(am == aidx and lp[am] > pc.LP_FLOOR) | |
| remove = bool(correct and m > pc.LOG2) | |
| self.bump(forwards=1, latency_s=r["latency_s"], prompt_tokens=r["prompt_tokens"], | |
| missing_letter_forwards=int(bool(missing))) | |
| pre = {2: "sf", 3: "v32_2b", 5: "v32_2b_shuffle", 6: "v32_8b"}[self.step] | |
| out = dict(video_id=vid, frame_keys=keys, n_frames=len(images), frame_wh=[info.get("w"), info.get("h")], | |
| correct_pos=aidx, lp=[round(x, 4) for x in lp], argmax=am, missing=missing, | |
| top1_token=r["top1_token"], remove=remove, n_forwards=1, | |
| latency_s=r["latency_s"], prompt_tokens=r["prompt_tokens"]) | |
| if perm_seed: | |
| out["perm_seed"] = perm_seed | |
| out[f"{pre}_correct"] = correct | |
| out[f"{pre}_margin"] = round(m, 4) | |
| return out | |
| def run_unit(runner, unit, rows_by_id, workers, deadline, flush_every=20): | |
| bench, part, n_parts, ids = unit | |
| path = pc.unit_file(runner.step, bench, part, n_parts) | |
| rows = [rows_by_id[i] for i in ids] | |
| if runner.step in pc.VISUAL_STEPS: # same-video items share the frame cache | |
| rows.sort(key=lambda r: (r["video_id"], r["item_id"])) | |
| buf, n_done, t0 = [], 0, time.time() | |
| stopped = False | |
| with ThreadPoolExecutor(max_workers=workers) as ex: | |
| pending = set() | |
| it = iter(rows) | |
| while True: | |
| while len(pending) < workers * 2 and not stopped: | |
| if deadline and time.time() > deadline: | |
| stopped = True | |
| break | |
| r = next(it, None) | |
| if r is None: | |
| stopped = True | |
| break | |
| pending.add(ex.submit(runner.run_item, r)) | |
| if not pending: | |
| break | |
| done = next(as_completed(pending)) | |
| pending.discard(done) | |
| buf.append(done.result()) | |
| n_done += 1 | |
| if len(buf) >= flush_every: | |
| pc.append_rows(path, buf) | |
| buf = [] | |
| if n_done % 200 == 0: | |
| st = runner.stats | |
| el = time.time() - t0 | |
| log(f"{bench}.p{part}: {n_done}/{len(rows)} items, {st['forwards']} fwd total, " | |
| f"{n_done / el:.2f} items/s, mean fwd latency {st['latency_s'] / max(st['forwards'], 1):.3f}s, " | |
| f"errors={st['errors']}", f"step{runner.step}") | |
| if buf: | |
| pc.append_rows(path, buf) | |
| return n_done, len(rows) - n_done | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | |
| ap.add_argument("--step", type=int, required=True, choices=[1, 2, 3, 4, 5, 6]) | |
| ap.add_argument("--endpoint", default=None) | |
| ap.add_argument("--workers", type=int, default=None) | |
| ap.add_argument("--bench", default=None, help="comma list (default: all)") | |
| ap.add_argument("--limit", type=int, default=None, help="first N eligible items per benchmark (smoke tests)") | |
| ap.add_argument("--max-minutes", type=float, default=None, help="stop starting new items after M minutes") | |
| ap.add_argument("--max-unit", type=int, default=20000) | |
| ap.add_argument("--shard", default=None, help="i/k (default: Slurm array env or 0/1)") | |
| ap.add_argument("--plan-only", action="store_true", help="print the remaining work of this shard and exit") | |
| a = ap.parse_args() | |
| pc.ensure_dirs() | |
| step = a.step | |
| model_name, _snap = pc.MODELS[pc.STEP_MODEL[step]] | |
| workers = a.workers or DEFAULT_WORKERS[step] | |
| t_start = time.time() | |
| df = load_items() | |
| elig, notes = eligible(step, df) | |
| if a.bench: | |
| want = {b.strip() for b in a.bench.split(",") if b.strip()} | |
| elig = elig[elig["benchmark"].isin(want)] | |
| ok, errs = pc.load_step_rows(step) | |
| todo = elig[~elig["item_id"].isin(set(ok))] | |
| perm_fail = {i for i, n in errs.items() if n >= pc.MAX_ERRORS_PER_ITEM} | |
| todo = todo[~todo["item_id"].isin(perm_fail)] | |
| if a.limit: | |
| todo = todo.sort_values("item_id").groupby("benchmark", sort=False).head(a.limit) | |
| work = [(b, list(g["item_id"])) for b, g in todo.groupby("benchmark", sort=True)] | |
| units = pc.plan_units(work, a.max_unit) | |
| if a.shard: | |
| tid, n = (int(x) for x in a.shard.split("/")) | |
| else: | |
| tid, n = pc.slurm_task() | |
| mine, loads = pc.assign_units(units, n, tid) | |
| n_mine = sum(len(u[3]) for u in mine) | |
| log(f"step {step} ({pc.STEPS[step]}, {model_name}): eligible={len(elig)} done={len(ok)} " | |
| f"permanently_failed={len(perm_fail)} remaining={len(todo)}; shard {tid}/{n} -> {len(mine)} unit(s), " | |
| f"{n_mine} items (max shard load {max(loads) if loads else 0:.0f}); {'; '.join(notes)}", f"step{step}") | |
| if a.plan_only: | |
| print(f"REMAINING_TOTAL={len(todo)} REMAINING_SHARD={n_mine} UNITS={len(mine)}") | |
| return | |
| if not mine: | |
| log("nothing to do", f"step{step}") | |
| print("INCOMPLETE=0") | |
| return | |
| if not a.endpoint: | |
| sys.exit("--endpoint required") | |
| runner = Runner(step, a.endpoint.rstrip("/"), model_name, workers) | |
| rows_by_id = {r["item_id"]: r for r in todo.to_dict("records")} | |
| deadline = (t_start + a.max_minutes * 60) if a.max_minutes else None | |
| left_total = 0 | |
| for u in mine: | |
| if deadline and time.time() > deadline: | |
| left_total += len(u[3]) | |
| continue | |
| n_done, left = run_unit(runner, u, rows_by_id, workers, deadline) | |
| left_total += left | |
| log(f"{u[0]}.p{u[1]}: done {n_done}, left {left}", f"step{step}") | |
| st = runner.stats | |
| wall = time.time() - t_start | |
| summary = dict(ts=time.strftime("%F %T"), stage=f"step{step}", shard=f"{tid}/{n}", model=model_name, | |
| items=st["items"], forwards=st["forwards"], errors=st["errors"], removed=st["removed"], | |
| wall_s=round(wall, 1), mean_fwd_latency_s=round(st["latency_s"] / max(st["forwards"], 1), 4), | |
| fwd_per_s=round(st["forwards"] / max(wall, 1e-9), 3), | |
| items_per_s=round(st["items"] / max(wall, 1e-9), 3), | |
| mean_prompt_tokens=round(st["prompt_tokens"] / max(st["forwards"], 1), 1), | |
| missing_letter_forwards=st["missing_letter_forwards"], decode_s=round(st["decode_s"], 1), | |
| workers=workers, token_variants=dict(sorted(runner.variants.items(), key=lambda kv: -kv[1])[:8]), | |
| left=left_total, slurm_job=os.environ.get("SLURM_JOB_ID")) | |
| with open(os.path.join(pc.LOG_DIR, "pool_timing.jsonl"), "a") as f: | |
| f.write(json.dumps(summary) + "\n") | |
| log(json.dumps(summary), f"step{step}") | |
| print(f"INCOMPLETE={left_total}") | |
| if __name__ == "__main__": | |
| main() | |