File size: 16,194 Bytes
2b9db19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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_VISUAL  # noqa: E402  (verbatim copies of stage_p1_runner)

MAX_ATTEMPTS = 5
DEFAULT_WORKERS = {1: 32, 2: 16, 3: 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."""
    df = df[df["format"] == "mcq"]
    notes = []
    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 >= 2:
        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)}")
    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)
            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):
        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)
            prompt = pc.PROMPT.format(intro=INTRO_BLIND, q=question, opts=pc.render_options(texts))
            r = self.forward(prompt, None, f"{iid}/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)
        return dict(perms=recs, blind_acc_4perm=round(acc, 4), blind_margin=round(margin, 4),
                    remove=remove, n_forwards=len(perms), latency_s=round(lat, 4), prompt_tokens=ptok)

    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")
        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 = "sf" if self.step == 2 else "v32_2b"
        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"])
        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 >= 2:                                  # 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])
    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()