Enxin commited on
Commit
15689bb
·
verified ·
1 Parent(s): afe458e

add code/

Browse files
code/exp/config.yaml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # trimmed config for the off-cluster run package; the data roots come from BENCH_BASE (common.py)
2
+ paths:
3
+ base: /replace/with/BENCH_BASE
4
+ work: /replace/with/BENCH_BASE/work
5
+ store: /replace/with/BENCH_BASE/store
6
+ limits:
7
+ work_dir_limit_gb: 100000
8
+ store_limit_gb: 100000
9
+ models:
10
+ diag_v: Qwen/Qwen3-VL-8B-Instruct
11
+ normalize:
12
+ max_frames: 1024
13
+ too_short_frames: 32
code/exp/pipeline/common.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared infra: config, disk guard, manifest, failures, remote-zip access."""
2
+ import hashlib
3
+ import json
4
+ import os
5
+ import subprocess
6
+ import time
7
+ import zipfile
8
+
9
+ import yaml
10
+
11
+ CFG = yaml.safe_load(open(os.path.join(os.path.dirname(__file__), "..", "config.yaml")))
12
+ # BENCH_BASE / BENCH_WORK / BENCH_STORE (2026-09-07): relocate the data roots for off-cluster run packages
13
+ BASE = os.environ.get("BENCH_BASE") or CFG["paths"]["base"]
14
+ WORK = os.environ.get("BENCH_WORK") or (f"{BASE}/work" if os.environ.get("BENCH_BASE") else CFG["paths"]["work"])
15
+ STORE = os.environ.get("BENCH_STORE") or (f"{BASE}/store" if os.environ.get("BENCH_BASE") else CFG["paths"]["store"])
16
+ for d in (WORK, STORE, f"{STORE}/annotations", f"{STORE}/samples",
17
+ f"{STORE}/needed_videos", f"{STORE}/normalized", f"{STORE}/audio",
18
+ f"{BASE}/logs"):
19
+ os.makedirs(d, exist_ok=True)
20
+
21
+ FAILURES = f"{BASE}/logs/failures.jsonl"
22
+ MANIFEST = f"{BASE}/logs/manifest.jsonl"
23
+ DEDUP_LOG = f"{BASE}/logs/dedup_log.csv"
24
+
25
+
26
+ def log_failure(stage, key, error, **kw):
27
+ rec = dict(ts=time.strftime("%F %T"), stage=stage, key=key, error=str(error)[:500], **kw)
28
+ with open(FAILURES, "a") as f:
29
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
30
+
31
+
32
+ def manifest_done():
33
+ done = {}
34
+ if os.path.exists(MANIFEST):
35
+ with open(MANIFEST) as f:
36
+ for line in f:
37
+ try:
38
+ r = json.loads(line)
39
+ if r.get("status") == "done":
40
+ done[r["key"]] = r
41
+ except Exception:
42
+ pass
43
+ return done
44
+
45
+
46
+ def manifest_write(key, status, **kw):
47
+ with open(MANIFEST, "a") as f:
48
+ f.write(json.dumps(dict(key=key, status=status, ts=time.strftime("%F %T"), **kw),
49
+ ensure_ascii=False) + "\n")
50
+
51
+
52
+ def du_gb(path):
53
+ r = subprocess.run(["du", "-sb", path], capture_output=True, text=True)
54
+ try:
55
+ return int(r.stdout.split()[0]) / 1e9
56
+ except Exception:
57
+ return 0.0
58
+
59
+
60
+ _DISK_GUARD_CACHE = {"ts": 0.0, "val": None}
61
+ DISK_GUARD_TTL_S = 600 # du over the store (~55k files on a network FS) takes seconds; with ~20
62
+ # concurrent stage_c processes a per-item du dominated wall time (2026-09-03)
63
+
64
+
65
+ def disk_guard(force=False):
66
+ """Return (ok, work_gb, store_gb). Caller MUST stop when not ok.
67
+ Result is cached per process for DISK_GUARD_TTL_S; a not-ok result is never cached."""
68
+ now = time.time()
69
+ c = _DISK_GUARD_CACHE
70
+ if not force and c["val"] is not None and c["val"][0] and now - c["ts"] < DISK_GUARD_TTL_S:
71
+ return c["val"]
72
+ w, s = du_gb(WORK), du_gb(STORE)
73
+ ok = w <= CFG["limits"]["work_dir_limit_gb"] and s <= CFG["limits"]["store_limit_gb"]
74
+ c["ts"], c["val"] = now, (ok, w, s)
75
+ return ok, w, s
76
+
77
+
78
+ def sha256_file(path, bufsize=1 << 20):
79
+ h = hashlib.sha256()
80
+ with open(path, "rb") as f:
81
+ while True:
82
+ b = f.read(bufsize)
83
+ if not b:
84
+ break
85
+ h.update(b)
86
+ return h.hexdigest()
87
+
88
+
89
+ def hf_token():
90
+ p = os.path.expanduser("~/.cache/huggingface/token")
91
+ return open(p).read().strip() if os.path.exists(p) else None
92
+
93
+
94
+ def api_tree(repo, revision=None):
95
+ """Full recursive file listing with sizes. Uses huggingface_hub pagination —
96
+ the raw /tree REST endpoint silently truncates at 1000 entries.
97
+ revision=None keeps the historical behavior (default branch / main);
98
+ pass a commit sha or tag to pin (see exp/watch/REVISION_PINNING.md)."""
99
+ from huggingface_hub import HfApi
100
+ out = []
101
+ for it in HfApi(token=hf_token()).list_repo_tree(repo, repo_type="dataset",
102
+ recursive=True, expand=False,
103
+ revision=revision):
104
+ if getattr(it, "size", None) is not None: # RepoFile
105
+ out.append(dict(type="file", path=it.path, size=it.size))
106
+ return out
107
+
108
+
109
+ _fs = None
110
+
111
+ def hffs():
112
+ global _fs
113
+ if _fs is None:
114
+ from huggingface_hub import HfFileSystem
115
+ _fs = HfFileSystem(token=hf_token())
116
+ return _fs
117
+
118
+
119
+ _zip_handles = {}
120
+
121
+ def remote_zip(repo, zip_path):
122
+ """Open a zip inside an HF dataset repo with range reads. Cached per path."""
123
+ key = f"datasets/{repo}/{zip_path}"
124
+ if key not in _zip_handles:
125
+ f = hffs().open(key, "rb")
126
+ _zip_handles[key] = zipfile.ZipFile(f)
127
+ return _zip_handles[key]
128
+
129
+
130
+ def zip_namelist(repo, zip_path):
131
+ return remote_zip(repo, zip_path).namelist()
132
+
133
+
134
+ def extract_member(repo, zip_path, member, dest):
135
+ """Stream ONE member out of a remote zip (only its bytes transferred)."""
136
+ zf = remote_zip(repo, zip_path)
137
+ with zf.open(member) as src, open(dest, "wb") as out:
138
+ while True:
139
+ b = src.read(1 << 20)
140
+ if not b:
141
+ break
142
+ out.write(b)
143
+ return dest
144
+
145
+
146
+ TAR_EXT = (".tar", ".tar.gz", ".tgz", ".tar.bz2")
147
+ TAR_COMPRESSED = (".tar.gz", ".tgz", ".tar.bz2")
148
+ TAR_STREAM_CAP_GB = 10 # compressed tars have no random access; cap full-stream size
149
+
150
+ _tar_handles = {}
151
+
152
+
153
+ class ConcatFile:
154
+ """Read-only seekable concatenation of fsspec files (split .tar.part.* archives)."""
155
+
156
+ def __init__(self, fs, paths, sizes=None):
157
+ self.fs = fs
158
+ self.parts = []
159
+ off = 0
160
+ for i, p in enumerate(paths):
161
+ size = sizes[i] if sizes and sizes[i] is not None else fs.info(p)["size"]
162
+ self.parts.append((off, size, p))
163
+ off += size
164
+ self.size = off
165
+ self.pos = 0
166
+ self._open = {}
167
+
168
+ # tarfile callers use `with _open_remote(...) as f` — without these the
169
+ # first chunked-archive access dies with AttributeError: __enter__
170
+ def __enter__(self):
171
+ return self
172
+
173
+ def __exit__(self, *exc):
174
+ self.close()
175
+ return False
176
+
177
+ def seek(self, pos, whence=0):
178
+ if whence == 1:
179
+ pos += self.pos
180
+ elif whence == 2:
181
+ pos += self.size
182
+ self.pos = max(0, pos)
183
+ return self.pos
184
+
185
+ def tell(self):
186
+ return self.pos
187
+
188
+ def read(self, n=-1):
189
+ if n is None or n < 0:
190
+ n = self.size - self.pos
191
+ out = []
192
+ while n > 0 and self.pos < self.size:
193
+ hit = next(((o, s, p) for o, s, p in self.parts if o <= self.pos < o + s), None)
194
+ if hit is None:
195
+ break
196
+ off, size, p = hit
197
+ f = self._open.get(p)
198
+ if f is None:
199
+ f = self._open[p] = self.fs.open(p, "rb")
200
+ f.seek(self.pos - off)
201
+ chunk = f.read(min(n, off + size - self.pos))
202
+ if not chunk:
203
+ break
204
+ out.append(chunk)
205
+ self.pos += len(chunk)
206
+ n -= len(chunk)
207
+ return b"".join(out)
208
+
209
+ def seekable(self):
210
+ return True
211
+
212
+ def readable(self):
213
+ return True
214
+
215
+ def close(self):
216
+ for f in self._open.values():
217
+ f.close()
218
+
219
+
220
+ _glob_cache = {}
221
+
222
+
223
+ def _natsort_key(p):
224
+ """Natural sort: 'x.part2' < 'x.part10' (lexicographic puts part10 between
225
+ part1 and part2 and CORRUPTS concatenated split archives)."""
226
+ import re
227
+ return [int(t) if t.isdigit() else t for t in re.split(r"(\d+)", str(p))]
228
+
229
+
230
+ def _open_remote(key):
231
+ """fsspec handle for a repo path; a '*' means split chunks joined in order.
232
+ glob+sizes are cached per pattern: without this every per-key fallback
233
+ redoes 1 glob + N info() calls against the HF paths-info API and the
234
+ 1000 req/5min quota dies (VideoEval-Pro: 194 keys x 36 calls -> 429)."""
235
+ fs = hffs()
236
+ if "*" in key:
237
+ cached = _glob_cache.get(key)
238
+ if cached is None:
239
+ detail = fs.glob(key, detail=True)
240
+ if not detail:
241
+ raise FileNotFoundError(key)
242
+ cached = sorted(((p, (info or {}).get("size"))
243
+ for p, info in detail.items()),
244
+ key=lambda x: _natsort_key(x[0]))
245
+ _glob_cache[key] = cached
246
+ return ConcatFile(fs, [p for p, _ in cached], [s for _, s in cached])
247
+ return fs.open(key, "rb")
248
+
249
+
250
+ def remote_tar(repo, tar_path):
251
+ """Seekable tarfile for plain .tar (range reads). None for compressed.
252
+ If tar_path itself doesn't exist, looks for split parts <tar_path>.part*."""
253
+ import tarfile
254
+ key = f"datasets/{repo}/{tar_path}"
255
+ if key not in _tar_handles:
256
+ if tar_path.lower().endswith(TAR_COMPRESSED) or "*" in tar_path:
257
+ _tar_handles[key] = None
258
+ else:
259
+ fs = hffs()
260
+ if fs.exists(key):
261
+ f = fs.open(key, "rb")
262
+ else:
263
+ parts = sorted(fs.glob(key + ".part*"), key=_natsort_key)
264
+ if not parts:
265
+ raise FileNotFoundError(key)
266
+ f = ConcatFile(fs, parts)
267
+ _tar_handles[key] = tarfile.open(fileobj=f, mode="r:")
268
+ return _tar_handles[key]
269
+
270
+
271
+ def tar_namelist(repo, tar_path):
272
+ """Member listing with a disk cache — remote tar walks cost ~0.1s/member."""
273
+ import tarfile
274
+ cache_dir = f"{STORE}/tar_index"
275
+ os.makedirs(cache_dir, exist_ok=True)
276
+ cache = f"{cache_dir}/{repo.replace('/', '__')}__{tar_path.replace('/', '__')}.json"
277
+ if os.path.exists(cache):
278
+ return json.load(open(cache))
279
+ tf = remote_tar(repo, tar_path)
280
+ if tf is not None:
281
+ names = [m.name for m in tf.getmembers() if m.isfile()]
282
+ else:
283
+ names = []
284
+ with _open_remote(f"datasets/{repo}/{tar_path}") as f, \
285
+ tarfile.open(fileobj=f, mode="r|*") as t:
286
+ for m in t:
287
+ if m.isfile():
288
+ names.append(m.name)
289
+ tmp = f"{cache}.tmp{os.getpid()}" # atomic: concurrent shards write it
290
+ json.dump(names, open(tmp, "w"))
291
+ os.replace(tmp, cache)
292
+ return names
293
+
294
+
295
+ def extract_tar_member(repo, tar_path, member, dest):
296
+ import shutil
297
+ import tarfile
298
+ tf = remote_tar(repo, tar_path)
299
+ if tf is not None:
300
+ src = tf.extractfile(member)
301
+ with open(dest, "wb") as out:
302
+ shutil.copyfileobj(src, out, 1 << 20)
303
+ return dest
304
+ with _open_remote(f"datasets/{repo}/{tar_path}") as f, \
305
+ tarfile.open(fileobj=f, mode="r|*") as t:
306
+ for m in t:
307
+ if m.name == member:
308
+ with open(dest, "wb") as out:
309
+ shutil.copyfileobj(t.extractfile(m), out, 1 << 20)
310
+ return dest
311
+ raise KeyError(f"{member} not in {tar_path}")
312
+
313
+
314
+ def extract_tar_members_bulk(repo, tar_path, members, dest_dir):
315
+ """One streaming pass through a (compressed) tar, extracting every wanted
316
+ member — avoids re-streaming the whole archive per video."""
317
+ import shutil
318
+ import tarfile
319
+ os.makedirs(dest_dir, exist_ok=True)
320
+ want = set(members)
321
+ got = {}
322
+ with _open_remote(f"datasets/{repo}/{tar_path}") as f, \
323
+ tarfile.open(fileobj=f, mode="r|*") as t:
324
+ for m in t:
325
+ if m.name in want:
326
+ dest = os.path.join(dest_dir, m.name.replace("/", "_"))
327
+ with open(dest, "wb") as out:
328
+ shutil.copyfileobj(t.extractfile(m), out, 1 << 20)
329
+ got[m.name] = dest
330
+ if len(got) == len(want):
331
+ break
332
+ return got
333
+
334
+
335
+ def hf_download_file(repo, path, dest_dir, revision=None):
336
+ """revision=None keeps the historical behavior (default branch / main);
337
+ pass a commit sha to pin (see exp/watch/REVISION_PINNING.md)."""
338
+ from huggingface_hub import hf_hub_download
339
+ return hf_hub_download(repo_id=repo, filename=path, repo_type="dataset",
340
+ local_dir=dest_dir, token=hf_token(), revision=revision)
341
+
342
+
343
+ def ffprobe(path):
344
+ r = subprocess.run(["ffprobe", "-v", "error", "-print_format", "json",
345
+ "-show_format", "-show_streams", path],
346
+ capture_output=True, text=True, timeout=300)
347
+ return json.loads(r.stdout)
code/exp/pipeline/extract_frames.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared frame extraction for Stage D (caption + AuroraCap runners).
2
+
3
+ Contract (unified across all stages):
4
+ - indices = round(linspace(0, n_frames-1, 32)) over meta.json n_frames
5
+ - decode via decord -> cv2 -> ffmpeg-select fallback
6
+ - JPEG q=85, long side capped at 768px
7
+ - single_frame condition = THE MIDDLE FRAME = round((n_frames-1)/2)
8
+ (= sample_indices(n_frames, 1); the data contract and stage_e1_api's
9
+ remote extractor use this rule — an earlier version of this module took
10
+ position 16 of the 32-index list, round(16*(n-1)/31), which drifts off
11
+ the true middle)
12
+
13
+ frames_for_hash() deduplicates repeated indices (videos with n_frames < 32
14
+ produce duplicate indices); callers can report len(result) as n_frames_used.
15
+ Dependency-light on purpose: json/PIL only; decord/cv2 optional.
16
+ """
17
+ import io
18
+ import json
19
+ import os
20
+ import subprocess
21
+ import tempfile
22
+
23
+ from PIL import Image
24
+
25
+ N_FRAMES_DEFAULT = 32
26
+ LONG_SIDE = 768
27
+ JPEG_QUALITY = 85
28
+
29
+
30
+ def sample_indices(n_frames, n=N_FRAMES_DEFAULT):
31
+ """round(linspace(0, n_frames-1, n)) without numpy. May contain duplicates."""
32
+ if n_frames <= 0:
33
+ raise ValueError("n_frames must be positive")
34
+ if n == 1:
35
+ return [round((n_frames - 1) / 2)]
36
+ return [round(i * (n_frames - 1) / (n - 1)) for i in range(n)]
37
+
38
+
39
+ def _resize(img):
40
+ w, h = img.size
41
+ m = max(w, h)
42
+ if m > LONG_SIDE:
43
+ img = img.resize((max(1, round(w * LONG_SIDE / m)),
44
+ max(1, round(h * LONG_SIDE / m))), Image.LANCZOS)
45
+ return img.convert("RGB")
46
+
47
+
48
+ def _decode_decord(path, idxs):
49
+ import decord
50
+ vr = decord.VideoReader(path, num_threads=2)
51
+ avail = len(vr)
52
+ uniq = sorted({min(i, avail - 1) for i in idxs})
53
+ out = {}
54
+ for c0 in range(0, len(uniq), 64): # chunked: 600 frames of 720p as one batch = ~1.7 GB
55
+ chunk = uniq[c0:c0 + 64]
56
+ batch = vr.get_batch(chunk).asnumpy()
57
+ for j, u in enumerate(chunk):
58
+ out[u] = Image.fromarray(batch[j])
59
+ return out
60
+
61
+
62
+ def _decode_cv2(path, idxs):
63
+ import cv2
64
+ cap = cv2.VideoCapture(path)
65
+ if not cap.isOpened():
66
+ raise RuntimeError(f"cv2 cannot open {path}")
67
+ want = sorted(set(idxs))
68
+ out, pos = {}, 0
69
+ hi = want[-1]
70
+ wi = 0
71
+ while wi < len(want):
72
+ ok = cap.grab()
73
+ if not ok:
74
+ break
75
+ if pos == want[wi]:
76
+ ok, fr = cap.retrieve()
77
+ if not ok:
78
+ break
79
+ out[pos] = Image.fromarray(cv2.cvtColor(fr, cv2.COLOR_BGR2RGB))
80
+ wi += 1
81
+ pos += 1
82
+ if pos > hi:
83
+ break
84
+ cap.release()
85
+ if not out:
86
+ raise RuntimeError(f"cv2 decoded 0/{len(want)} frames from {path}")
87
+ last = max(out)
88
+ for w in want: # clamp missing tail indices to last decoded frame
89
+ if w not in out:
90
+ out[w] = out[last]
91
+ return out
92
+
93
+
94
+ def _decode_ffmpeg(path, idxs):
95
+ uniq = sorted(set(idxs))
96
+ sel = "+".join(f"eq(n\\,{i})" for i in uniq)
97
+ with tempfile.TemporaryDirectory() as td:
98
+ cmd = [os.environ.get("FFMPEG_BIN", "ffmpeg"), "-y", "-v", "error",
99
+ "-i", path, "-vf", f"select='{sel}'", "-vsync", "0",
100
+ f"{td}/f_%05d.jpg"]
101
+ subprocess.run(cmd, check=True, capture_output=True, timeout=1800)
102
+ files = sorted(os.listdir(td))
103
+ if not files:
104
+ raise RuntimeError(f"ffmpeg extracted 0 frames from {path}")
105
+ imgs = [Image.open(os.path.join(td, f)) for f in files]
106
+ for im in imgs:
107
+ im.load()
108
+ out = {}
109
+ for j, u in enumerate(uniq): # ffmpeg may drop trailing frames; clamp
110
+ out[u] = imgs[min(j, len(imgs) - 1)]
111
+ return out
112
+
113
+
114
+ def _decode(path, idxs):
115
+ errs = []
116
+ for fn in (_decode_decord, _decode_cv2, _decode_ffmpeg):
117
+ try:
118
+ return fn(path, idxs)
119
+ except ImportError:
120
+ continue
121
+ except Exception as e:
122
+ errs.append(f"{fn.__name__}: {e}")
123
+ raise RuntimeError("all decoders failed: " + " | ".join(errs))
124
+
125
+
126
+ def frames_for_hash(store, content_hash, n=N_FRAMES_DEFAULT, single=False):
127
+ """Return list[PIL.Image] (RGB, long side <=768) for a normalized video.
128
+
129
+ single=True -> [middle frame] = round((n_frames-1)/2), the contract rule
130
+ shared with stage_e1_api's remote extractor.
131
+ Otherwise the n sampled frames with duplicate indices removed
132
+ (order preserved); len(result) == n unless n_frames < n.
133
+ """
134
+ d = os.path.join(store, "normalized", content_hash)
135
+ meta = json.load(open(os.path.join(d, "meta.json")))
136
+ if single:
137
+ idxs = sample_indices(meta["n_frames"], 1)
138
+ else:
139
+ idxs = sample_indices(meta["n_frames"], n)
140
+ keep = list(dict.fromkeys(idxs)) # dedupe, keep order
141
+ decoded = _decode(os.path.join(d, "video.mp4"), keep)
142
+ avail_max = max(decoded)
143
+ return [_resize(decoded[min(i, avail_max)]) for i in keep]
144
+
145
+
146
+ def to_jpeg_bytes(img):
147
+ buf = io.BytesIO()
148
+ img.save(buf, format="JPEG", quality=JPEG_QUALITY)
149
+ return buf.getvalue()
150
+
151
+
152
+ def to_data_url(img):
153
+ import base64
154
+ return "data:image/jpeg;base64," + base64.b64encode(to_jpeg_bytes(img)).decode()
code/exp/pipeline/scoring.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
code/exp/pipeline/stage_p1_runner.py ADDED
@@ -0,0 +1,777 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage P1 — DIAG_V profiling conditions over sampled benchmarks (runs ON 104).
2
+
3
+ Model: DIAG_V = config models.diag_v (Qwen/Qwen3-VL-8B-Instruct) served by the
4
+ local vLLM fleet (default endpoints localhost:8011-8016, round-robin).
5
+ NOTE: the fleet must be serving with --limit-mm-per-prompt '{"image": 128}'
6
+ and --max-model-len 65536 (MM_IMAGES=128 MAX_LEN=65536 serve_qwen3vl.sh);
7
+ the original 32-image/32k launch rejects v_128 and storage-res v_32 prompts.
8
+
9
+ Input : store/samples/<bench>.jsonl rows {qid,question,options,answer,
10
+ subcategory,video_ref}; video_key = f"{repo}::{zip_path}::{member}"
11
+ -> logs/manifest.jsonl (status=done) content_hash
12
+ -> store/normalized/<hash>/{video.mp4,meta.json}. The normalized MP4
13
+ is the only visual source.
14
+ Output: store/p1_raw/<condition>/<bench>__DIAG_V.jsonl
15
+ {qid, pred_raw, status, meta{...}} (append-only)
16
+ store/conditions_results.csv
17
+ benchmark,condition,model,question_id,correct,raw_output_path
18
+ (append-only; resume dedups on (benchmark,condition,question_id))
19
+ logs/p1_timing.jsonl per (bench,condition) timing/token stats
20
+ Failures -> common.log_failure (logs/failures.jsonl); never silently skipped.
21
+
22
+ Conditions (frame targets are TIME-uniform over meta frame_timestamps; frame
23
+ index = nearest timestamp; duplicate indices deduped, order kept):
24
+ v_blind no frames, same prompt skeleton
25
+ v_1 the middle element (position 16, 0-based) of the 32-frame grid
26
+ v_32 32 frames, storage resolution
27
+ v_32_s448 v_32 frames, short side downscaled to 448 at decode time.
28
+ Videos stored at short side 480 (meta normalized_short_side)
29
+ are NOT re-inferred: the v_32 result row is copied with
30
+ meta.reused_from = "v_32".
31
+ v_32_s224 v_32 frames, short side downscaled to 224
32
+ v_128 128 frames time-uniform; n_frames < 128 -> all frames,
33
+ meta.capped = True
34
+ v_32_shuffle exactly the v_32 frames, order shuffled by one fixed per-item
35
+ permutation random.Random(f"42|{qid}"); meta.perm_seed records
36
+ the seed string
37
+ v_half1/2 16 frames time-uniform inside the first / second temporal half
38
+ v_32_off1/2 32-cell uniform grid with a random phase offset
39
+ phase = random.Random(f"42|{qid}|off1|2").uniform(0,1);
40
+ target_j = t0 + (j + phase) * span/32; meta.offset = phase
41
+ too_short=True videos skip {v_128, v_32_shuffle, v_half1/2, v_32_off1/2}:
42
+ the row is recorded with status=NA (raw + correct=NA in the csv).
43
+
44
+ Design decisions (recorded here on purpose):
45
+ * JPEG q=85 everywhere (extract_frames convention); v_32 sends the frames
46
+ at storage resolution (no 768 long-side cap — the resolution ladder
47
+ s448/s224 must sit BELOW the base condition).
48
+ * Context safety: est. Qwen3-VL tokens/img = ceil(w/32)*ceil(h/32) (+small
49
+ overhead). If a prompt estimate exceeds --token-budget (default 58000),
50
+ all frames are scaled by sqrt(budget/est) and meta.fit_short_side records
51
+ the resulting short side (mainly v_128 on 720p-stored videos, which
52
+ cannot physically fit at storage res in a 65536 ctx).
53
+ * Scoring: scoring.score(pred, answer, options, question_format from
54
+ ../video_benchmarks.csv).
55
+ * Decode: extract_frames._decode (decord -> cv2 -> ffmpeg); per-video LRU
56
+ cache of storage-res JPEGs keyed (hash, index-tuple) so v_32 / s448 /
57
+ s224 / shuffle share one decode pass.
58
+
59
+ Usage (on 104, vllm_qwen python):
60
+ python stage_p1_runner.py --bench MVBench,LVBench --conditions v_blind,v_32 \
61
+ --limit 300 --workers 12 [--endpoints URL,URL,...] [--dry-run]
62
+
63
+ Task 11 conditions (2026-09-07, notes/server_tasks_2026-09-07.md):
64
+ v_32_s168 / v_32_s336 the v_32 frames, short side 168 / 336 (resolution ladder with s224, s448, v_32)
65
+ v_8_s224 / v_128_s224 8 / 128 time-uniform frames at short side 224 (frame-count ladder with v_32_s224);
66
+ v_128_s224: n_frames < 128 -> all frames, meta.capped = True
67
+ v_fps{0.25,0.5,1,2}_s224 nearest stored frame to a fixed-fps grid from t0, deduped, short side 224;
68
+ N_max = min(--max-images, floor((--token-budget - 1500) / tokens_per_frame)) with
69
+ tokens_per_frame = ceil(w/32)*ceil(h/32)+6 at the 224 dims of the video; when the grid
70
+ exceeds N_max the frames are re-sampled time-uniformly to N_max and meta.capped_ctx =
71
+ True (meta also records fps, n_grid, n_max, tokens_per_frame, n_frames_used).
72
+ too_short videos: v_128_s224 and the fps ladder are NA (existing rule); vLLM needs --max-model-len 65536 and
73
+ --limit-mm-per-prompt images >= --max-images (default 1024).
74
+ P1_MANIFEST manifest.jsonl to read instead of <base>/logs/manifest.jsonl (off-cluster run package)
75
+ BENCH_BASE / BENCH_STORE (common.py) relocate the data root / store off-cluster.
76
+
77
+ Environment overrides (2026-09-07, phase-B top-up items; both optional):
78
+ P1_SAMPLES_DIR sample directory read instead of store/samples
79
+ (top-up: exp/data/samples_topup)
80
+ P1_RESULTS_ROOT root that receives p1_raw/<cond>/<bench>__DIAG_V.jsonl and
81
+ conditions_results.csv instead of store (top-up:
82
+ store/topup -> store/topup/p1_raw, store/topup/conditions_results.csv);
83
+ the main P1 outputs are not read or written in that case.
84
+ """
85
+ import argparse
86
+ import base64
87
+ import csv
88
+ import io
89
+ import json
90
+ import math
91
+ import os
92
+ import random
93
+ import sys
94
+ import threading
95
+ import time
96
+ from collections import OrderedDict
97
+ from concurrent.futures import ThreadPoolExecutor, as_completed
98
+
99
+ import requests
100
+ from PIL import Image
101
+
102
+ HERE = os.path.dirname(os.path.abspath(__file__))
103
+ sys.path.insert(0, HERE)
104
+ from common import BASE, CFG, STORE, log_failure # noqa: E402
105
+ from extract_frames import JPEG_QUALITY, _decode # noqa: E402
106
+ from scoring import score # noqa: E402
107
+
108
+ MODEL_LABEL = "DIAG_V"
109
+ MODEL_NAME = CFG.get("models", {}).get("diag_v", "Qwen/Qwen3-VL-8B-Instruct")
110
+ SAMPLES_DIR = os.environ.get("P1_SAMPLES_DIR") or f"{STORE}/samples"
111
+ RESULTS_ROOT = os.environ.get("P1_RESULTS_ROOT") or STORE
112
+ RAW_DIR = f"{RESULTS_ROOT}/p1_raw"
113
+ RESULTS_CSV = f"{RESULTS_ROOT}/conditions_results.csv"
114
+ TIMING_LOG = f"{BASE}/logs/p1_timing.jsonl"
115
+ BENCH_CSV = os.path.join(HERE, "..", "video_benchmarks.csv")
116
+ DEFAULT_ENDPOINTS = ",".join(f"http://127.0.0.1:{p}/v1" for p in range(8011, 8017))
117
+
118
+ # ---- prompt skeleton: identical wording across all conditions -------------
119
+ ANSWER_INSTR = ("Reply with ONLY the option letter "
120
+ "(or the exact short answer if no options).")
121
+ PROMPT = "{intro}\n\nQuestion: {q}\n{opts}\n" + ANSWER_INSTR
122
+ INTRO_VISUAL = ("You are given {n} frame(s) sampled from a video. "
123
+ "Answer the question based on these frames.")
124
+ INTRO_OPT_ONLY = ("You are given NO frames from the video and NO question text. "
125
+ "Using only the answer options below, choose the option most likely to be correct.")
126
+ PROMPT_OPT_ONLY = "{intro}\n\n{opts}\n" + ANSWER_INSTR
127
+ INTRO_BLIND = ("You are given NO frames from the video. "
128
+ "Answer the question from the text alone.")
129
+
130
+ # Task 11 (notes/server_tasks_2026-09-07.md, "frames or pixels"): resolution ladder at the v_32 frames
131
+ # (s168 / s336 new; s224 / s448 / storage exist), frame-rate ladder at short side 224 (nearest stored
132
+ # frame to a fixed-fps grid, deduped, capped by what the context holds: N_max = min(--max-images,
133
+ # floor((--token-budget - TEXT_RESERVE) / tokens_per_frame_at_224)); capped videos are re-sampled
134
+ # time-uniformly to N_max and record meta.capped_ctx = True, n_grid, n_max), and a frame-count ladder
135
+ # at 224 (v_8_s224 / v_128_s224 new, v_32_s224 exists). vLLM must run with --max-model-len 65536 and
136
+ # --limit-mm-per-prompt images >= --max-images.
137
+ FPS_CONDS = {"v_fps0.25_s224": 0.25, "v_fps0.5_s224": 0.5, "v_fps1_s224": 1.0, "v_fps2_s224": 2.0}
138
+ CONDITIONS = ["v_blind", "v_1", "v_32", "v_32_s448", "v_32_s224", "v_128",
139
+ "v_32_shuffle", "v_half1", "v_half2", "v_32_off1", "v_32_off2",
140
+ "v_opt_only", # N0.2 options-only (2026-09-06): no frames, no question text
141
+ "v_32_s168", "v_32_s336", "v_8_s224", "v_128_s224",
142
+ "v_fps0.25_s224", "v_fps0.5_s224", "v_fps1_s224", "v_fps2_s224"]
143
+ NO_VIDEO_CONDS = {"v_blind", "v_opt_only"}
144
+ NA_WHEN_TOO_SHORT = {"v_128", "v_32_shuffle", "v_half1", "v_half2",
145
+ "v_32_off1", "v_32_off2", "v_128_s224", *FPS_CONDS}
146
+ SHORT_SIDE = {"v_32_s448": 448, "v_32_s224": 224, "v_32_s168": 168, "v_32_s336": 336,
147
+ "v_8_s224": 224, "v_128_s224": 224, **{c: 224 for c in FPS_CONDS}}
148
+ V32_SHARED = {"v_32", "v_32_s448", "v_32_s224", "v_32_s168", "v_32_s336", "v_32_shuffle"}
149
+ MAX_ATTEMPTS = 6 # enough to ride out one wedged endpoint + ctx shrinks
150
+ TOKEN_OVERHEAD_PER_IMG = 6 # vision start/end tokens etc. (measured ~2-5)
151
+ TEXT_RESERVE_TOKENS = 1500 # prompt text + answer headroom when sizing the fps ladders
152
+ MAX_IMAGES_DEFAULT = 1024 # stored videos hold <= 1024 frames; vLLM --limit-mm-per-prompt must be >= this
153
+
154
+
155
+ def log(msg):
156
+ print(f"[P1] {msg}", file=sys.stderr, flush=True)
157
+
158
+
159
+ def video_key(row):
160
+ r = row["video_ref"]
161
+ return f"{r['repo']}::{r.get('zip_path', '')}::{r['member']}"
162
+
163
+
164
+ def fmt_opts(o):
165
+ if not o:
166
+ return ""
167
+ if isinstance(o, str):
168
+ return o
169
+ return "\n".join(str(x) for x in o)
170
+
171
+
172
+ def load_bench_fmt():
173
+ fmt = {}
174
+ if os.path.exists(BENCH_CSV):
175
+ for r in csv.DictReader(open(BENCH_CSV)):
176
+ fmt[r["name"]] = r.get("question_format", "")
177
+ return fmt
178
+
179
+
180
+ def manifest_map():
181
+ m = {}
182
+ for line in open(os.environ.get("P1_MANIFEST") or f"{BASE}/logs/manifest.jsonl"):
183
+ try:
184
+ r = json.loads(line)
185
+ except Exception:
186
+ continue
187
+ if r.get("status") == "done" and r.get("content_hash"):
188
+ m[r["key"]] = r["content_hash"]
189
+ return m
190
+
191
+
192
+ # ------------------------------------------------------- frame-grid selection
193
+ def _nearest_indices(ts, targets):
194
+ """Nearest frame index per target time; ts is sorted ascending."""
195
+ import bisect
196
+ out = []
197
+ for t in targets:
198
+ i = bisect.bisect_left(ts, t)
199
+ if i <= 0:
200
+ out.append(0)
201
+ elif i >= len(ts):
202
+ out.append(len(ts) - 1)
203
+ else:
204
+ out.append(i if ts[i] - t < t - ts[i - 1] else i - 1)
205
+ return out
206
+
207
+
208
+ def _uniform_times(t0, t1, k):
209
+ if k == 1:
210
+ return [(t0 + t1) / 2.0]
211
+ return [t0 + j * (t1 - t0) / (k - 1) for j in range(k)]
212
+
213
+
214
+ def _dedupe(idxs):
215
+ return list(dict.fromkeys(idxs))
216
+
217
+
218
+ def frame_dims_at(meta, short_side):
219
+ """(w, h) of a stored frame after downscaling its short side to `short_side` (never upscaled)."""
220
+ res = meta.get("original_resolution") or [1280, 720]
221
+ try:
222
+ ow, oh = int(res[0]), int(res[1])
223
+ except Exception:
224
+ ow, oh = 1280, 720
225
+ ss = int(meta.get("normalized_short_side") or min(ow, oh))
226
+ sc = ss / max(1, min(ow, oh))
227
+ w, h = max(1, round(ow * sc)), max(1, round(oh * sc)) # stored dims
228
+ s = min(1.0, short_side / max(1, min(w, h)))
229
+ return max(1, round(w * s)), max(1, round(h * s))
230
+
231
+
232
+ def tokens_per_frame(meta, short_side):
233
+ w, h = frame_dims_at(meta, short_side)
234
+ return math.ceil(w / 32) * math.ceil(h / 32) + TOKEN_OVERHEAD_PER_IMG
235
+
236
+
237
+ def cond_indices(cond, meta, qid, budget=None, max_images=None):
238
+ """-> (ordered index list, extra meta dict). Time-uniform via timestamps.
239
+ budget / max_images size the fps ladders (N_max); unused by the other conditions."""
240
+ n = int(meta["n_frames"])
241
+ ts = meta.get("frame_timestamps") or []
242
+ if len(ts) != n: # defensive: fall back to index grid
243
+ ts = list(range(n))
244
+ t0, t1 = ts[0], ts[-1]
245
+ grid32 = _nearest_indices(ts, _uniform_times(t0, t1, 32))
246
+ extra = {}
247
+ if cond == "v_1":
248
+ idxs = [grid32[16]]
249
+ elif cond in ("v_32", "v_32_s448", "v_32_s224", "v_32_s168", "v_32_s336"):
250
+ idxs = _dedupe(grid32)
251
+ elif cond == "v_8_s224":
252
+ idxs = _dedupe(_nearest_indices(ts, _uniform_times(t0, t1, 8)))
253
+ elif cond in ("v_128", "v_128_s224"):
254
+ if n < 128:
255
+ idxs = list(range(n))
256
+ extra["capped"] = True
257
+ else:
258
+ idxs = _dedupe(_nearest_indices(ts, _uniform_times(t0, t1, 128)))
259
+ extra["capped"] = False
260
+ elif cond in FPS_CONDS:
261
+ fps = FPS_CONDS[cond]
262
+ k = int(math.floor((t1 - t0) * fps + 1e-9)) + 1
263
+ idxs = _dedupe(_nearest_indices(ts, [t0 + j / fps for j in range(k)]))
264
+ extra.update(fps=fps, n_grid=len(idxs))
265
+ tpf = tokens_per_frame(meta, SHORT_SIDE[cond])
266
+ n_max = int(max(1, ((budget or 58000) - TEXT_RESERVE_TOKENS) // tpf))
267
+ n_max = min(n_max, max_images or MAX_IMAGES_DEFAULT)
268
+ extra.update(n_max=n_max, tokens_per_frame=tpf)
269
+ if len(idxs) > n_max:
270
+ idxs = _dedupe(_nearest_indices(ts, _uniform_times(t0, t1, n_max)))
271
+ extra["capped_ctx"] = True
272
+ else:
273
+ extra["capped_ctx"] = False
274
+ elif cond == "v_32_shuffle":
275
+ idxs = _dedupe(grid32)
276
+ seed = f"42|{qid}"
277
+ random.Random(seed).shuffle(idxs)
278
+ extra["perm_seed"] = seed
279
+ elif cond in ("v_half1", "v_half2"):
280
+ tm = (t0 + t1) / 2.0
281
+ lo, hi = (t0, tm) if cond == "v_half1" else (tm, t1)
282
+ idxs = _dedupe(_nearest_indices(ts, _uniform_times(lo, hi, 16)))
283
+ elif cond in ("v_32_off1", "v_32_off2"):
284
+ seed = f"42|{qid}|{'off1' if cond.endswith('off1') else 'off2'}"
285
+ phase = random.Random(seed).uniform(0.0, 1.0)
286
+ w = (t1 - t0) / 32.0
287
+ idxs = _dedupe(_nearest_indices(ts, [t0 + (j + phase) * w
288
+ for j in range(32)]))
289
+ extra["offset"] = round(phase, 6)
290
+ else:
291
+ raise ValueError(cond)
292
+ return idxs, extra
293
+
294
+
295
+ # ----------------------------------------------------------- decode + resize
296
+ class FrameCache:
297
+ """LRU of storage-resolution JPEG frame lists keyed (hash, idx-tuple)."""
298
+
299
+ def __init__(self, maxsize=12):
300
+ self.maxsize = maxsize
301
+ self.d = OrderedDict()
302
+ self.lock = threading.Lock()
303
+
304
+ def get(self, chash, idxs):
305
+ key = (chash, tuple(idxs))
306
+ with self.lock:
307
+ if key in self.d:
308
+ self.d.move_to_end(key)
309
+ return self.d[key]
310
+ path = os.path.join(STORE, "normalized", chash, "video.mp4")
311
+ decoded = _decode(path, list(idxs)) # dict idx -> PIL
312
+ avail = max(decoded)
313
+ frames = []
314
+ for i in idxs:
315
+ im = decoded[min(i, avail)].convert("RGB")
316
+ buf = io.BytesIO()
317
+ im.save(buf, format="JPEG", quality=JPEG_QUALITY)
318
+ frames.append((buf.getvalue(), im.size[0], im.size[1]))
319
+ with self.lock:
320
+ self.d[key] = frames
321
+ self.d.move_to_end(key)
322
+ while len(self.d) > self.maxsize:
323
+ self.d.popitem(last=False)
324
+ return frames
325
+
326
+
327
+ def _resize_jpegs(frames, scale=None, short_target=None):
328
+ """Downscale (never upscale) each (jpeg,w,h); returns new list."""
329
+ out = []
330
+ for blob, w, h in frames:
331
+ s = scale
332
+ if s is None:
333
+ s = short_target / min(w, h)
334
+ if s >= 1.0:
335
+ out.append((blob, w, h))
336
+ continue
337
+ im = Image.open(io.BytesIO(blob)).convert("RGB")
338
+ nw, nh = max(1, round(w * s)), max(1, round(h * s))
339
+ im = im.resize((nw, nh), Image.LANCZOS)
340
+ buf = io.BytesIO()
341
+ im.save(buf, format="JPEG", quality=JPEG_QUALITY)
342
+ out.append((buf.getvalue(), nw, nh))
343
+ return out
344
+
345
+
346
+ def est_tokens(frames):
347
+ return sum(math.ceil(w / 32) * math.ceil(h / 32) + TOKEN_OVERHEAD_PER_IMG
348
+ for _, w, h in frames)
349
+
350
+
351
+ def fit_to_budget(frames, budget):
352
+ """Scale all frames down until the token estimate fits. -> (frames, fitted)"""
353
+ fitted = False
354
+ for _ in range(4):
355
+ e = est_tokens(frames)
356
+ if e <= budget:
357
+ break
358
+ frames = _resize_jpegs(frames, scale=math.sqrt(budget / e) * 0.98)
359
+ fitted = True
360
+ return frames, fitted
361
+
362
+
363
+ # ------------------------------------------------------------------ vLLM API
364
+ class ContextTooLong(Exception):
365
+ pass
366
+
367
+
368
+ def vllm_chat(endpoint, prompt, frames, max_tokens=128, timeout=(10, 600)):
369
+ content = [{"type": "image_url",
370
+ "image_url": {"url": "data:image/jpeg;base64,"
371
+ + base64.b64encode(b).decode()}}
372
+ for b, _, _ in (frames or [])]
373
+ content.append({"type": "text", "text": prompt})
374
+ r = requests.post(f"{endpoint}/chat/completions",
375
+ json={"model": MODEL_NAME, "temperature": 0.0,
376
+ "max_tokens": max_tokens,
377
+ "messages": [{"role": "user", "content": content}]},
378
+ timeout=timeout)
379
+ if r.status_code == 400 and ("maximum" in r.text or "longer than" in r.text
380
+ or "context length" in r.text):
381
+ raise ContextTooLong(r.text[:200])
382
+ r.raise_for_status()
383
+ d = r.json()
384
+ text = (d["choices"][0]["message"]["content"] or "").strip()
385
+ ptok = (d.get("usage") or {}).get("prompt_tokens", 0)
386
+ if not text:
387
+ raise RuntimeError("empty completion")
388
+ return text, ptok
389
+
390
+
391
+ # ------------------------------------------------------------------ run state
392
+ class Ctx:
393
+ def __init__(self, args):
394
+ self.endpoints = [e.strip().rstrip("/") for e in args.endpoints.split(",")
395
+ if e.strip()]
396
+ self.budget = args.token_budget
397
+ self.max_images = getattr(args, "max_images", MAX_IMAGES_DEFAULT)
398
+ self.cache = FrameCache(args.cache_size)
399
+ self.key2hash = manifest_map()
400
+ self.bench_fmt = load_bench_fmt()
401
+ self.meta_cache, self.meta_lock = {}, threading.Lock()
402
+ self.io_lock = threading.Lock()
403
+ self.tick_lock = threading.Lock()
404
+ self.tick = 0
405
+ self.cooldown = {} # endpoint -> unix ts until which it is avoided
406
+ # a wedged instance (engine dead, frontend still accepting) is a
407
+ # tar pit: without a cooldown every retry eventually parks there
408
+ self.done = set() # (bench, cond, qid) already in the csv
409
+ self.v32_preds = {} # (bench, qid) -> pred_raw (for s448 reuse)
410
+ self.stats = {} # (bench, cond) -> counters
411
+ self.stats_lock = threading.Lock()
412
+ self._load_done()
413
+
414
+ def _load_done(self):
415
+ if not os.path.exists(RESULTS_CSV):
416
+ return
417
+ # repair a torn final line (killed mid-append): without the trailing
418
+ # newline the next append would fuse two rows into one corrupt record
419
+ with open(RESULTS_CSV, "rb+") as f:
420
+ f.seek(0, 2)
421
+ if f.tell() and (f.seek(-1, 2) or True) and f.read(1) != b"\n":
422
+ f.write(b"\n")
423
+ log("repaired missing trailing newline in conditions_results.csv")
424
+ for r in csv.DictReader(open(RESULTS_CSV)):
425
+ if r.get("model") == MODEL_LABEL:
426
+ self.done.add((r["benchmark"], r["condition"], r["question_id"]))
427
+
428
+ def preload_v32(self, bench):
429
+ p = f"{RAW_DIR}/v_32/{bench}__{MODEL_LABEL}.jsonl"
430
+ if os.path.exists(p):
431
+ for l in open(p):
432
+ try:
433
+ r = json.loads(l)
434
+ except Exception:
435
+ continue
436
+ if r.get("pred_raw") is not None:
437
+ self.v32_preds[(bench, str(r["qid"]))] = r["pred_raw"]
438
+
439
+ def next_endpoint(self):
440
+ now = time.time()
441
+ with self.tick_lock:
442
+ for _ in range(len(self.endpoints)):
443
+ self.tick += 1
444
+ ep = self.endpoints[self.tick % len(self.endpoints)]
445
+ if self.cooldown.get(ep, 0) <= now:
446
+ return ep
447
+ return self.endpoints[self.tick % len(self.endpoints)] # all cooling
448
+
449
+ def mark_dead(self, ep, secs=180):
450
+ with self.tick_lock:
451
+ self.cooldown[ep] = time.time() + secs
452
+ log(f"endpoint {ep} on {secs}s cooldown (timeout/conn error)")
453
+
454
+ def meta(self, chash):
455
+ with self.meta_lock:
456
+ if chash in self.meta_cache:
457
+ return self.meta_cache[chash]
458
+ m = json.load(open(os.path.join(STORE, "normalized", chash, "meta.json")))
459
+ with self.meta_lock:
460
+ self.meta_cache[chash] = m
461
+ return m
462
+
463
+ def bump(self, bench, cond, **kw):
464
+ with self.stats_lock:
465
+ st = self.stats.setdefault((bench, cond), dict(
466
+ infer=0, reused=0, na=0, fail=0, decode_s=0.0, infer_s=0.0,
467
+ prompt_tokens=0, fitted=0))
468
+ for k, v in kw.items():
469
+ st[k] += v
470
+
471
+ def write(self, bench, cond, qid, pred_raw, correct, meta, status="ok"):
472
+ raw_dir = f"{RAW_DIR}/{cond}"
473
+ os.makedirs(raw_dir, exist_ok=True)
474
+ raw_p = f"{raw_dir}/{bench}__{MODEL_LABEL}.jsonl"
475
+ row = dict(qid=qid, pred_raw=pred_raw, status=status, meta=meta)
476
+ with self.io_lock:
477
+ with open(raw_p, "a") as f:
478
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
479
+ new_csv = not os.path.exists(RESULTS_CSV)
480
+ with open(RESULTS_CSV, "a", newline="") as f:
481
+ w = csv.writer(f)
482
+ if new_csv:
483
+ w.writerow(["benchmark", "condition", "model",
484
+ "question_id", "correct", "raw_output_path"])
485
+ w.writerow([bench, cond, MODEL_LABEL, qid,
486
+ "NA" if correct is None else bool(correct), raw_p])
487
+ self.done.add((bench, cond, qid))
488
+ if cond == "v_32" and pred_raw is not None:
489
+ self.v32_preds[(bench, qid)] = pred_raw
490
+
491
+
492
+ # ------------------------------------------------------------------- workers
493
+ def infer_with_retry(ctx, prompt, frames, who):
494
+ """-> (text, prompt_tokens, n_shrinks, final_frames). Raises on final
495
+ failure. final_frames is what was ACTUALLY sent (ContextTooLong shrinks
496
+ mutate the frame list — meta.sent_short_side must reflect it)."""
497
+ shrinks = 0
498
+ empties = 0
499
+ last = None
500
+ for attempt in range(MAX_ATTEMPTS):
501
+ ep = ctx.next_endpoint()
502
+ try:
503
+ text, ptok = vllm_chat(ep, prompt, frames)
504
+ return text, ptok, shrinks, frames
505
+ except ContextTooLong as e:
506
+ if frames is None or shrinks >= 3:
507
+ raise
508
+ frames = _resize_jpegs(frames, scale=0.8)
509
+ shrinks += 1
510
+ last = e
511
+ except (requests.Timeout, requests.ConnectionError) as e:
512
+ ctx.mark_dead(ep) # likely wedged/dead instance
513
+ last = e
514
+ except RuntimeError as e:
515
+ if "empty completion" in str(e):
516
+ # temperature=0: an empty reply is (near-)deterministic —
517
+ # one cross-endpoint retry, then fail fast instead of
518
+ # burning all attempts on backoff sleeps
519
+ empties += 1
520
+ last = e
521
+ if empties >= 2:
522
+ raise RuntimeError(f"{who}: empty completion x{empties} "
523
+ f"(deterministic at temp=0)")
524
+ continue
525
+ last = e
526
+ time.sleep(min(30, 2 ** attempt + random.uniform(0, 2)))
527
+ except Exception as e:
528
+ last = e
529
+ time.sleep(min(30, 2 ** attempt + random.uniform(0, 2)))
530
+ raise RuntimeError(f"{who}: {type(last).__name__}: {str(last)[:200]}")
531
+
532
+
533
+ def process_row(ctx, bench, row, conds, fmt):
534
+ qid = str(row["qid"]) # csv resume keys are strings
535
+ pending = [c for c in conds if (bench, c, qid) not in ctx.done]
536
+ if not pending:
537
+ return
538
+ chash = ctx.key2hash.get(video_key(row))
539
+ if not chash:
540
+ # v_blind needs no video; every visual condition is a hard failure
541
+ visual = [c for c in pending if c not in NO_VIDEO_CONDS]
542
+ if visual:
543
+ for c in visual:
544
+ ctx.bump(bench, c, fail=1)
545
+ log_failure("stage_p1", f"{bench}::{qid}",
546
+ "no normalized video in manifest",
547
+ conditions=",".join(visual))
548
+ pending = [c for c in pending if c in NO_VIDEO_CONDS]
549
+ if not pending:
550
+ return
551
+ meta, stored_ss = {}, None
552
+ else:
553
+ try:
554
+ meta = ctx.meta(chash)
555
+ except Exception as e:
556
+ # manifest says done but meta.json is missing/corrupt: fail the
557
+ # visual conditions INDIVIDUALLY (qid + condition list logged),
558
+ # keep v_blind — never abort the whole row anonymously
559
+ visual = [c for c in pending if c not in NO_VIDEO_CONDS]
560
+ for c in visual:
561
+ ctx.bump(bench, c, fail=1)
562
+ if visual:
563
+ log_failure("stage_p1", f"{bench}::{qid}",
564
+ f"meta.json unreadable for {chash}: "
565
+ f"{type(e).__name__}: {e}",
566
+ conditions=",".join(visual))
567
+ pending = [c for c in pending if c in NO_VIDEO_CONDS]
568
+ if not pending:
569
+ return
570
+ meta, stored_ss = {}, None
571
+ else:
572
+ stored_ss = meta.get("normalized_short_side")
573
+ opts = row.get("options")
574
+ for cond in pending:
575
+ base_meta = dict(stored_short_side=stored_ss)
576
+ try:
577
+ if cond in NA_WHEN_TOO_SHORT and meta.get("too_short"):
578
+ ctx.write(bench, cond, qid, None, None,
579
+ dict(base_meta, reason="too_short"), status="NA")
580
+ ctx.bump(bench, cond, na=1)
581
+ continue
582
+ if cond == "v_32_s448" and stored_ss == 480:
583
+ pred = ctx.v32_preds.get((bench, qid))
584
+ if pred is None:
585
+ ctx.bump(bench, cond, fail=1)
586
+ log_failure("stage_p1", f"{bench}::{qid}::{cond}",
587
+ "v_32 result missing for stored-480 reuse; "
588
+ "run v_32 first")
589
+ continue
590
+ ok = score(pred, row.get("answer"), opts, fmt)
591
+ ctx.write(bench, cond, qid, pred, ok,
592
+ dict(base_meta, reused_from="v_32"))
593
+ ctx.bump(bench, cond, reused=1)
594
+ continue
595
+ frames = None
596
+ if cond == "v_blind":
597
+ prompt = PROMPT.format(intro=INTRO_BLIND, q=row["question"],
598
+ opts=fmt_opts(opts))
599
+ elif cond == "v_opt_only":
600
+ if not opts:
601
+ ctx.bump(bench, cond, fail=1)
602
+ log_failure("stage_p1", f"{bench}::{qid}", "v_opt_only: item has no options list", conditions=cond)
603
+ continue
604
+ prompt = PROMPT_OPT_ONLY.format(intro=INTRO_OPT_ONLY, opts=fmt_opts(opts))
605
+ else:
606
+ idxs, extra = cond_indices(cond, meta, qid, ctx.budget, ctx.max_images)
607
+ base_meta.update(extra)
608
+ t0 = time.time()
609
+ if cond in V32_SHARED and cond != "v_32":
610
+ # share the v_32 decode pass (shuffle reorders afterwards)
611
+ v32_idxs, _ = cond_indices("v_32", meta, qid)
612
+ got = ctx.cache.get(chash, v32_idxs)
613
+ pos = {ix: j for j, ix in enumerate(v32_idxs)}
614
+ frames = [got[pos[i]] for i in idxs]
615
+ elif cond in FPS_CONDS:
616
+ # one decode pass for the whole fps ladder: union of the four (capped) grids
617
+ union = set()
618
+ for c in FPS_CONDS:
619
+ union.update(cond_indices(c, meta, qid, ctx.budget, ctx.max_images)[0])
620
+ union = sorted(union)
621
+ got = ctx.cache.get(chash, union)
622
+ pos = {ix: j for j, ix in enumerate(union)}
623
+ frames = [got[pos[i]] for i in idxs]
624
+ else:
625
+ frames = ctx.cache.get(chash, idxs)
626
+ if cond in SHORT_SIDE:
627
+ frames = _resize_jpegs(frames, short_target=SHORT_SIDE[cond])
628
+ ctx.bump(bench, cond, decode_s=time.time() - t0)
629
+ frames, fitted = fit_to_budget(frames, ctx.budget)
630
+ if fitted:
631
+ base_meta["fit_short_side"] = min(min(w, h)
632
+ for _, w, h in frames)
633
+ ctx.bump(bench, cond, fitted=1)
634
+ base_meta["n_frames_used"] = len(frames)
635
+ prompt = PROMPT.format(intro=INTRO_VISUAL.format(n=len(frames)),
636
+ q=row["question"], opts=fmt_opts(opts))
637
+ t1 = time.time()
638
+ pred, ptok, shrinks, sent_frames = infer_with_retry(
639
+ ctx, prompt, frames, f"{bench}/{cond}/{qid}")
640
+ ctx.bump(bench, cond, infer_s=time.time() - t1, prompt_tokens=ptok)
641
+ if shrinks:
642
+ base_meta["ctx_shrinks"] = shrinks
643
+ if sent_frames:
644
+ # AFTER retries: ContextTooLong shrinks scale the frames, so
645
+ # the recorded resolution must be what was actually sent
646
+ base_meta["sent_short_side"] = min(min(w, h)
647
+ for _, w, h in sent_frames)
648
+ ok = score(pred, row.get("answer"), opts, fmt)
649
+ ctx.write(bench, cond, qid, pred[:2000], ok, base_meta)
650
+ ctx.bump(bench, cond, infer=1)
651
+ except Exception as e:
652
+ ctx.bump(bench, cond, fail=1)
653
+ log_failure("stage_p1", f"{bench}::{qid}::{cond}",
654
+ f"{type(e).__name__}: {e}")
655
+
656
+
657
+ # ---------------------------------------------------------------------- main
658
+ def order_conditions(conds):
659
+ bad = [c for c in conds if c not in CONDITIONS]
660
+ if bad:
661
+ sys.exit(f"unknown conditions: {bad}")
662
+ return [c for c in CONDITIONS if c in conds]
663
+
664
+
665
+ def run_bench(ctx, path, conds, limit, workers, dry):
666
+ bench = os.path.basename(path)[:-6]
667
+ fmt = ctx.bench_fmt.get(bench, "")
668
+ rows = [json.loads(l) for l in open(path) if l.strip()]
669
+ # duplicate qids would race past the resume check and append twice
670
+ seen_q, uniq = set(), []
671
+ for r in rows:
672
+ if str(r["qid"]) in seen_q:
673
+ continue
674
+ seen_q.add(str(r["qid"]))
675
+ uniq.append(r)
676
+ if len(uniq) != len(rows):
677
+ log(f"{bench}: {len(rows) - len(uniq)} duplicate qid row(s) in the "
678
+ f"samples file — deduped (first wins)")
679
+ rows = uniq
680
+ if limit:
681
+ rows = rows[:limit]
682
+ ctx.preload_v32(bench)
683
+ # sort by video hash so the frame cache gets adjacent same-video rows
684
+ rows.sort(key=lambda r: (ctx.key2hash.get(video_key(r), ""), str(r["qid"])))
685
+ todo = [r for r in rows
686
+ if any((bench, c, str(r["qid"])) not in ctx.done for c in conds)]
687
+ if dry:
688
+ for c in conds:
689
+ miss = sum(1 for r in rows
690
+ if (bench, c, str(r["qid"])) not in ctx.done)
691
+ na = reuse = novideo = 0
692
+ for r in rows:
693
+ if (bench, c, str(r["qid"])) in ctx.done:
694
+ continue
695
+ h = ctx.key2hash.get(video_key(r))
696
+ if not h:
697
+ novideo += 1
698
+ continue
699
+ try:
700
+ m = ctx.meta(h)
701
+ except Exception: # video not present in this copy of the store
702
+ novideo += 1
703
+ continue
704
+ if c in NA_WHEN_TOO_SHORT and m.get("too_short"):
705
+ na += 1
706
+ elif c == "v_32_s448" and m.get("normalized_short_side") == 480:
707
+ reuse += 1
708
+ log(f"DRY {bench}/{c}: todo={miss} of {len(rows)} "
709
+ f"(na={na} reuse={reuse} no_video={novideo} infer={miss - na - reuse - novideo})")
710
+ return
711
+ t0 = time.time()
712
+ log(f"{bench}: {len(todo)} rows x {len(conds)} conditions "
713
+ f"(of {len(rows)} sampled)")
714
+ with ThreadPoolExecutor(max_workers=workers) as ex:
715
+ futs = [ex.submit(process_row, ctx, bench, r, conds, fmt) for r in todo]
716
+ for i, fut in enumerate(as_completed(futs)):
717
+ try:
718
+ fut.result()
719
+ except Exception as e: # row-level crash must not kill the bench
720
+ log_failure("stage_p1", f"{bench}::row", f"{type(e).__name__}: {e}")
721
+ if (i + 1) % 25 == 0:
722
+ done_inf = sum(v["infer"] for (b, _), v in ctx.stats.items()
723
+ if b == bench)
724
+ log(f"{bench}: {i + 1}/{len(todo)} rows (infer={done_inf})")
725
+ wall = time.time() - t0
726
+ with open(TIMING_LOG, "a") as f:
727
+ for (b, c), st in sorted(ctx.stats.items()):
728
+ if b != bench:
729
+ continue
730
+ f.write(json.dumps(dict(ts=time.strftime("%F %T"), bench=b,
731
+ condition=c, wall_s=round(wall, 1), **{
732
+ k: (round(v, 1) if isinstance(v, float)
733
+ else v) for k, v in st.items()}))
734
+ + "\n")
735
+ log(f"{b}/{c}: infer={st['infer']} reused={st['reused']} "
736
+ f"na={st['na']} fail={st['fail']} decode={st['decode_s']:.0f}s "
737
+ f"infer={st['infer_s']:.0f}s ptok={st['prompt_tokens']}")
738
+ log(f"{bench}: bench wall {wall / 60:.1f} min")
739
+
740
+
741
+ def main():
742
+ ap = argparse.ArgumentParser()
743
+ ap.add_argument("--bench", default=None,
744
+ help="comma list of exact names, or a substring")
745
+ ap.add_argument("--conditions", default=",".join(CONDITIONS))
746
+ ap.add_argument("--limit", type=int, default=None)
747
+ ap.add_argument("--workers", type=int, default=12)
748
+ ap.add_argument("--endpoints", default=DEFAULT_ENDPOINTS)
749
+ ap.add_argument("--token-budget", type=int, default=58000)
750
+ ap.add_argument("--max-images", type=int, default=MAX_IMAGES_DEFAULT,
751
+ help="upper bound of frames per request for the fps ladders (= vLLM --limit-mm-per-prompt images)")
752
+ ap.add_argument("--cache-size", type=int, default=12)
753
+ ap.add_argument("--dry-run", action="store_true")
754
+ a = ap.parse_args()
755
+ conds = order_conditions([c.strip() for c in a.conditions.split(",")
756
+ if c.strip()])
757
+ import glob
758
+ files = sorted(glob.glob(f"{SAMPLES_DIR}/*.jsonl"))
759
+ if a.bench:
760
+ names = [b.strip() for b in a.bench.split(",") if b.strip()]
761
+ exact = [f for f in files if os.path.basename(f)[:-6] in names]
762
+ files = exact or [f for f in files
763
+ if any(n in os.path.basename(f) for n in names)]
764
+ if not files:
765
+ sys.exit("no benchmarks matched")
766
+ ctx = Ctx(a)
767
+ log(f"model={MODEL_NAME} ({MODEL_LABEL}) endpoints={len(ctx.endpoints)} "
768
+ f"benches={[os.path.basename(f)[:-6] for f in files]} conds={conds} "
769
+ f"resume_keys={len(ctx.done)} samples={SAMPLES_DIR} results_root={RESULTS_ROOT}")
770
+ t0 = time.time()
771
+ for p in files:
772
+ run_bench(ctx, p, conds, a.limit, a.workers, a.dry_run)
773
+ log(f"ALL DONE in {(time.time() - t0) / 60:.1f} min")
774
+
775
+
776
+ if __name__ == "__main__":
777
+ main()
code/exp/video_benchmarks.csv ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name,hf_repo,eval_type,question_format,has_chance_level,num_options,text_heavy,video_repo
2
+ Video-MME,lmms-eval/Video-MME,llm_fallback,mixed,False,4,False,
3
+ LongVideoBench,longvideobench/LongVideoBench,llm_fallback,mixed,False,5,False,
4
+ MLVU,sy1998/MLVU_dev,llm_fallback,MCQ,False,,False,
5
+ MVBench,OpenGVLab/MVBench,llm_fallback,mixed,False,,False,
6
+ VideoMMMU,lmms-eval/VideoMMMU,rule_only,MCQ,True,4,True,
7
+ EgoSchema,lmms-eval/egoschema,rule_only,MCQ,True,4,False,
8
+ LVBench,lmms-eval/LVBench,rule_only,MCQ,False,,False,
9
+ NExT-QA,lmms-eval/NExTQA,rule_only,MCQ,True,4,False,
10
+ PerceptionTest,lmms-eval/PerceptionTest,rule_only,MCQ,False,,False,lmms-eval/PerceptionTest_Val
11
+ MMVU,lmms-eval/MMVU,llm_required,MCQ,False,,False,
12
+ MMBench-Video,opencompass/MMBench-Video,llm_required,open,False,,False,
13
+ Charades-STA,lmms-eval/charades_sta,rule_only,mixed,False,,False,
14
+ TempCompass,lmms-eval/TempCompass,llm_fallback,mixed,False,2,False,
15
+ ActivityNet-QA,lmms-eval/ActivityNetQA,llm_required,open,False,,False,
16
+ VideoChatGPT,lmms-eval/VideoChatGPT,llm_required,open,False,,False,
17
+ MotionBench,zai-org/MotionBench,rule_only,MCQ,True,5,False,
18
+ VSI-Bench,nyu-visionx/VSI-Bench,rule_only,MCQ,False,,False,
19
+ CG-Bench,CG-Bench/CG-Bench,llm_required,mixed,False,,False,
20
+ HourVideo,HourVideo/HourVideo,rule_only,MCQ,False,,False,
21
+ VideoDetailCaption,lmms-lab/VideoDetailDescription,llm_required,open,False,,False,
22
+ TOMATO,lmms-eval/TOMATO,llm_required,MCQ,True,4,False,
23
+ Video-MME-v2,MME-Benchmarks/Video-MME-v2,llm_fallback,mixed,False,5,False,
24
+ WorldSense,lmms-lab/worldsense,llm_fallback,mixed,False,4,False,
25
+ ActivityNet-Captions,unknown,rule_only,open,False,,False,
26
+ STAR,unknown,rule_only,MCQ,False,,False,
27
+ DREAM-1K,mjuicem/DREAM-1k-VLMEvalKit,llm_required,open,False,,False,omni-research/DREAM-1K
28
+ MovieChat-1K,Enxin/lmms_MovieChat_test,llm_required,open,False,,False,
29
+ Kinetics-700,unknown,unknown,unknown,False,,False,
30
+ ReVSI,3dlg-hcvc/ReVSI,rule_only,MCQ,False,,False,
31
+ VSI-Super,nyu-visionx/VSI-SUPER-Count,rule_only,MCQ,False,,False,
32
+ TimeLens,kcz358/timelens,rule_only,grounding,False,,False,
33
+ VDC,wchai/lmms_VDC_test,llm_required,open,False,,False,
34
+ VideoEval-Pro,TIGER-Lab/VideoEval-Pro,llm_required,MCQ,False,,False,
35
+ FAVOR-Bench,FAVOR-Bench/FAVOR,rule_only,mixed,False,,False,
36
+ Video-Holmes,TencentARC/Video-Holmes,llm_fallback,MCQ,True,6,False,
37
+ MSVD-QA,unknown,rule_only,open,False,,False,
38
+ Molmo2-VideoCount,allenai/Molmo2-VideoCountEval,rule_only,numeric,False,,False,
39
+ VideoHallucer,bigai-nlco/VideoHallucer,rule_only,MCQ,False,,False,
40
+ StreamingBench,mjuicem/StreamingBench,rule_only,MCQ,False,,False,
41
+ Video-TT,lmms-eval/video-tt,llm_fallback,mixed,False,5,unknown,
42
+ OMTGBench,insomnia7/omtg_bench,rule_only,grounding,False,,False,
43
+ SiteBench-Video,franky-veteran/SITE-Bench,rule_only,mixed,False,4,False,
44
+ LongTimeScope,Apollo-LMMs/LongTimeScope2,rule_only,MCQ,False,,unknown,
45
+ LSDBench,TainU/LSDBench,rule_only,open,False,,False,
46
+ MVP-Bench,facebook/minimal_video_pairs,rule_only,MCQ,False,,unknown,
47
+ OSI-Bench,HarmlessSR07/OSI-Bench,rule_only,mixed,False,,unknown,
48
+ PAIBench-U,Jialuo21/PAIBench-U,rule_only,MCQ,True,2/3/4,unknown,
49
+ SIS-Bench,choucsan/SIS-Bench,rule_only,MCQ,True,4,unknown,
50
+ FALCONBench,cplou99/FALCON-Bench,llm_required,mixed,False,4,False,
51
+ DSRBench,lmms-lab-si/EASI-Leaderboard-Data,rule_only,MCQ,True,4,False,
52
+ STI-Bench,MINT-SJTU/STI-Bench,rule_only,MCQ,True,5,False,
53
+ MVTamperBench,Srikant86/MVTamperBench,llm_fallback,mixed,False,,False,
54
+ OVOBench,kcz358/OVOBench,rule_only,open,False,,False,JoeLeelyf/OVO-Bench
55
+ RepCount,lmms-lab-eval/repcount,rule_only,open,False,,False,
56
+ SSv2,lmms-lab-eval/ssv2,rule_only,open,False,,False,
57
+ TemporalBench,microsoft/TemporalBench,rule_only,open,False,,False,
58
+ QBench-Video,zhangzicheng/Q-Bench-Video,rule_only,MCQ,False,,False,
59
+ EgoTaskQA,nv-njb/EgoTaskQA-MCQ,rule_only,MCQ,False,,False,
60
+ Countix,unknown,rule_only,open,False,,False,
61
+ HD-EPIC,unknown,rule_only,grounding,False,,False,
62
+ FunQA,fesvhtr/FunQA_LMMs,llm_required,open,False,,False,
63
+ MMWorld,MMWorld/MMWorld,rule_only,MCQ,True,4,False,
64
+ Minerva,unknown,rule_only,unknown,False,,False,
65
+ EgoTempo,lmms-lab-eval/egotempo,rule_only,grounding,False,,False,
66
+ PLM-VideoBench,facebook/PLM-VideoBench,llm_required,mixed,False,,False,
67
+ Vinoground,HanSolo9682/Vinoground,rule_only,open,False,,False,
68
+ Video-MMLU,Enxin/Video-MMLU,llm_required,open,False,,True,
69
+ VITATECS,lscpku/VITATECS,llm_required,mixed,False,,False,
70
+ CG-AV-Counting,CG-Bench/CG-AV-Counting,rule_only,mixed,False,,False,
71
+ OVR-Kinetics,lmms-lab-eval/ovr_kinetics,rule_only,mixed,False,,False,
72
+ CVRR-ES,lmms-eval/CVRR-ES,llm_required,open,False,,False,
73
+ TVBench,FunAILab/TVBench,rule_only,mixed,False,,False,
74
+ CinePile,tomg-group-umd/cinepile,rule_only,MCQ,True,5,False,
75
+ Neptune,lmms-eval/GoogleDeepMind-NEPTUNE,rule_only,MCQ,True,5,False,
76
+ EgoPlan-Bench,EgoLife-v1/EgoPlan,rule_only,mixed,False,4,False,
77
+ EgoExoBench,Heleun/EgoExoBench_MCQ,llm_fallback,MCQ,False,,False,
78
+ SciVideoBench,groundmore/scivideobench,rule_only,MCQ,True,10,True,
79
+ VideoMathQA,MBZUAI/VideoMathQA,rule_only,mixed,False,5,True,
80
+ MMSI-Video,oscarqjh/MMSI-Video-Bench_lmmseval,rule_only,unknown,False,,False,
81
+ V2P-Bench,gaotiexinqu/V2P-Bench,rule_only,MCQ,False,,False,
82
+ VCR-Bench,VLM-Reasoning/VCR-Bench,rule_only,MCQ,True,3/4/5,False,
83
+ MEGA-Bench(video),TIGER-Lab/MEGA-Bench,rule_only,grounding,False,,unknown,
84
+ AV-SpeakerBench,plnguyen2908/AV-SpeakerBench,rule_only,MCQ,True,4,False,
85
+ AV-Odyssey,AV-Odyssey/AV_Odyssey_Bench_LMMs_Eval,rule_only,MCQ,True,4,False,
86
+ CameraBench,chancharikm/camerabench_vqa_lmms_eval,rule_only,MCQ,True,2,False,
87
+ COVER,lmms-lab-eval/COVER,rule_only,MCQ,False,,unknown,PeterPanonly/COVER
88
+ CUVA,fesvhtr/CUVA_LMMs,rule_only,open,False,,False,
89
+ IntPhys2,facebook/IntPhys2,rule_only,open,False,,False,
90
+ JumpScore,lmms-lab-encoder/JumpScore,rule_only,mixed,False,,unknown,
91
+ TimeScope,Apollo-LMMs/TimeScope,rule_only,MCQ,False,,False,
92
+ LongVT,longvideotool/VideoSIAH-Eval,rule_only,MCQ,True,4,unknown,
93
+ Lemonade,amathislab/LEMONADE,rule_only,MCQ,True,4,unknown,
94
+ MMOU,kcz358/MMOU,rule_only,MCQ,True,10,unknown,
95
+ PerceptionComp,hrinnnn/PerceptionComp,rule_only,MCQ,True,5,unknown,
96
+ PhysicalAI-Understanding,shi-labs/physical-ai-bench-understanding,rule_only,MCQ,True,4,False,
97
+ PushupBench,anonymousatom/pushupbench,rule_only,numeric,False,,False,
98
+ SpatialTreeBench,LongfeiLi/SpatialTree-Bench,rule_only,MCQ,False,,False,
99
+ VStaT,nyu-visionx/vstat,rule_only,MCQ,False,,unknown,
100
+ WorldQA,lmms-eval/worldqa,llm_required,MCQ,True,4,False,
101
+ ExtremeWhenBench,min1321/extreme-when-bench,rule_only,grounding,False,,False,
102
+ MVU-Eval,MVU-Eval-Team/MVU-Eval-Data,rule_only,MCQ,False,,unknown,
103
+ VIABench,MCG-NJU/VIABench,unknown,open,False,NA,unknown,
104
+ E-VQA,Salesforce/ST-Evidence-Bench,rule_only,mixed,False,5,unknown,
105
+ Camera Movement Understanding (BU/Google),Yuwen2024/ACaM-Bench,unknown,MCQ,True,4,unknown,
106
+ AnyGroundBench,rinost081/AnyGroundBench,unknown,grounding,False,NA,unknown,
107
+ VidPair-Halluc,Jethro37/VidPair-Halluc,rule_only,MCQ,True,2,unknown,
108
+ Video-MME-Logical,marcuskwan/video-mme-logical,rule_only,open,False,NA,unknown,
109
+ Ego-MC-Bench,neuripsedtracksub/ego-counterfactual-mistakes,unknown,mixed,False,NA,unknown,
110
+ ChronoPhyBench,Kohsin/ChronoPhyBench,unknown,mixed,False,NA,unknown,
111
+ VideoKR,minuzero/VideoKR-Eval,llm_fallback,mixed,False,NA,unknown,
112
+ VideoOdyssey,maifoundations/VideoOdyssey,rule_only,MCQ,True,4,unknown,
113
+ Artifact-Bench,DogNeverSleep/Artifact-Bench,rule_only,mixed,False,NA,unknown,
114
+ VURB,wyccccc/VURB_Data,unknown,MCQ,False,NA,unknown,
115
+ SFI-Bench,le723z/SFI-Bench,unknown,MCQ,True,4,unknown,
116
+ GasVideo-1000,kk12ff/GasVideo1000,unknown,mixed,False,NA,unknown,
117
+ VideoZeroBench,marinero4972/VideoZeroBench,rule_only,mixed,False,NA,unknown,
118
+ SAW-Bench,ucsbai/SAW-Bench,llm_fallback,MCQ,True,3,unknown,
119
+ TimeBlind,BaiqiL/TimeBlind,rule_only,MCQ,True,2,unknown,
120
+ AVMeme Exam,naplab/AVMeme-Exam,unknown,MCQ,False,NA,unknown,
121
+ FutureOmni,OpenMOSS-Team/FutureOmni,rule_only,MCQ,False,4 or 6,unknown,
122
+ VKnowU,Eurayka/VKnowU,rule_only,MCQ,False,NA,unknown,
123
+ TeleEgo,David0219/TeleEgo,llm_fallback,mixed,False,NA,unknown,
124
+ DSI-Bench,Viglong/DSI-Bench,rule_only,MCQ,True,4,unknown,
125
+ Omni-Cloze,BoJack/Omni-Cloze,llm_required,MCQ,True,5,unknown,
126
+ ExpVid,OpenGVLab/ExpVid,unknown,mixed,False,NA,unknown,
127
+ EgoNight,dehezhang2/EgoNight,llm_fallback,open,False,NA,unknown,
128
+ v-HUB,Foreverskyou/v-HUB,llm_fallback,mixed,False,5,unknown,
129
+ ELV-Halluc,HLSv/ELV-Halluc,rule_only,MCQ,True,2,unknown,shuzhig/elv-halluc-videos
130
+ RynnEC-Bench,Alibaba-DAMO-Academy/RynnEC-Bench,llm_required,mixed,False,NA,unknown,
131
+ GLIMPSE,AIMING-Lab-UNC/GLIMPSE,rule_only,MCQ,True,4,unknown,
132
+ SoMi-ToM,SoMi-ToM/SoMi-ToM,rule_only,MCQ,True,3,unknown,
133
+ ShotBench,Vchitect/ShotBench,llm_fallback,MCQ,True,4,unknown,
134
+ VRBench,OpenGVLab/VRBench,llm_required,mixed,False,NA,unknown,
135
+ ViMUL-Bench,MBZUAI/ViMUL-Bench,llm_required,mixed,False,4,unknown,
136
+ MF2 (Movie Facts and Fibs),sardinelab/MF2,rule_only,MCQ,True,2,unknown,
137
+ MORSE-500,video-reasoning/morse-500,llm_required,mixed,False,NA,unknown,
138
+ MMR-V,JokerJan/MMR-VBench,rule_only,MCQ,False,NA,unknown,
139
+ SAVVY-Bench,uwneuroai/SAVVY-Bench,rule_only,mixed,False,4,unknown,
140
+ AoTBench,sherryxzh/AoTBench,rule_only,MCQ,False,NA,unknown,
141
+ VSI-Super-Wild,THUSI-Lab/VSI-Super-Wild,rule_only,mixed,False,NA,unknown,
142
+ FindingDory,yali30/findingdory,rule_only,grounding,False,NA,unknown,
143
+ ExAct,Alexhimself/ExAct,rule_only,MCQ,True,5,unknown,
144
+ K9-Bench,K9Bench/K9Bench,unknown,MCQ,False,,True,yt::K9-Bench
145
+ S3-Bench,kszucs/buckets-vs-s3-benchmark,unknown,mixed,False,,True,
146
+ REVEAL,aaeagal/Reveal,unknown,mixed,False,,True,
147
+ HumanPCR,HumanPCR/HumanPCR,rule_only,mixed,False,,True,
148
+ EgoMonth,anonymous-egomonth/egomonth-dataset,rule_only,mixed,False,,True,
149
+ VideoGAIA,Karl28/VideoGAIA,unknown,mixed,False,,True,
150
+ TAR-Bench,nvidia/PhysicalAI-Traffic-Anomaly-Reasoning,rule_only,mixed,False,,True,
151
+ VideoVIBE,AdwolfCzar/video_vibe_captioned_dataset,unknown,MCQ,False,,True,
152
+ ViSTR-Bench,homothetic/ViSTR-Bench-Public,unknown,MCQ,False,,True,
153
+ LongVILBench,cq838/LongVILBench,rule_only,mixed,False,,True,
154
+ ID-VTG,Chloe-UniU-oO/ID-VTG,rule_only,mixed,False,,True,
155
+ RISE-Bench,PhoenixZ/RISEBench,rule_only,mixed,False,,True,
156
+ UAV-DualCog,Lozumi/UAV-DualCog,unknown,mixed,False,,True,
157
+ SLVMBench,SLVMBench/SLVMBench,unknown,MCQ,False,,True,
158
+ S-EMBER,facebook/S-EMBER,unknown,mixed,False,,True,
159
+ MedStreamBench,Venn2024/MedStreamBench,unknown,mixed,False,,True,
160
+ VideoLLM-BoE,lab-flair/VideoLLM-BoE,unknown,MCQ,False,,True,
161
+ OmniVDCBench,videobenchlab/omniVDCBench,rule_only,mixed,False,,True,
162
+ ReactHuman Benchmark (Scaled),Alan123/reacthuman-benchmark-scaled-with-videos,rule_only,MCQ,False,,True,
163
+ VideoMemory-Bench,viktorcyt/VideoMemory-Bench,rule_only,MCQ,False,,True,
164
+ VideoAesBench,chris-123/VideoAesBench,unknown,mixed,False,,True,
165
+ V-NIAH-D,Tianyi1112/VideoRoPE,rule_only,MCQ,False,,True,
166
+ VideoIntentMCQ_OE,KHUjongseo/VideoIntentMCQ_OE,unknown,mixed,False,,True,
167
+ NaturalBench-Video,BaiqiL/NaturalBench-Video,rule_only,MCQ,False,,True,
168
+ LongVideo-Reason-eval,LongVideo-Reason/longvideo_eval_videos,unknown,MCQ,False,,True,
169
+ Causal2Needles,causal2needles/Causal2Needles,unknown,mixed,False,,True,
170
+ InstructionBench,sunwhw/InstructionBench,mixed,mixed,False,,True,
171
+ TemporalVQA,fazliimam/temporal-vqa,rule_only,MCQ,False,,True,
172
+ Charades-CON / ActivityNet-CON,mjjung/Consistency-Evaluation-for-Video-LLMs,rule_only,MCQ,False,,True,
173
+ TaskMeAnything-v1-videoqa-2024,weikaih/TaskMeAnything-v1-videoqa-2024,rule_only,MCQ,False,,True,local::TaskMeAnything-v1-videoqa-2024
174
+ Colon-Bench,ajhamdi/colon-bench,unknown,MCQ,True,5,True,
175
+ "ID-VTG (IDVTG-Gym, IDVTG-InternVid)",Chloe-UniU-oO/ID-VTG,unknown,mixed,False,,True,
176
+ SVCBench,buaaplay/SVCBench,unknown,numeric,False,,True,
177
+ ScaleLong,m-a-p/ScaleLong,unknown,MCQ,False,,True,
178
+ TOC-Bench,anonymous-video-benchmark/toc_bench,unknown,mixed,False,,True,
179
+ VideoGameQA-Bench,taesiri/VideoGameQA-Bench,unknown,mixed,False,,True,
180
+ IV-Bench,m-a-p/IV-Bench,unknown,MCQ,False,,True,
181
+ SmartHome-Bench,violetcliff/SmartHome-Bench,unknown,MCQ,False,,True,yt::SmartHome-Bench
182
+ VStream-QA,IVGSZ/VStream-QA,unknown,mixed,False,,True,
183
+ Charades-CON,mjjung/Consistency-Evaluation-for-Video-LLMs,unknown,MCQ,False,,True,lmms-eval/charades_sta
184
+ ActivityNet-CON,mjjung/Consistency-Evaluation-for-Video-LLMs,unknown,MCQ,False,,True,friedrichor/ActivityNet_Captions
185
+ EventHallusion,lccshunli/EventHallusion,unknown,MCQ,False,,True,lccshunli/EventHallusion
186
+ KFS-Bench,longvideobench/LongVideoBench,unknown,MCQ,False,,True,longvideobench/LongVideoBench
187
+ UCF101-AD,raiyaanabdullah/UCF101-AD,unknown,MCQ,False,,True,raiyaanabdullah/UCF101-AD
188
+ iSafetyBench,raiyaanabdullah/isafety-bench,unknown,MCQ,False,,True,raiyaanabdullah/isafety-bench
189
+ OVO-S-Bench,JoeLeelyf/OVO-S-Bench,unknown,MCQ,False,,True,url::OVO-S-Bench
190
+ VANE-Bench,rohit901/VANE-Bench,unknown,MCQ,False,,True,local::VANE-Bench
191
+ M^3-Verse,modelscope::WalKaWay/M3-Verse,unknown,MCQ,False,,True,local::M^3-Verse
192
+ VNBench,videoniah/VNBench,unknown,MCQ,False,,True,local::VNBench
193
+ CAViAR,sparshgarg57/CAViAR,unknown,MCQ,False,,True,nexar-ai/nexar_collision_prediction
194
+ Video-LevelGauge,Cola-any/Video-LevelGauge,unknown,MCQ,False,,True,
195
+ HERBench,DanBenAmi/HERBench,unknown,MCQ,False,,False,
196
+ MME-VideoOCR,DogNeverSleep/MME-VideoOCR_Dataset,unknown,MCQ,False,,True,
197
+ E.T. Bench,PolyU-ChenLab/ETBench,unknown,MCQ,False,,False,
198
+ VRU-Accident,VRUAccidentAnonymous/VRU-Accident,unknown,MCQ,False,,True,
199
+ ALLVB,ALLVB/ALLVB,unknown,MCQ,False,,False,
200
+ GUI-World,ONE-Lab/GUI-World,unknown,MCQ,False,,True,
201
+ VideoEspresso,hshjerry0315/VideoEspresso-Test,unknown,MCQ,False,,True,
202
+ VAU-Bench (UCF-Crime),7xiang/VAU-Bench,unknown,MCQ,False,,False,AllenXeon/ucf_crime
203
+ VF-Eval,songtingyu/vf-eval,unknown,MCQ,False,,True,
204
+ UrbanVideo-Bench,EmbodiedCity/UrbanVideo-Bench,unknown,MCQ,False,,False,
205
+ HLV-1K,ZouHQ/HLV-1K,unknown,MCQ,False,,True,yt::HLV-1K
206
+ CineTechBench,Xinran0906/CineTechBench,unknown,MCQ,False,,True,yt::CineTechBench
207
+ ReXTime,ReXTime/ReXTime,unknown,MCQ,False,,True,yt::ReXTime
208
+ LOKI,bczhou/LOKI,unknown,MCQ,False,,True,
209
+ ContPhy,zzcnewly/ContPhy_Dataset,unknown,MCQ,False,,True,
210
+ FineBench,FINEBENCH/FineBench,unknown,MCQ,False,,False,yt::FineBench
211
+ ForeSeaQA,qualcomm/ForeSeaQA,unknown,MCQ,False,,False,AllenXeon/ucf_crime
212
+ VideoAds,Zheyuan14/VideoAds,unknown,MCQ,False,,False,
213
+ VELOCITI,katha-ai-iiith/VELOCITI,unknown,MCQ,False,,False,
214
+ VGenST-Bench,NeurIPS2026-VGenST-Bench/VGenST-Bench,unknown,MCQ,False,,False,
215
+ SportsD,addisonwu05/sportsd,unknown,MCQ,False,,False,
code/requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # origin cluster versions (Python 3.12); vLLM CUDA 12.8 wheels (RTX 5090 = sm_120 needs torch 2.8 cu128)
2
+ vllm==0.11.0
3
+ torch==2.8.0
4
+ transformers==4.57.6
5
+ decord>=0.6.0 # frame decoder (fallbacks: opencv-python-headless, ffmpeg on PATH)
6
+ opencv-python-headless>=4.10
7
+ pillow>=10
8
+ pyyaml>=6
9
+ requests>=2.32
10
+ huggingface_hub>=0.34
code/run_frames_pixels.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # run_frames_pixels.sh — task 11 (resolution x frame-rate sweep) on a multi-GPU machine without Slurm.
3
+ # bash code/run_frames_pixels.sh --dry-run # count the work per benchmark x condition (no GPU)
4
+ # PILOT=1 bash code/run_frames_pixels.sh # MVBench, LVBench, TimeScope only (report timing first)
5
+ # bash code/run_frames_pixels.sh # all 84 benchmarks
6
+ # BENCH="MVBench,LVBench" bash code/run_frames_pixels.sh # explicit benchmark list
7
+ # One vLLM server per GPU (Qwen3-VL-8B, --max-model-len 65536, --limit-mm-per-prompt images 1024), one
8
+ # runner process that round-robins over the servers. Resumable: rows already in results/conditions_results.csv
9
+ # are skipped, so the conditions that exist on the origin cluster are never re-run.
10
+ # Env: NGPU (default all), WORKERS (default 4 per GPU), GPU_UTIL (0.85), MAX_SEQS (default 8), PORT0 (8011),
11
+ # PY (python3), VLLM (vllm), CONDS (default: the task-11 list below), TOKEN_BUDGET (58000), MAX_IMAGES (1024)
12
+ set -u
13
+ CODE=$(cd "$(dirname "$0")" && pwd); ROOT=$(cd "$CODE/.." && pwd)
14
+ export BENCH_BASE=${BENCH_BASE:-$ROOT/data} # <root>/data/store/normalized/<hash>/..., <root>/data/logs
15
+ export P1_SAMPLES_DIR=${P1_SAMPLES_DIR:-$ROOT/items/samples}
16
+ export P1_RESULTS_ROOT=${P1_RESULTS_ROOT:-$ROOT/results}
17
+ export P1_MANIFEST=${P1_MANIFEST:-$ROOT/manifest/manifest_subset.jsonl}
18
+ mkdir -p "$BENCH_BASE/logs" "$P1_RESULTS_ROOT" "$ROOT/logs"
19
+ [ -d "$BENCH_BASE/store/normalized" ] || { echo "unpack the video shards into $BENCH_BASE/store/normalized first"; exit 2; }
20
+ PY=${PY:-python3}; VLLM=${VLLM:-vllm}; PORT0=${PORT0:-8011}; GPU_UTIL=${GPU_UTIL:-0.85}; MAX_SEQS=${MAX_SEQS:-8}
21
+ TOKEN_BUDGET=${TOKEN_BUDGET:-58000}; MAX_IMAGES=${MAX_IMAGES:-1024}
22
+ MODEL="Qwen/Qwen3-VL-8B-Instruct"; REV=0c351dd01ed87e9c1b53cbc748cba10e6187ff3b
23
+ CONDS=${CONDS:-v_blind,v_1,v_32,v_32_s448,v_32_s224,v_32_s168,v_32_s336,v_8_s224,v_128_s224,v_fps0.25_s224,v_fps0.5_s224,v_fps1_s224,v_fps2_s224}
24
+ RUNNER="$CODE/exp/pipeline/stage_p1_runner.py"
25
+ if [ "${PILOT:-0}" = "1" ]; then BENCH=${BENCH:-MVBench,LVBench,TimeScope}; fi
26
+ BENCH_ARG=(); [ -n "${BENCH:-}" ] && BENCH_ARG=(--bench "$BENCH")
27
+ if [ "${1:-}" = "--dry-run" ]; then
28
+ "$PY" "$RUNNER" --conditions "$CONDS" --endpoints http://127.0.0.1:1/v1 --token-budget "$TOKEN_BUDGET" --max-images "$MAX_IMAGES" "${BENCH_ARG[@]}" --dry-run; exit $?
29
+ fi
30
+ NGPU=${NGPU:-$(nvidia-smi -L 2>/dev/null | wc -l)}; [ "$NGPU" -ge 1 ] || { echo "no GPU found"; exit 2; }
31
+ WORKERS=${WORKERS:-$((4 * NGPU))}
32
+ export VLLM_USE_FLASHINFER_SAMPLER=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True TOKENIZERS_PARALLELISM=false
33
+ PIDS=(); EPS=""
34
+ for i in $(seq 0 $((NGPU - 1))); do
35
+ PORT=$((PORT0 + i)); EPS="${EPS:+$EPS,}http://127.0.0.1:$PORT/v1"
36
+ CUDA_VISIBLE_DEVICES=$i "$VLLM" serve "$MODEL" --revision "$REV" --served-model-name "$MODEL" --host 127.0.0.1 --port "$PORT" \
37
+ --max-model-len 65536 --gpu-memory-utilization "$GPU_UTIL" --max-num-seqs "$MAX_SEQS" \
38
+ --limit-mm-per-prompt "{\"image\": $MAX_IMAGES}" --mm-processor-cache-gb 0 \
39
+ > "$ROOT/logs/vllm_gpu${i}.log" 2>&1 &
40
+ PIDS+=($!)
41
+ done
42
+ trap 'for p in "${PIDS[@]}"; do kill "$p" 2>/dev/null; done' EXIT
43
+ for i in $(seq 0 $((NGPU - 1))); do
44
+ PORT=$((PORT0 + i))
45
+ for t in $(seq 1 180); do curl -sf "http://127.0.0.1:$PORT/v1/models" >/dev/null 2>&1 && break; kill -0 "${PIDS[$i]}" 2>/dev/null || { echo "vLLM on GPU $i died, see logs/vllm_gpu${i}.log"; exit 1; }; sleep 10; done
46
+ echo "[frames_pixels] vLLM ready on GPU $i (:$PORT)"
47
+ done
48
+ echo "[frames_pixels] launch: --max-model-len 65536 --limit-mm-per-prompt images=$MAX_IMAGES --max-num-seqs $MAX_SEQS --gpu-memory-utilization $GPU_UTIL; runner --token-budget $TOKEN_BUDGET --max-images $MAX_IMAGES --workers $WORKERS" | tee -a "$ROOT/logs/launch_params.txt"
49
+ "$PY" "$RUNNER" --conditions "$CONDS" --endpoints "$EPS" --workers "$WORKERS" --token-budget "$TOKEN_BUDGET" --max-images "$MAX_IMAGES" "${BENCH_ARG[@]}" 2>&1 | tee -a "$ROOT/logs/runner.log"
50
+ rc=${PIPESTATUS[0]}
51
+ echo "[frames_pixels] runner finished rc=$rc"; exit $rc