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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""pool_steps.py — shared vLLM client for the three screening steps (TASK.md).
|
| 3 |
+
|
| 4 |
+
step 1 blind Qwen3-VL-8B, text only. N_PERM=4 option shuffles per item
|
| 5 |
+
(random.Random(f"42|{item_id}")), one forward each, log-probs of the
|
| 6 |
+
presented letters. blind_acc_4perm = share of permutations whose
|
| 7 |
+
argmax letter is the correct one; blind_margin = mean over permutations
|
| 8 |
+
of (log p(correct) - mean log p(others)). Removed when
|
| 9 |
+
blind_margin > log 2 AND >= 3 of 4 permutations pick the correct option.
|
| 10 |
+
step 2 single_frame Qwen3-VL-8B, the middle grid frame (v_1 position, 448 px long side),
|
| 11 |
+
original option order, one forward. sf_correct = argmax is correct;
|
| 12 |
+
sf_margin as above. Removed when sf_correct AND sf_margin > log 2.
|
| 13 |
+
step 3 v32_2b Qwen3-VL-2B, the 32-frame grid (448 px), one forward.
|
| 14 |
+
v32_2b_correct / v32_2b_margin; same removal rule.
|
| 15 |
+
|
| 16 |
+
Chain: step 1 runs on step-0 kept mcq items; step 2 on step-1 survivors with a normalized
|
| 17 |
+
video; step 3 on step-2 survivors. Every step is resumable by item_id (rows with
|
| 18 |
+
status != ok are retried up to MAX_ERRORS_PER_ITEM times). Log-probs: max_tokens=1,
|
| 19 |
+
logprobs=true, top_logprobs=20, assistant turn prefilled with "Answer:" so the next token
|
| 20 |
+
is the letter; token variants ("A", " A", "(A", "A.") are merged; a letter absent from
|
| 21 |
+
the top-20 gets log(1e-6) and is listed in `missing`.
|
| 22 |
+
|
| 23 |
+
Usage (inside the GPU job; step1_blind.py / step2_single_frame.py / step3_v32_2b.py wrap this):
|
| 24 |
+
pool_steps.py --step 1 --endpoint http://127.0.0.1:8001/v1 [--workers 32]
|
| 25 |
+
[--bench A,B] [--limit N] [--max-minutes M] [--plan-only] [--shard i/k]
|
| 26 |
+
"""
|
| 27 |
+
import argparse
|
| 28 |
+
import base64
|
| 29 |
+
import json
|
| 30 |
+
import os
|
| 31 |
+
import random
|
| 32 |
+
import sys
|
| 33 |
+
import threading
|
| 34 |
+
import time
|
| 35 |
+
from collections import OrderedDict
|
| 36 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 37 |
+
|
| 38 |
+
import pyarrow.parquet as pq
|
| 39 |
+
|
| 40 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 41 |
+
import pool_common as pc # noqa: E402
|
| 42 |
+
from pool_common import log # noqa: E402
|
| 43 |
+
import frames_decode as fd # noqa: E402
|
| 44 |
+
from pool_prompts import INTRO_BLIND, INTRO_VISUAL # noqa: E402 (verbatim copies of stage_p1_runner)
|
| 45 |
+
|
| 46 |
+
MAX_ATTEMPTS = 5
|
| 47 |
+
DEFAULT_WORKERS = {1: 32, 2: 16, 3: 8}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# ------------------------------------------------------------------ items
|
| 51 |
+
def load_items():
|
| 52 |
+
"""Base items with video_id/video_path refreshed from the current manifest."""
|
| 53 |
+
cols = ["benchmark", "item_id", "video_key", "video_id", "video_path", "question", "options",
|
| 54 |
+
"n_options", "answer_idx", "format"]
|
| 55 |
+
df = pq.read_table(pc.BASE_PARQUET, columns=cols).to_pandas()
|
| 56 |
+
hashes = pc.manifest_hashes()
|
| 57 |
+
pend = df["video_id"].str.startswith("k:")
|
| 58 |
+
new = df.loc[pend, "video_key"].map(hashes)
|
| 59 |
+
got = new.notna()
|
| 60 |
+
df.loc[new[got].index, "video_id"] = new[got].values
|
| 61 |
+
df.loc[new[got].index, "video_path"] = [pc.normalized_path(x) for x in new[got].values]
|
| 62 |
+
return df
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def eligible(step, df):
|
| 66 |
+
"""Items this step should process (chain rule), plus a note on upstream state."""
|
| 67 |
+
df = df[df["format"] == "mcq"]
|
| 68 |
+
notes = []
|
| 69 |
+
if os.path.exists(pc.STEP0_KEPT):
|
| 70 |
+
kept = pq.read_table(pc.STEP0_KEPT, columns=["item_id", "kept"]).to_pandas()
|
| 71 |
+
keep_ids = set(kept.loc[kept["kept"], "item_id"])
|
| 72 |
+
df = df[df["item_id"].isin(keep_ids)]
|
| 73 |
+
else:
|
| 74 |
+
notes.append("step0_kept.parquet missing: no dedup applied")
|
| 75 |
+
if step >= 2:
|
| 76 |
+
ok1, _ = pc.load_step_rows(1)
|
| 77 |
+
surv = {i for i, r in ok1.items() if not r.get("remove")}
|
| 78 |
+
df = df[df["item_id"].isin(surv)]
|
| 79 |
+
df = df[df["video_path"].notna()]
|
| 80 |
+
notes.append(f"step1 done={len(ok1)} survivors={len(surv)}")
|
| 81 |
+
if step >= 3:
|
| 82 |
+
ok2, _ = pc.load_step_rows(2)
|
| 83 |
+
surv = {i for i, r in ok2.items() if not r.get("remove")}
|
| 84 |
+
df = df[df["item_id"].isin(surv)]
|
| 85 |
+
notes.append(f"step2 done={len(ok2)} survivors={len(surv)}")
|
| 86 |
+
return df, notes
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# ------------------------------------------------------------------ runner
|
| 90 |
+
class Runner:
|
| 91 |
+
def __init__(self, step, endpoint, model, workers):
|
| 92 |
+
self.step, self.endpoint, self.model, self.workers = step, endpoint, model, workers
|
| 93 |
+
self.frames_cache = OrderedDict() # video_id -> (info, {k: b64})
|
| 94 |
+
self.cache_lock = threading.Lock()
|
| 95 |
+
self.meta_cache = {}
|
| 96 |
+
self.stats = dict(items=0, forwards=0, errors=0, latency_s=0.0, prompt_tokens=0,
|
| 97 |
+
removed=0, missing_letter_forwards=0, decode_s=0.0)
|
| 98 |
+
self.stats_lock = threading.Lock()
|
| 99 |
+
self.variants = {}
|
| 100 |
+
|
| 101 |
+
def bump(self, **kw):
|
| 102 |
+
with self.stats_lock:
|
| 103 |
+
for k, v in kw.items():
|
| 104 |
+
self.stats[k] += v
|
| 105 |
+
|
| 106 |
+
def note_variants(self, variants):
|
| 107 |
+
with self.stats_lock:
|
| 108 |
+
for L, toks in variants.items():
|
| 109 |
+
for t in toks:
|
| 110 |
+
key = repr(t)
|
| 111 |
+
self.variants[key] = self.variants.get(key, 0) + 1
|
| 112 |
+
|
| 113 |
+
def frames_b64(self, video_id, video_path, keys):
|
| 114 |
+
with self.cache_lock:
|
| 115 |
+
ent = self.frames_cache.get(video_id)
|
| 116 |
+
if ent is not None:
|
| 117 |
+
self.frames_cache.move_to_end(video_id)
|
| 118 |
+
if ent is None:
|
| 119 |
+
t0 = time.time()
|
| 120 |
+
meta = self.meta_cache.get(video_id) or pc.meta_of(video_id)
|
| 121 |
+
self.meta_cache[video_id] = meta
|
| 122 |
+
info = fd.ensure_frames(video_id, video_path, meta)
|
| 123 |
+
b64 = {k: base64.b64encode(fd.frame_bytes(video_id, k)).decode() for k in info["keys"]}
|
| 124 |
+
ent = (info, b64)
|
| 125 |
+
self.bump(decode_s=time.time() - t0)
|
| 126 |
+
with self.cache_lock:
|
| 127 |
+
self.frames_cache[video_id] = ent
|
| 128 |
+
while len(self.frames_cache) > 64:
|
| 129 |
+
self.frames_cache.popitem(last=False)
|
| 130 |
+
info, b64 = ent
|
| 131 |
+
if keys == "mid":
|
| 132 |
+
return info, [b64[info["mid_k"]]], [info["mid_k"]]
|
| 133 |
+
return info, [b64[k] for k in info["keys"]], list(info["keys"])
|
| 134 |
+
|
| 135 |
+
def forward(self, prompt, images, who):
|
| 136 |
+
last = None
|
| 137 |
+
for attempt in range(MAX_ATTEMPTS):
|
| 138 |
+
try:
|
| 139 |
+
return pc.logprob_request(self.endpoint, self.model, prompt, images)
|
| 140 |
+
except pc.ContextTooLong:
|
| 141 |
+
raise
|
| 142 |
+
except Exception as e: # connection / 5xx / timeout
|
| 143 |
+
last = e
|
| 144 |
+
time.sleep(min(20, 2 ** attempt + random.uniform(0, 1)))
|
| 145 |
+
raise RuntimeError(f"{who}: {type(last).__name__}: {str(last)[:200]}")
|
| 146 |
+
|
| 147 |
+
# ---- per item
|
| 148 |
+
def run_item(self, row):
|
| 149 |
+
iid, bench = row["item_id"], row["benchmark"]
|
| 150 |
+
opts = list(row["options"])
|
| 151 |
+
k, aidx = len(opts), int(row["answer_idx"])
|
| 152 |
+
base = dict(item_id=iid, benchmark=bench, step=pc.STEPS[self.step], model=self.model,
|
| 153 |
+
n_options=k, ts=time.strftime("%F %T"))
|
| 154 |
+
try:
|
| 155 |
+
if self.step == 1:
|
| 156 |
+
out = self.blind(iid, row["question"], opts, k, aidx)
|
| 157 |
+
else:
|
| 158 |
+
out = self.visual(iid, row, opts, k, aidx)
|
| 159 |
+
out.update(base)
|
| 160 |
+
out["status"] = "ok"
|
| 161 |
+
self.bump(items=1, removed=int(bool(out["remove"])))
|
| 162 |
+
return out
|
| 163 |
+
except Exception as e:
|
| 164 |
+
self.bump(errors=1)
|
| 165 |
+
return dict(base, status="error", error=f"{type(e).__name__}: {str(e)[:300]}")
|
| 166 |
+
|
| 167 |
+
def blind(self, iid, question, opts, k, aidx):
|
| 168 |
+
perms = pc.permutations_for(iid, k)
|
| 169 |
+
recs, hits, margins, lat, ptok = [], 0, [], 0.0, 0
|
| 170 |
+
for perm in perms:
|
| 171 |
+
texts = [opts[i] for i in perm]
|
| 172 |
+
cpos = perm.index(aidx)
|
| 173 |
+
prompt = pc.PROMPT.format(intro=INTRO_BLIND, q=question, opts=pc.render_options(texts))
|
| 174 |
+
r = self.forward(prompt, None, f"{iid}/blind")
|
| 175 |
+
lp, missing, variants = pc.letter_logprobs(r["top"], k)
|
| 176 |
+
self.note_variants(variants)
|
| 177 |
+
am = pc.argmax_pos(lp)
|
| 178 |
+
m = pc.margin_of(lp, cpos)
|
| 179 |
+
hit = int(am == cpos and lp[am] > pc.LP_FLOOR)
|
| 180 |
+
hits += hit
|
| 181 |
+
margins.append(m)
|
| 182 |
+
lat += r["latency_s"]
|
| 183 |
+
ptok += r["prompt_tokens"]
|
| 184 |
+
self.bump(forwards=1, latency_s=r["latency_s"], prompt_tokens=r["prompt_tokens"],
|
| 185 |
+
missing_letter_forwards=int(bool(missing)))
|
| 186 |
+
recs.append(dict(order=perm, correct_pos=cpos, lp=[round(x, 4) for x in lp], argmax=am,
|
| 187 |
+
hit=hit, margin=round(m, 4), missing=missing, top1_token=r["top1_token"]))
|
| 188 |
+
acc = hits / len(perms)
|
| 189 |
+
margin = sum(margins) / len(margins)
|
| 190 |
+
remove = bool(margin > pc.LOG2 and hits >= len(perms) - 1)
|
| 191 |
+
return dict(perms=recs, blind_acc_4perm=round(acc, 4), blind_margin=round(margin, 4),
|
| 192 |
+
remove=remove, n_forwards=len(perms), latency_s=round(lat, 4), prompt_tokens=ptok)
|
| 193 |
+
|
| 194 |
+
def visual(self, iid, row, opts, k, aidx):
|
| 195 |
+
vid, vpath = row["video_id"], row["video_path"]
|
| 196 |
+
info, images, keys = self.frames_b64(vid, vpath, "mid" if self.step == 2 else "all")
|
| 197 |
+
prompt = pc.PROMPT.format(intro=INTRO_VISUAL.format(n=len(images)), q=row["question"],
|
| 198 |
+
opts=pc.render_options(opts))
|
| 199 |
+
r = self.forward(prompt, images, f"{iid}/{pc.STEPS[self.step]}")
|
| 200 |
+
lp, missing, variants = pc.letter_logprobs(r["top"], k)
|
| 201 |
+
self.note_variants(variants)
|
| 202 |
+
am = pc.argmax_pos(lp)
|
| 203 |
+
m = pc.margin_of(lp, aidx)
|
| 204 |
+
correct = bool(am == aidx and lp[am] > pc.LP_FLOOR)
|
| 205 |
+
remove = bool(correct and m > pc.LOG2)
|
| 206 |
+
self.bump(forwards=1, latency_s=r["latency_s"], prompt_tokens=r["prompt_tokens"],
|
| 207 |
+
missing_letter_forwards=int(bool(missing)))
|
| 208 |
+
pre = "sf" if self.step == 2 else "v32_2b"
|
| 209 |
+
out = dict(video_id=vid, frame_keys=keys, n_frames=len(images), frame_wh=[info.get("w"), info.get("h")],
|
| 210 |
+
correct_pos=aidx, lp=[round(x, 4) for x in lp], argmax=am, missing=missing,
|
| 211 |
+
top1_token=r["top1_token"], remove=remove, n_forwards=1,
|
| 212 |
+
latency_s=r["latency_s"], prompt_tokens=r["prompt_tokens"])
|
| 213 |
+
out[f"{pre}_correct"] = correct
|
| 214 |
+
out[f"{pre}_margin"] = round(m, 4)
|
| 215 |
+
return out
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def run_unit(runner, unit, rows_by_id, workers, deadline, flush_every=20):
|
| 219 |
+
bench, part, n_parts, ids = unit
|
| 220 |
+
path = pc.unit_file(runner.step, bench, part, n_parts)
|
| 221 |
+
rows = [rows_by_id[i] for i in ids]
|
| 222 |
+
if runner.step >= 2: # same-video items share the frame cache
|
| 223 |
+
rows.sort(key=lambda r: (r["video_id"], r["item_id"]))
|
| 224 |
+
buf, n_done, t0 = [], 0, time.time()
|
| 225 |
+
stopped = False
|
| 226 |
+
with ThreadPoolExecutor(max_workers=workers) as ex:
|
| 227 |
+
pending = set()
|
| 228 |
+
it = iter(rows)
|
| 229 |
+
while True:
|
| 230 |
+
while len(pending) < workers * 2 and not stopped:
|
| 231 |
+
if deadline and time.time() > deadline:
|
| 232 |
+
stopped = True
|
| 233 |
+
break
|
| 234 |
+
r = next(it, None)
|
| 235 |
+
if r is None:
|
| 236 |
+
stopped = True
|
| 237 |
+
break
|
| 238 |
+
pending.add(ex.submit(runner.run_item, r))
|
| 239 |
+
if not pending:
|
| 240 |
+
break
|
| 241 |
+
done = next(as_completed(pending))
|
| 242 |
+
pending.discard(done)
|
| 243 |
+
buf.append(done.result())
|
| 244 |
+
n_done += 1
|
| 245 |
+
if len(buf) >= flush_every:
|
| 246 |
+
pc.append_rows(path, buf)
|
| 247 |
+
buf = []
|
| 248 |
+
if n_done % 200 == 0:
|
| 249 |
+
st = runner.stats
|
| 250 |
+
el = time.time() - t0
|
| 251 |
+
log(f"{bench}.p{part}: {n_done}/{len(rows)} items, {st['forwards']} fwd total, "
|
| 252 |
+
f"{n_done / el:.2f} items/s, mean fwd latency {st['latency_s'] / max(st['forwards'], 1):.3f}s, "
|
| 253 |
+
f"errors={st['errors']}", f"step{runner.step}")
|
| 254 |
+
if buf:
|
| 255 |
+
pc.append_rows(path, buf)
|
| 256 |
+
return n_done, len(rows) - n_done
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def main():
|
| 260 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 261 |
+
ap.add_argument("--step", type=int, required=True, choices=[1, 2, 3])
|
| 262 |
+
ap.add_argument("--endpoint", default=None)
|
| 263 |
+
ap.add_argument("--workers", type=int, default=None)
|
| 264 |
+
ap.add_argument("--bench", default=None, help="comma list (default: all)")
|
| 265 |
+
ap.add_argument("--limit", type=int, default=None, help="first N eligible items per benchmark (smoke tests)")
|
| 266 |
+
ap.add_argument("--max-minutes", type=float, default=None, help="stop starting new items after M minutes")
|
| 267 |
+
ap.add_argument("--max-unit", type=int, default=20000)
|
| 268 |
+
ap.add_argument("--shard", default=None, help="i/k (default: Slurm array env or 0/1)")
|
| 269 |
+
ap.add_argument("--plan-only", action="store_true", help="print the remaining work of this shard and exit")
|
| 270 |
+
a = ap.parse_args()
|
| 271 |
+
pc.ensure_dirs()
|
| 272 |
+
step = a.step
|
| 273 |
+
model_name, _snap = pc.MODELS[pc.STEP_MODEL[step]]
|
| 274 |
+
workers = a.workers or DEFAULT_WORKERS[step]
|
| 275 |
+
t_start = time.time()
|
| 276 |
+
|
| 277 |
+
df = load_items()
|
| 278 |
+
elig, notes = eligible(step, df)
|
| 279 |
+
if a.bench:
|
| 280 |
+
want = {b.strip() for b in a.bench.split(",") if b.strip()}
|
| 281 |
+
elig = elig[elig["benchmark"].isin(want)]
|
| 282 |
+
ok, errs = pc.load_step_rows(step)
|
| 283 |
+
todo = elig[~elig["item_id"].isin(set(ok))]
|
| 284 |
+
perm_fail = {i for i, n in errs.items() if n >= pc.MAX_ERRORS_PER_ITEM}
|
| 285 |
+
todo = todo[~todo["item_id"].isin(perm_fail)]
|
| 286 |
+
if a.limit:
|
| 287 |
+
todo = todo.sort_values("item_id").groupby("benchmark", sort=False).head(a.limit)
|
| 288 |
+
work = [(b, list(g["item_id"])) for b, g in todo.groupby("benchmark", sort=True)]
|
| 289 |
+
units = pc.plan_units(work, a.max_unit)
|
| 290 |
+
if a.shard:
|
| 291 |
+
tid, n = (int(x) for x in a.shard.split("/"))
|
| 292 |
+
else:
|
| 293 |
+
tid, n = pc.slurm_task()
|
| 294 |
+
mine, loads = pc.assign_units(units, n, tid)
|
| 295 |
+
n_mine = sum(len(u[3]) for u in mine)
|
| 296 |
+
log(f"step {step} ({pc.STEPS[step]}, {model_name}): eligible={len(elig)} done={len(ok)} "
|
| 297 |
+
f"permanently_failed={len(perm_fail)} remaining={len(todo)}; shard {tid}/{n} -> {len(mine)} unit(s), "
|
| 298 |
+
f"{n_mine} items (max shard load {max(loads) if loads else 0:.0f}); {'; '.join(notes)}", f"step{step}")
|
| 299 |
+
if a.plan_only:
|
| 300 |
+
print(f"REMAINING_TOTAL={len(todo)} REMAINING_SHARD={n_mine} UNITS={len(mine)}")
|
| 301 |
+
return
|
| 302 |
+
if not mine:
|
| 303 |
+
log("nothing to do", f"step{step}")
|
| 304 |
+
print("INCOMPLETE=0")
|
| 305 |
+
return
|
| 306 |
+
if not a.endpoint:
|
| 307 |
+
sys.exit("--endpoint required")
|
| 308 |
+
runner = Runner(step, a.endpoint.rstrip("/"), model_name, workers)
|
| 309 |
+
rows_by_id = {r["item_id"]: r for r in todo.to_dict("records")}
|
| 310 |
+
deadline = (t_start + a.max_minutes * 60) if a.max_minutes else None
|
| 311 |
+
left_total = 0
|
| 312 |
+
for u in mine:
|
| 313 |
+
if deadline and time.time() > deadline:
|
| 314 |
+
left_total += len(u[3])
|
| 315 |
+
continue
|
| 316 |
+
n_done, left = run_unit(runner, u, rows_by_id, workers, deadline)
|
| 317 |
+
left_total += left
|
| 318 |
+
log(f"{u[0]}.p{u[1]}: done {n_done}, left {left}", f"step{step}")
|
| 319 |
+
st = runner.stats
|
| 320 |
+
wall = time.time() - t_start
|
| 321 |
+
summary = dict(ts=time.strftime("%F %T"), stage=f"step{step}", shard=f"{tid}/{n}", model=model_name,
|
| 322 |
+
items=st["items"], forwards=st["forwards"], errors=st["errors"], removed=st["removed"],
|
| 323 |
+
wall_s=round(wall, 1), mean_fwd_latency_s=round(st["latency_s"] / max(st["forwards"], 1), 4),
|
| 324 |
+
fwd_per_s=round(st["forwards"] / max(wall, 1e-9), 3),
|
| 325 |
+
items_per_s=round(st["items"] / max(wall, 1e-9), 3),
|
| 326 |
+
mean_prompt_tokens=round(st["prompt_tokens"] / max(st["forwards"], 1), 1),
|
| 327 |
+
missing_letter_forwards=st["missing_letter_forwards"], decode_s=round(st["decode_s"], 1),
|
| 328 |
+
workers=workers, token_variants=dict(sorted(runner.variants.items(), key=lambda kv: -kv[1])[:8]),
|
| 329 |
+
left=left_total, slurm_job=os.environ.get("SLURM_JOB_ID"))
|
| 330 |
+
with open(os.path.join(pc.LOG_DIR, "pool_timing.jsonl"), "a") as f:
|
| 331 |
+
f.write(json.dumps(summary) + "\n")
|
| 332 |
+
log(json.dumps(summary), f"step{step}")
|
| 333 |
+
print(f"INCOMPLETE={left_total}")
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
if __name__ == "__main__":
|
| 337 |
+
main()
|