Enxin commited on
Commit
9e19fa1
·
verified ·
1 Parent(s): 5d4c567

add supplement_20260910/code/

Browse files
supplement_20260910/code/exp/analysis/pool/TASK.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 全量题池构建:三步筛选跑批(parcc,单卡 B200,Slurm)(用户 2026-09-06)
2
+
3
+ ## 目标
4
+ 对 benchmark 全部题目建题池。三步跑批,任一步答对即出池,其余全部保留并带标签。
5
+ 产物是一张逐题表和一个可查询的题池数据库,供后续的规格查询与 Vendi 选择使用。
6
+
7
+ ## 输入
8
+ - 已下载的 benchmark,路径与格式见现有 loader;先补齐 loader 缺失的 benchmark。
9
+ - 统一 item schema:benchmark、item_id、video_id、video_path、question、options(列表)、answer_idx、
10
+ duration、declared_task、declared_scene、license。选项缺失或 ground truth 非选项的题标 format=open,不进后续跑批。
11
+
12
+ ## 步骤 0:筛(CPU)
13
+ - 视频内容哈希去重,得到 video_id;同 benchmark 内题干加选项文本近重复(bge-large-en-v1.5,余弦 > 0.9)只留一道。
14
+ - 判分规则固定为三步级联(选项字母、答案行正则、选项文本),与主文 3.2 一致。
15
+ - 输出 screen_counts_full.csv:每个 benchmark 的总题数、去重后题数、format=open 题数。
16
+
17
+ ## 步骤 1:盲测(Qwen3-VL-8B,文本模式,vLLM)
18
+ - 每题 4 次选项置换,每次只做一个前向,取四个选项字母的 log-prob,选最大者。
19
+ - 记录 blind_acc_4perm(0 到 1)与 blind_margin = 平均 log-prob 边际。
20
+ - 出池条件:blind_acc_4perm 在 chance 之上显著(单侧二项检验,n=4 太小,改用 log-prob 边际的阈值:
21
+ 正确选项 log-prob 高于其余三者均值超过 log(2),且 4 次置换中至少 3 次选中正确项)。
22
+
23
+ ## 步骤 2:单帧(Qwen3-VL-8B,448 像素,vLLM)
24
+ - 每题取视频中点一帧,一个前向,取选项 log-prob。
25
+ - 记录 sf_correct、sf_margin。
26
+ - 出池条件:sf_correct 且 sf_margin > log(2)。
27
+
28
+ ## 步骤 3:32 帧(Qwen3-VL-2B,448 像素,vLLM)
29
+ - 每题均匀 32 帧,一个前向,取选项 log-prob。
30
+ - 记录 v32_2b_correct、v32_2b_margin。
31
+ - 出池条件:v32_2b_correct 且 v32_2b_margin > log(2)。
32
+
33
+ ## 调度
34
+ - 每片一个 vLLM 进程,端口按 SLURM_ARRAY_TASK_ID 错开。
35
+ - 帧解码单独一个 CPU 数组作业先跑,缓存到本地 SSD,格式 jpg,命名 video_id/frame_k.jpg。
36
+ - 步骤 1 不依赖帧,先跑;步骤 2 和 3 等帧缓存完成。
37
+ - 断点续跑:逐题写 jsonl,重启时跳过已完成 item_id。
38
+ - run_accounting.csv 记录每步的请求数、GPU 小时、失败数。
39
+
40
+ ## 输出
41
+ - pool_items.parquet:上面 schema 的全部列,加 blind_acc_4perm、blind_margin、sf_correct、sf_margin、
42
+ v32_2b_correct、v32_2b_margin、removed_by(none / blind / single_frame / v32_2b,多个用逗号连接)、
43
+ task_class、scene_type(先用 declared 字段,打标 agent 之后覆盖)、cell_thin(该任务 × 场景格子剩余不足 30 题)。
44
+ - pool.duckdb:同一张表,供 SQL 查询。
45
+ - pool_summary.md:总题数、各步出池数与占比、剩余题数、按 benchmark 与按格子的剩余分布、薄格子清单。
46
+ - 三步的逐题 jsonl 原始输出保留。
47
+
48
+ ## 验收
49
+ - 任意一个 benchmark 剩余为 0 时单独报告,不自动删除。
50
+ - 全部完成后把 pool_summary.md 和 screen_counts_full.csv build 进 Overleaf 的 fig_tex/。
51
+
52
+ ## 执行说明(主会话 2026-09-06)
53
+ - 用户要求"根据集群实际情况进行调度优化,尽快跑完":GPU 分区 mig45 本组作业已排队 1.5 天,
54
+ 作业拆小(短时限、单片)以利回填;步骤 1 纯文本可先跑;帧解码与视频下载并行推进。
55
+ - 全量视频仍在下载(2026-09-06 11:50 完成 43%),步骤 0/1 用已解析的全量题目先跑,步骤 2/3 随视频到齐分批。
supplement_20260910/code/exp/analysis/pool/frames_decode.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """frames_decode.py — frame cache for steps 2 and 3.
3
+
4
+ Cache location: bench_exp/work/pool_frames/<video_id>/frame_<k>.jpg + frames.json
5
+ (video_id = content_hash). Decision (2026-09-06): the cluster runs
6
+ job_container/tmpfs (per-job private /tmp, destroyed at job end) and the MIG node
7
+ reports TmpDisk=0, so node-local storage cannot be shared between the CPU decode array
8
+ and the GPU array. /vast is the shared NVMe-backed (VAST) filesystem every node mounts;
9
+ it is the only cache that the decode array and all GPU tasks can read and write, and
10
+ it survives job boundaries for incremental re-runs. GPU tasks decode any video still
11
+ missing from the cache on the fly (same function) so steps 2-3 never block on the array.
12
+
13
+ Frames = the stage_p1_runner v_32 grid: 32 time-uniform targets over meta
14
+ frame_timestamps, nearest frame index each, duplicates (short videos) collapsed to the
15
+ first grid position. frame_<k>.jpg is named by grid position k (0..31); frames.json
16
+ lists the positions that exist (`keys`), the single-frame position `mid_k` (grid
17
+ position 16 = v_1), and the frame size after resizing to a 448 px long side (never
18
+ upscaled), JPEG q85.
19
+
20
+ frames_decode.py [--shard i/k] [--workers 8] [--limit N] [--video-ids FILE]
21
+ [--all-videos] (default: videos of items still in the pool)
22
+ frames_decode.py --stats
23
+ """
24
+ import argparse
25
+ import hashlib
26
+ import io
27
+ import json
28
+ import os
29
+ import shutil
30
+ import sys
31
+ import time
32
+ from concurrent.futures import ProcessPoolExecutor, as_completed
33
+
34
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
35
+ import pool_common as pc # noqa: E402
36
+ from pool_common import log # noqa: E402
37
+
38
+
39
+ def frames_json_path(video_id):
40
+ return os.path.join(pc.FRAMES_DIR, video_id, "frames.json")
41
+
42
+
43
+ def load_frames_json(video_id):
44
+ p = frames_json_path(video_id)
45
+ if not os.path.exists(p):
46
+ return None
47
+ try:
48
+ d = json.load(open(p))
49
+ return d if d.get("ok") else None
50
+ except Exception:
51
+ return None
52
+
53
+
54
+ def grid_positions(meta):
55
+ """-> (grid of 32 frame indices, ordered unique positions k, mid_k)."""
56
+ from stage_p1_runner import _nearest_indices, _uniform_times
57
+ n = int(meta["n_frames"])
58
+ ts = meta.get("frame_timestamps") or []
59
+ if len(ts) != n or n == 0:
60
+ ts = list(range(max(n, 1)))
61
+ grid = _nearest_indices(ts, _uniform_times(ts[0], ts[-1], pc.N_FRAMES_V32))
62
+ first = {}
63
+ keys = []
64
+ for k, idx in enumerate(grid):
65
+ if idx not in first:
66
+ first[idx] = k
67
+ keys.append(k)
68
+ mid_k = first[grid[pc.MID_POS]]
69
+ return grid, keys, mid_k
70
+
71
+
72
+ def ensure_frames(video_id, video_path, meta=None, long_side=pc.FRAME_LONG_SIDE):
73
+ """Decode + cache if missing; returns the frames.json dict (or raises)."""
74
+ d = load_frames_json(video_id)
75
+ if d is not None:
76
+ return d
77
+ from PIL import Image
78
+ from extract_frames import _decode
79
+ if meta is None:
80
+ meta = pc.meta_of(video_id)
81
+ if not meta:
82
+ raise RuntimeError("meta.json missing")
83
+ grid, keys, mid_k = grid_positions(meta)
84
+ idxs = [grid[k] for k in keys]
85
+ decoded = _decode(video_path, idxs) # {idx: PIL}
86
+ avail = max(decoded)
87
+ out_dir = os.path.join(pc.FRAMES_DIR, video_id)
88
+ tmp_dir = f"{out_dir}.tmp{os.getpid()}"
89
+ os.makedirs(tmp_dir, exist_ok=True)
90
+ w = h = None
91
+ for k, idx in zip(keys, idxs):
92
+ im = decoded[min(idx, avail)].convert("RGB")
93
+ W, H = im.size
94
+ s = long_side / max(W, H)
95
+ if s < 1.0:
96
+ im = im.resize((max(1, round(W * s)), max(1, round(H * s))), Image.LANCZOS)
97
+ w, h = im.size
98
+ im.save(os.path.join(tmp_dir, f"frame_{k}.jpg"), format="JPEG", quality=pc.JPEG_QUALITY)
99
+ info = dict(video_id=video_id, n_frames_video=int(meta.get("n_frames", 0)), grid=grid, keys=keys,
100
+ mid_k=mid_k, w=w, h=h, long_side=long_side, jpeg_quality=pc.JPEG_QUALITY,
101
+ too_short=bool(meta.get("too_short")), ok=True, ts=time.strftime("%F %T"))
102
+ json.dump(info, open(os.path.join(tmp_dir, "frames.json"), "w"))
103
+ try:
104
+ os.rename(tmp_dir, out_dir)
105
+ except OSError:
106
+ # another worker finished first: keep theirs
107
+ shutil.rmtree(tmp_dir, ignore_errors=True)
108
+ d = load_frames_json(video_id)
109
+ if d is None:
110
+ raise
111
+ return d
112
+ return info
113
+
114
+
115
+ def frame_bytes(video_id, k):
116
+ with open(os.path.join(pc.FRAMES_DIR, video_id, f"frame_{k}.jpg"), "rb") as f:
117
+ return f.read()
118
+
119
+
120
+ # ------------------------------------------------------------------ selection
121
+ def pool_videos(all_videos=False):
122
+ """(video_id, video_path) of videos whose items are still in the pool: base items
123
+ that are mcq, kept by step 0 (if run) and not removed by step 1 (if run)."""
124
+ import pyarrow.parquet as pq
125
+ df = pq.read_table(pc.BASE_PARQUET, columns=["benchmark", "item_id", "video_key", "video_id",
126
+ "video_path", "format"]).to_pandas()
127
+ hashes = pc.manifest_hashes()
128
+ pend = df["video_id"].str.startswith("k:")
129
+ new = df.loc[pend, "video_key"].map(hashes)
130
+ got = new.notna()
131
+ df.loc[new[got].index, "video_id"] = new[got].values
132
+ df.loc[new[got].index, "video_path"] = [pc.normalized_path(x) for x in new[got].values]
133
+ df = df[df["video_path"].notna()]
134
+ if not all_videos:
135
+ df = df[df["format"] == "mcq"]
136
+ if os.path.exists(pc.STEP0_KEPT):
137
+ kept = pq.read_table(pc.STEP0_KEPT, columns=["item_id", "kept"]).to_pandas()
138
+ keep_ids = set(kept.loc[kept["kept"], "item_id"])
139
+ df = df[df["item_id"].isin(keep_ids)]
140
+ ok1, _ = pc.load_step_rows(1)
141
+ if ok1:
142
+ removed = {i for i, r in ok1.items() if r.get("remove")}
143
+ df = df[~df["item_id"].isin(removed)]
144
+ vids = df.drop_duplicates("video_id")[["video_id", "video_path"]]
145
+ return list(vids.itertuples(index=False, name=None))
146
+
147
+
148
+ def shard_of(video_id, n):
149
+ return int(hashlib.sha1(video_id.encode()).hexdigest()[:8], 16) % n
150
+
151
+
152
+ def work_one(video_id, video_path):
153
+ t0 = time.time()
154
+ try:
155
+ info = ensure_frames(video_id, video_path)
156
+ return video_id, None, len(info["keys"]), round(time.time() - t0, 2)
157
+ except Exception as e:
158
+ return video_id, f"{type(e).__name__}: {str(e)[:200]}", 0, round(time.time() - t0, 2)
159
+
160
+
161
+ def main():
162
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
163
+ ap.add_argument("--shard", default=None, help="i/k (default: Slurm array env or 0/1)")
164
+ ap.add_argument("--workers", type=int, default=max(1, int(os.environ.get("SLURM_CPUS_PER_TASK", 16)) // 2))
165
+ ap.add_argument("--limit", type=int, default=None)
166
+ ap.add_argument("--video-ids", default=None, help="file with one video_id per line (smoke tests)")
167
+ ap.add_argument("--all-videos", action="store_true", help="every normalized video of the base items")
168
+ ap.add_argument("--stats", action="store_true")
169
+ a = ap.parse_args()
170
+ pc.ensure_dirs()
171
+ vids = pool_videos(a.all_videos)
172
+ if a.video_ids:
173
+ want = {l.strip() for l in open(a.video_ids) if l.strip()}
174
+ vids = [v for v in vids if v[0] in want]
175
+ cached = [v for v in vids if load_frames_json(v[0]) is not None]
176
+ if a.stats:
177
+ print(f"pool videos with a normalized file: {len(vids)}; frames cached: {len(cached)}; "
178
+ f"missing: {len(vids) - len(cached)}")
179
+ return
180
+ if a.shard:
181
+ tid, n = (int(x) for x in a.shard.split("/"))
182
+ else:
183
+ tid, n = pc.slurm_task()
184
+ todo = [v for v in vids if load_frames_json(v[0]) is None and shard_of(v[0], n) == tid]
185
+ if a.limit:
186
+ todo = todo[:a.limit]
187
+ log(f"frames shard {tid}/{n}: {len(todo)} video(s) to decode of {len(vids)} "
188
+ f"({len(cached)} already cached); workers={a.workers}", "frames")
189
+ if not todo:
190
+ return
191
+ t0 = time.time()
192
+ n_ok = n_err = n_frames = 0
193
+ errs = []
194
+ with ProcessPoolExecutor(max_workers=a.workers) as ex:
195
+ futs = [ex.submit(work_one, v, p) for v, p in todo]
196
+ for i, f in enumerate(as_completed(futs), 1):
197
+ vid, err, nf, dt = f.result()
198
+ if err:
199
+ n_err += 1
200
+ errs.append(dict(video_id=vid, error=err))
201
+ else:
202
+ n_ok += 1
203
+ n_frames += nf
204
+ if i % 200 == 0 or i == len(todo):
205
+ el = time.time() - t0
206
+ log(f"{i}/{len(todo)} ok={n_ok} err={n_err} {i / el:.2f} videos/s", "frames")
207
+ el = time.time() - t0
208
+ if errs:
209
+ with open(os.path.join(pc.LOG_DIR, "pool_frames_errors.jsonl"), "a") as f:
210
+ for e in errs:
211
+ f.write(json.dumps(dict(ts=time.strftime("%F %T"), **e)) + "\n")
212
+ with open(os.path.join(pc.LOG_DIR, "pool_timing.jsonl"), "a") as f:
213
+ f.write(json.dumps(dict(ts=time.strftime("%F %T"), stage="frames", shard=f"{tid}/{n}", n_videos=len(todo),
214
+ n_ok=n_ok, n_err=n_err, n_frames=n_frames, wall_s=round(el, 1),
215
+ videos_per_s=round(len(todo) / max(el, 1e-9), 3), workers=a.workers)) + "\n")
216
+ log(f"done: ok={n_ok} err={n_err} frames={n_frames} in {el / 60:.1f} min "
217
+ f"({len(todo) / max(el, 1e-9):.2f} videos/s)", "frames")
218
+
219
+
220
+ if __name__ == "__main__":
221
+ main()
supplement_20260910/code/exp/analysis/pool/pool_common.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared paths, schema helpers and the vLLM option-letter log-prob client for the
2
+ full-item-pool screening run (exp/analysis/pool/TASK.md).
3
+
4
+ Layout
5
+ exp/results/pool/ small tabular outputs (csv/md) + parquet/duckdb
6
+ pool_items_base.parquet pool_schema.py (all items, TASK schema)
7
+ step0_kept.parquet step0_screen.py (dedup verdict per item)
8
+ screen_counts_full.csv step0_screen.py
9
+ step1/<bench>[.p<j>].jsonl step1_blind.py (one row per item, append-only)
10
+ step2/<bench>[.p<j>].jsonl step2_single_frame.py
11
+ step3/<bench>[.p<j>].jsonl step3_v32_2b.py
12
+ pool_items.parquet, pool.duckdb, pool_summary.md, run_accounting.csv (assemble/accounting)
13
+ bench_exp/work/pool_items_cache/ per-bench enumeration cache (jsonl) for the 88
14
+ benchmarks without a T3 full-text export
15
+ bench_exp/work/pool_embeddings/ bge-large-en-v1.5 cache per bench (ids.json + .npy),
16
+ same layout as exp/data/embeddings/text
17
+ bench_exp/work/pool_frames/<video_id>/ frame_<k>.jpg (448 px long side) + frames.json
18
+
19
+ Item id = the pipeline qid (f"{bench}_{pool_index}", or the stage_b adapter qid for
20
+ MVBench / LVBench / VideoMMMU). video_id = normalized content_hash, or
21
+ "k:" + sha1(video_key)[:16] while the video is not yet normalized.
22
+ """
23
+ import fcntl
24
+ import hashlib
25
+ import json
26
+ import math
27
+ import os
28
+ import random
29
+ import re
30
+ import sys
31
+ import time
32
+
33
+ HERE = os.path.dirname(os.path.abspath(__file__)) # exp/analysis/pool
34
+ EXP = os.path.abspath(os.path.join(HERE, "..", "..")) # exp
35
+ REPO = os.path.dirname(EXP)
36
+ PIPE = os.path.join(EXP, "pipeline")
37
+ for p in (PIPE, os.path.join(EXP, "t3")):
38
+ if p not in sys.path:
39
+ sys.path.insert(0, p)
40
+ os.environ.setdefault("FINEBENCH_ROUTE", "yt") # FineBench samples were drawn with the YouTube route
41
+
42
+ # Off-cluster runs (exp/analysis/pool/REMOTE_README.md, HF dataset GMLRVigil/BenchCheck-Pool): POOL_BASE
43
+ # replaces the cluster data root (the store / manifest / caches under it are optional for steps 1-3),
44
+ # POOL_FRAMES_DIR points at the unpacked frame cache, POOL_RESULTS_ROOT at the items + step outputs.
45
+ BASE = os.environ.get("POOL_BASE") or "/vast/projects/jgu32/lab/enxin/bench_exp"
46
+ STORE = f"{BASE}/store"
47
+ WORK = f"{BASE}/work"
48
+ NORMALIZED = f"{STORE}/normalized"
49
+ MANIFEST_JSONL = f"{BASE}/logs/manifest.jsonl"
50
+ T3_FULL = f"{BASE}/t3_export_n1_fulltext/full"
51
+ ITEMS_CACHE = f"{WORK}/pool_items_cache"
52
+ EMB_DIR = f"{WORK}/pool_embeddings"
53
+ FRAMES_DIR = os.environ.get("POOL_FRAMES_DIR") or f"{WORK}/pool_frames"
54
+ LOG_DIR = f"{BASE}/logs"
55
+
56
+ RESULTS = os.environ.get("POOL_RESULTS_ROOT") or os.path.join(EXP, "results", "pool") # override for smoke tests
57
+ BASE_PARQUET = os.path.join(RESULTS, "pool_items_base.parquet")
58
+ SCHEMA_MANIFEST = os.path.join(RESULTS, "pool_schema_manifest.csv")
59
+ STEP0_KEPT = os.path.join(RESULTS, "step0_kept.parquet")
60
+ STEP0_REMOVED = os.path.join(RESULTS, "step0_removed.jsonl")
61
+ SCREEN_CSV = os.path.join(RESULTS, "screen_counts_full.csv")
62
+ POOL_PARQUET = os.path.join(RESULTS, "pool_items.parquet")
63
+ POOL_DUCKDB = os.path.join(RESULTS, "pool.duckdb")
64
+ POOL_SUMMARY_MD = os.path.join(RESULTS, "pool_summary.md")
65
+ POOL_SUMMARY_CSV = os.path.join(RESULTS, "pool_summary.csv")
66
+ ACCOUNTING_CSV = os.path.join(RESULTS, "run_accounting.csv")
67
+
68
+ VB_CSV = os.path.join(EXP, "video_benchmarks.csv")
69
+ REGISTRY_CSV = os.path.join(REPO, "meta", "benchmark_registry.csv")
70
+ SAMPLE_DIRS = [os.path.join(EXP, "data", "samples"), os.path.join(EXP, "data", "samples_n1")]
71
+
72
+ HF_HUB = "/vast/projects/jgu32/lab/enxin/cache/hf/hub"
73
+ MODELS = {
74
+ # step -> (served model name, snapshot dir)
75
+ "8b": ("Qwen/Qwen3-VL-8B-Instruct",
76
+ f"{HF_HUB}/models--Qwen--Qwen3-VL-8B-Instruct/snapshots/0c351dd01ed87e9c1b53cbc748cba10e6187ff3b"),
77
+ "2b": ("Qwen/Qwen3-VL-2B-Instruct",
78
+ f"{HF_HUB}/models--Qwen--Qwen3-VL-2B-Instruct/snapshots/89644892e4d85e24eaac8bacfd4f463576704203"),
79
+ }
80
+ BGE_SNAPSHOT = f"{HF_HUB}/models--BAAI--bge-large-en-v1.5/snapshots/d4aa6901d3a41ba39fb536a557fa166f842b0e09"
81
+
82
+ # 2026-09-10 (user decision, pool <= 50k without per-benchmark caps): three more removal steps that mirror
83
+ # the paper's pyramid levels missing from the screen -- option level (options-only, 8B), the frame-level
84
+ # reference model (8B on the 32-frame grid at 448 px) and the order level (2B on the shuffled 32-frame grid).
85
+ STEPS = {1: "blind", 2: "single_frame", 3: "v32_2b", 4: "opt_only", 5: "v32_2b_shuffle", 6: "v32_8b"}
86
+ STEP_MODEL = {1: "8b", 2: "8b", 3: "2b", 4: "8b", 5: "2b", 6: "8b"}
87
+ VISUAL_STEPS = {2, 3, 5, 6}
88
+ PROMPT_OPT_ONLY = "{intro}\n\nOptions:\n{opts}\nAnswer with the option letter only."
89
+ STEP_DIR = {k: os.path.join(RESULTS, f"step{k}") for k in STEPS}
90
+
91
+ SEED = 42
92
+ N_PERM = 4
93
+ LOG2 = math.log(2.0)
94
+ LP_FLOOR = math.log(1e-6) # letter absent from the top-20 log-probs
95
+ TOP_LOGPROBS = 20
96
+ MAX_OPTIONS = 26 # letters A..Z; more options -> format=open
97
+ LETTERS = [chr(65 + i) for i in range(MAX_OPTIONS)]
98
+ FRAME_LONG_SIDE = 448
99
+ N_FRAMES_V32 = 32
100
+ MID_POS = 16 # stage_p1_runner v_1: grid32[16]
101
+ JPEG_QUALITY = 85
102
+ MAX_ERRORS_PER_ITEM = 3 # error rows before an item is treated as permanently failed
103
+
104
+ # one prompt skeleton for all three steps (intro strings reused from stage_p1_runner)
105
+ PROMPT = "{intro}\n\nQuestion: {q}\nOptions:\n{opts}\nAnswer with the option letter only."
106
+ ASSISTANT_PREFIX = "Answer:" # continue_final_message -> the next token is the letter
107
+ _TOKEN_LETTER = re.compile(r"^\s*[\(\[]?([A-Z])[\)\]\.:]?\s*$")
108
+
109
+
110
+ def log(msg, tag="pool"):
111
+ print(f"[{tag}] {time.strftime('%H:%M:%S')} {msg}", file=sys.stderr, flush=True)
112
+
113
+
114
+ def ensure_dirs():
115
+ for d in (RESULTS, ITEMS_CACHE, EMB_DIR, FRAMES_DIR, LOG_DIR, *STEP_DIR.values()):
116
+ os.makedirs(d, exist_ok=True)
117
+
118
+
119
+ # ------------------------------------------------------------------ benches
120
+ def bench_list():
121
+ """Stems of exp/data/samples/*.jsonl + exp/data/samples_n1/*.jsonl (139 onboarded)."""
122
+ import glob
123
+ names = set()
124
+ for d in SAMPLE_DIRS:
125
+ for p in glob.glob(os.path.join(d, "*.jsonl")):
126
+ if os.path.exists(p):
127
+ names.add(os.path.basename(p)[:-6])
128
+ return sorted(names)
129
+
130
+
131
+ def sample_path(bench):
132
+ for d in SAMPLE_DIRS:
133
+ p = os.path.join(d, f"{bench}.jsonl")
134
+ if os.path.exists(p):
135
+ return p
136
+ return None
137
+
138
+
139
+ def read_jsonl(path):
140
+ out = []
141
+ with open(path, encoding="utf-8") as f:
142
+ for line in f:
143
+ if line.strip():
144
+ try:
145
+ out.append(json.loads(line))
146
+ except json.JSONDecodeError:
147
+ continue # torn final line of a killed writer
148
+ return out
149
+
150
+
151
+ def key_of(ref):
152
+ return f"{ref['repo']}::{ref.get('zip_path', '')}::{ref['member']}"
153
+
154
+
155
+ def manifest_hashes():
156
+ """video_key -> content_hash for logs/manifest.jsonl status=done rows (last wins)."""
157
+ m = {}
158
+ if not os.path.exists(MANIFEST_JSONL):
159
+ return m
160
+ with open(MANIFEST_JSONL, encoding="utf-8") as f:
161
+ for line in f:
162
+ try:
163
+ r = json.loads(line)
164
+ except Exception:
165
+ continue
166
+ if r.get("status") == "done" and r.get("content_hash") and "::" in str(r.get("key", "")):
167
+ m[r["key"]] = r["content_hash"]
168
+ return m
169
+
170
+
171
+ def key_video_id(key):
172
+ return "k:" + hashlib.sha1(key.encode("utf-8")).hexdigest()[:16]
173
+
174
+
175
+ def normalized_path(h):
176
+ return f"{NORMALIZED}/{h}/video.mp4"
177
+
178
+
179
+ def meta_of(h):
180
+ try:
181
+ return json.load(open(f"{NORMALIZED}/{h}/meta.json"))
182
+ except Exception:
183
+ return None
184
+
185
+
186
+ # ------------------------------------------------------------------ options
187
+ _SEQ_PREFIX = re.compile(r"^\s*[\(\[]?([A-Za-z])[\)\]\.:]\s*(.*)$", re.S)
188
+
189
+
190
+ def strip_sequential_prefix(opts):
191
+ """['A. x', 'B. y'] -> (['x', 'y'], True) when every option carries the letter of
192
+ its position (A, B, C, ...); otherwise the list is returned unchanged."""
193
+ texts = []
194
+ for i, o in enumerate(opts):
195
+ m = _SEQ_PREFIX.match(str(o))
196
+ if not m or m.group(1).upper() != chr(65 + i):
197
+ return [str(o) for o in opts], False
198
+ texts.append(m.group(2).strip())
199
+ return texts, True
200
+
201
+
202
+ def render_options(texts):
203
+ return "\n".join(f"{LETTERS[i]}. {t}" for i, t in enumerate(texts))
204
+
205
+
206
+ def item_text(question, options):
207
+ """Text embedded for the near-duplicate check: question + options."""
208
+ q = " ".join(str(question or "").split())
209
+ if isinstance(options, list) and options:
210
+ return q + "\n" + "\n".join(str(o) for o in options)
211
+ return q
212
+
213
+
214
+ def permutations_for(item_id, k, n_perm=N_PERM, seed=SEED):
215
+ """TASK.md step 1: n_perm option shuffles, seed 42, per item. perm[j] = original
216
+ option index shown at position j."""
217
+ rng = random.Random(f"{seed}|{item_id}")
218
+ return [rng.sample(range(k), k) for _ in range(n_perm)]
219
+
220
+
221
+ # ------------------------------------------------------------------ log-probs
222
+ def letter_logprobs(top_logprobs, k):
223
+ """top_logprobs: list of {token, logprob} for the first generated position.
224
+ -> (lp list over the k presented letters, missing letters, matched variants).
225
+ Tokenization variants ('A', ' A', '(A', 'A.') are merged by log-sum-exp."""
226
+ acc = {}
227
+ variants = {}
228
+ for e in top_logprobs or []:
229
+ m = _TOKEN_LETTER.match(e.get("token") or "")
230
+ if not m:
231
+ continue
232
+ L = m.group(1)
233
+ if L not in acc:
234
+ acc[L] = e["logprob"]
235
+ else:
236
+ a, b = acc[L], e["logprob"]
237
+ acc[L] = max(a, b) + math.log1p(math.exp(-abs(a - b)))
238
+ variants.setdefault(L, []).append(e.get("token"))
239
+ lp, missing = [], []
240
+ for i in range(k):
241
+ L = LETTERS[i]
242
+ if L in acc:
243
+ lp.append(float(acc[L]))
244
+ else:
245
+ lp.append(LP_FLOOR)
246
+ missing.append(L)
247
+ return lp, missing, variants
248
+
249
+
250
+ def margin_of(lp, correct_pos):
251
+ others = [v for i, v in enumerate(lp) if i != correct_pos]
252
+ return lp[correct_pos] - (sum(others) / len(others) if others else 0.0)
253
+
254
+
255
+ def argmax_pos(lp):
256
+ best = max(lp)
257
+ return lp.index(best)
258
+
259
+
260
+ class ContextTooLong(Exception):
261
+ pass
262
+
263
+
264
+ def logprob_request(endpoint, model, prompt, images_b64=None, timeout=(10, 600)):
265
+ """One forward: max_tokens=1, logprobs=true, top_logprobs=20; the assistant turn is
266
+ prefilled with ASSISTANT_PREFIX (continue_final_message) so the next token is the
267
+ letter. -> dict(top=[{token, logprob}], top1_token, prompt_tokens, latency_s)."""
268
+ import requests
269
+ content = [{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + b}}
270
+ for b in (images_b64 or [])]
271
+ content.append({"type": "text", "text": prompt})
272
+ body = {"model": model, "temperature": 0.0, "max_tokens": 1,
273
+ "logprobs": True, "top_logprobs": TOP_LOGPROBS,
274
+ "messages": [{"role": "user", "content": content},
275
+ {"role": "assistant", "content": ASSISTANT_PREFIX}],
276
+ "continue_final_message": True, "add_generation_prompt": False}
277
+ t0 = time.time()
278
+ r = requests.post(f"{endpoint}/chat/completions", json=body, timeout=timeout)
279
+ if r.status_code == 400 and ("maximum" in r.text or "longer than" in r.text
280
+ or "context length" in r.text):
281
+ raise ContextTooLong(r.text[:200])
282
+ r.raise_for_status()
283
+ d = r.json()
284
+ ch = d["choices"][0]
285
+ lpc = (ch.get("logprobs") or {}).get("content") or []
286
+ if not lpc:
287
+ raise RuntimeError("no logprobs in response")
288
+ top = [{"token": e.get("token"), "logprob": e.get("logprob")} for e in (lpc[0].get("top_logprobs") or [])]
289
+ return dict(top=top, top1_token=lpc[0].get("token"),
290
+ prompt_tokens=(d.get("usage") or {}).get("prompt_tokens", 0),
291
+ latency_s=round(time.time() - t0, 4))
292
+
293
+
294
+ # ------------------------------------------------------------------ result files
295
+ def bench_files(step, bench):
296
+ """All jsonl files of a benchmark under step<k>/ (part files included)."""
297
+ d = STEP_DIR[step]
298
+ if not os.path.isdir(d):
299
+ return []
300
+ out = []
301
+ for f in os.listdir(d):
302
+ if f == f"{bench}.jsonl" or (f.startswith(f"{bench}.p") and f.endswith(".jsonl")
303
+ and f[len(bench) + 2:-6].isdigit()):
304
+ out.append(os.path.join(d, f))
305
+ return sorted(out)
306
+
307
+
308
+ def unit_file(step, bench, part, n_parts):
309
+ return os.path.join(STEP_DIR[step], f"{bench}.jsonl" if n_parts == 1 else f"{bench}.p{part}.jsonl")
310
+
311
+
312
+ def load_step_rows(step, benches=None):
313
+ """item_id -> last successful row; plus item_id -> error count.
314
+ Rows with status != ok are errors (never counted as done)."""
315
+ ok, errs = {}, {}
316
+ d = STEP_DIR[step]
317
+ if not os.path.isdir(d):
318
+ return ok, errs
319
+ files = []
320
+ for f in sorted(os.listdir(d)):
321
+ if not f.endswith(".jsonl"):
322
+ continue
323
+ if benches is not None:
324
+ b = f[:-6]
325
+ if "." in b and b.rsplit(".", 1)[1][1:].isdigit() and b.rsplit(".", 1)[1].startswith("p"):
326
+ b = b.rsplit(".", 1)[0]
327
+ if b not in benches:
328
+ continue
329
+ files.append(os.path.join(d, f))
330
+ for p in files:
331
+ for r in read_jsonl(p):
332
+ iid = r.get("item_id")
333
+ if iid is None:
334
+ continue
335
+ if r.get("status", "ok") == "ok":
336
+ ok[iid] = r
337
+ else:
338
+ errs[iid] = errs.get(iid, 0) + 1
339
+ return ok, errs
340
+
341
+
342
+ def append_rows(path, rows):
343
+ """Append json rows under an exclusive flock (several array tasks may touch a file
344
+ across re-runs; the lock keeps rows whole)."""
345
+ os.makedirs(os.path.dirname(path), exist_ok=True)
346
+ data = "".join(json.dumps(r, ensure_ascii=False, default=str) + "\n" for r in rows)
347
+ with open(path, "a", encoding="utf-8") as f:
348
+ fcntl.flock(f, fcntl.LOCK_EX)
349
+ try:
350
+ f.write(data)
351
+ f.flush()
352
+ finally:
353
+ fcntl.flock(f, fcntl.LOCK_UN)
354
+
355
+
356
+ # ------------------------------------------------------------------ sharding
357
+ def plan_units(work, max_unit=20000):
358
+ """work: list of (bench, [item_ids sorted]) -> units [(bench, part, n_parts, ids)].
359
+ Big benchmarks are split into parts of <= max_unit items (deterministic by sorted
360
+ item_id) so one array task never owns more than max_unit items of one file."""
361
+ units = []
362
+ for bench, ids in work:
363
+ ids = sorted(ids)
364
+ n_parts = max(1, math.ceil(len(ids) / max_unit)) if ids else 1
365
+ size = math.ceil(len(ids) / n_parts) if ids else 0
366
+ for part in range(n_parts):
367
+ units.append((bench, part, n_parts, ids[part * size:(part + 1) * size]))
368
+ return units
369
+
370
+
371
+ def assign_units(units, n_tasks, task_id, weight=lambda u: len(u[3])):
372
+ """Deterministic LPT (largest first to the least loaded task)."""
373
+ loads = [0.0] * n_tasks
374
+ mine = []
375
+ for u in sorted(units, key=lambda u: (-weight(u), u[0], u[1])):
376
+ t = min(range(n_tasks), key=lambda i: (loads[i], i))
377
+ loads[t] += weight(u)
378
+ if t == task_id:
379
+ mine.append(u)
380
+ return mine, loads
381
+
382
+
383
+ def slurm_task():
384
+ """(task_id, n_tasks) from the Slurm array environment; (0, 1) outside Slurm."""
385
+ tid = int(os.environ.get("SLURM_ARRAY_TASK_ID", 0))
386
+ n = os.environ.get("SLURM_ARRAY_TASK_COUNT")
387
+ if n is None:
388
+ lo, hi = os.environ.get("SLURM_ARRAY_TASK_MIN"), os.environ.get("SLURM_ARRAY_TASK_MAX")
389
+ n = int(hi) - int(lo) + 1 if lo is not None and hi is not None else 1
390
+ if lo is not None:
391
+ tid -= int(lo)
392
+ return tid, int(n)
supplement_20260910/code/exp/analysis/pool/pool_prompts.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prompt intro strings of the pool screening steps.
2
+
3
+ Copied verbatim from exp/pipeline/stage_p1_runner.py (INTRO_BLIND / INTRO_VISUAL) so the pool
4
+ client runs off-cluster without the P1 runner and its dependencies. When stage_p1_runner is
5
+ importable the strings are asserted equal at import time.
6
+ """
7
+ INTRO_VISUAL = ("You are given {n} frame(s) sampled from a video. "
8
+ "Answer the question based on these frames.")
9
+ INTRO_BLIND = ("You are given NO frames from the video. "
10
+ "Answer the question from the text alone.")
11
+ INTRO_OPT_ONLY = ("You are given NO frames from the video and NO question text. "
12
+ "Using only the answer options below, choose the option most likely to be correct.")
13
+
14
+ try: # keep the two copies in lockstep on the cluster
15
+ import stage_p1_runner as _p1 # noqa: E402
16
+ assert _p1.INTRO_VISUAL == INTRO_VISUAL and _p1.INTRO_BLIND == INTRO_BLIND \
17
+ and _p1.INTRO_OPT_ONLY == INTRO_OPT_ONLY, \
18
+ "pool_prompts.py drifted from stage_p1_runner.py"
19
+ except ImportError:
20
+ pass
supplement_20260910/code/exp/analysis/pool/pool_steps.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """pool_steps.py — shared vLLM client for the three screening steps (TASK.md).
3
+
4
+ step 1 blind Qwen3-VL-8B, text only. N_PERM=4 option shuffles per item
5
+ (random.Random(f"42|{item_id}")), one forward each, log-probs of the
6
+ presented letters. blind_acc_4perm = share of permutations whose
7
+ argmax letter is the correct one; blind_margin = mean over permutations
8
+ of (log p(correct) - mean log p(others)). Removed when
9
+ blind_margin > log 2 AND >= 3 of 4 permutations pick the correct option.
10
+ step 2 single_frame Qwen3-VL-8B, the middle grid frame (v_1 position, 448 px long side),
11
+ original option order, one forward. sf_correct = argmax is correct;
12
+ sf_margin as above. Removed when sf_correct AND sf_margin > log 2.
13
+ step 3 v32_2b Qwen3-VL-2B, the 32-frame grid (448 px), one forward.
14
+ v32_2b_correct / v32_2b_margin; same removal rule.
15
+
16
+ Chain: step 1 runs on step-0 kept mcq items; step 2 on step-1 survivors with a normalized
17
+ video; step 3 on step-2 survivors. Every step is resumable by item_id (rows with
18
+ status != ok are retried up to MAX_ERRORS_PER_ITEM times). Log-probs: max_tokens=1,
19
+ logprobs=true, top_logprobs=20, assistant turn prefilled with "Answer:" so the next token
20
+ is the letter; token variants ("A", " A", "(A", "A.") are merged; a letter absent from
21
+ the top-20 gets log(1e-6) and is listed in `missing`.
22
+
23
+ Usage (inside the GPU job; step1_blind.py / step2_single_frame.py / step3_v32_2b.py wrap this):
24
+ pool_steps.py --step 1 --endpoint http://127.0.0.1:8001/v1 [--workers 32]
25
+ [--bench A,B] [--limit N] [--max-minutes M] [--plan-only] [--shard i/k]
26
+ """
27
+ import argparse
28
+ import base64
29
+ import json
30
+ import os
31
+ import random
32
+ import sys
33
+ import threading
34
+ import time
35
+ from collections import OrderedDict
36
+ from concurrent.futures import ThreadPoolExecutor, as_completed
37
+
38
+ import pyarrow.parquet as pq
39
+
40
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
41
+ import pool_common as pc # noqa: E402
42
+ from pool_common import log # noqa: E402
43
+ import frames_decode as fd # noqa: E402
44
+ from pool_prompts import INTRO_BLIND, INTRO_OPT_ONLY, INTRO_VISUAL # noqa: E402 (verbatim copies of stage_p1_runner)
45
+
46
+ MAX_ATTEMPTS = 5
47
+ DEFAULT_WORKERS = {1: 32, 2: 16, 3: 8, 4: 32, 5: 8, 6: 8}
48
+
49
+
50
+ # ------------------------------------------------------------------ items
51
+ def load_items():
52
+ """Base items with video_id/video_path refreshed from the current manifest."""
53
+ cols = ["benchmark", "item_id", "video_key", "video_id", "video_path", "question", "options",
54
+ "n_options", "answer_idx", "format"]
55
+ df = pq.read_table(pc.BASE_PARQUET, columns=cols).to_pandas()
56
+ hashes = pc.manifest_hashes()
57
+ pend = df["video_id"].str.startswith("k:")
58
+ new = df.loc[pend, "video_key"].map(hashes)
59
+ got = new.notna()
60
+ df.loc[new[got].index, "video_id"] = new[got].values
61
+ df.loc[new[got].index, "video_path"] = [pc.normalized_path(x) for x in new[got].values]
62
+ return df
63
+
64
+
65
+ def eligible(step, df):
66
+ """Items this step should process (chain rule), plus a note on upstream state.
67
+ 2026-09-10: items whose options are a bare yes/no (true/false) pair are not multiple-choice items
68
+ under the project rule and are skipped by every step (they stay in the parquet, assemble marks them)."""
69
+ df = df[df["format"] == "mcq"]
70
+ from chance import _yes_no_options
71
+ yn = df["options"].map(lambda o: _yes_no_options(list(o)) if o is not None else False)
72
+ df = df[~yn]
73
+ notes = [f"yes/no-option items skipped={int(yn.sum())}"]
74
+ if os.path.exists(pc.STEP0_KEPT):
75
+ kept = pq.read_table(pc.STEP0_KEPT, columns=["item_id", "kept"]).to_pandas()
76
+ keep_ids = set(kept.loc[kept["kept"], "item_id"])
77
+ df = df[df["item_id"].isin(keep_ids)]
78
+ else:
79
+ notes.append("step0_kept.parquet missing: no dedup applied")
80
+ if step in (2, 3):
81
+ ok1, _ = pc.load_step_rows(1)
82
+ surv = {i for i, r in ok1.items() if not r.get("remove")}
83
+ df = df[df["item_id"].isin(surv)]
84
+ df = df[df["video_path"].notna()]
85
+ notes.append(f"step1 done={len(ok1)} survivors={len(surv)}")
86
+ if step == 3:
87
+ ok2, _ = pc.load_step_rows(2)
88
+ surv = {i for i, r in ok2.items() if not r.get("remove")}
89
+ df = df[df["item_id"].isin(surv)]
90
+ notes.append(f"step2 done={len(ok2)} survivors={len(surv)}")
91
+ if step >= 4:
92
+ # steps 4-6 run on the step-1 survivors that no other step (with rows) has removed; they do not
93
+ # wait for steps 2/3 (removal is "any step"), so machines can share the work; visual steps need frames
94
+ ok1, _ = pc.load_step_rows(1)
95
+ surv = {i for i, r in ok1.items() if not r.get("remove")}
96
+ df = df[df["item_id"].isin(surv)]
97
+ notes.append(f"step1 done={len(ok1)} survivors={len(surv)}")
98
+ for other in pc.STEPS:
99
+ if other in (1, step):
100
+ continue
101
+ oko, _ = pc.load_step_rows(other)
102
+ removed = {i for i, r in oko.items() if r.get("remove")}
103
+ if removed:
104
+ df = df[~df["item_id"].isin(removed)]
105
+ notes.append(f"step{other} removed={len(removed)} excluded")
106
+ if step in pc.VISUAL_STEPS:
107
+ df = df[df["video_path"].notna()]
108
+ return df, notes
109
+
110
+
111
+ # ------------------------------------------------------------------ runner
112
+ class Runner:
113
+ def __init__(self, step, endpoint, model, workers):
114
+ self.step, self.endpoint, self.model, self.workers = step, endpoint, model, workers
115
+ self.frames_cache = OrderedDict() # video_id -> (info, {k: b64})
116
+ self.cache_lock = threading.Lock()
117
+ self.meta_cache = {}
118
+ self.stats = dict(items=0, forwards=0, errors=0, latency_s=0.0, prompt_tokens=0,
119
+ removed=0, missing_letter_forwards=0, decode_s=0.0)
120
+ self.stats_lock = threading.Lock()
121
+ self.variants = {}
122
+
123
+ def bump(self, **kw):
124
+ with self.stats_lock:
125
+ for k, v in kw.items():
126
+ self.stats[k] += v
127
+
128
+ def note_variants(self, variants):
129
+ with self.stats_lock:
130
+ for L, toks in variants.items():
131
+ for t in toks:
132
+ key = repr(t)
133
+ self.variants[key] = self.variants.get(key, 0) + 1
134
+
135
+ def frames_b64(self, video_id, video_path, keys):
136
+ with self.cache_lock:
137
+ ent = self.frames_cache.get(video_id)
138
+ if ent is not None:
139
+ self.frames_cache.move_to_end(video_id)
140
+ if ent is None:
141
+ t0 = time.time()
142
+ meta = self.meta_cache.get(video_id) or pc.meta_of(video_id)
143
+ self.meta_cache[video_id] = meta
144
+ info = fd.ensure_frames(video_id, video_path, meta)
145
+ b64 = {k: base64.b64encode(fd.frame_bytes(video_id, k)).decode() for k in info["keys"]}
146
+ ent = (info, b64)
147
+ self.bump(decode_s=time.time() - t0)
148
+ with self.cache_lock:
149
+ self.frames_cache[video_id] = ent
150
+ while len(self.frames_cache) > 64:
151
+ self.frames_cache.popitem(last=False)
152
+ info, b64 = ent
153
+ if keys == "mid":
154
+ return info, [b64[info["mid_k"]]], [info["mid_k"]]
155
+ return info, [b64[k] for k in info["keys"]], list(info["keys"])
156
+
157
+ def forward(self, prompt, images, who):
158
+ last = None
159
+ for attempt in range(MAX_ATTEMPTS):
160
+ try:
161
+ return pc.logprob_request(self.endpoint, self.model, prompt, images)
162
+ except pc.ContextTooLong:
163
+ raise
164
+ except Exception as e: # connection / 5xx / timeout
165
+ last = e
166
+ time.sleep(min(20, 2 ** attempt + random.uniform(0, 1)))
167
+ raise RuntimeError(f"{who}: {type(last).__name__}: {str(last)[:200]}")
168
+
169
+ # ---- per item
170
+ def run_item(self, row):
171
+ iid, bench = row["item_id"], row["benchmark"]
172
+ opts = list(row["options"])
173
+ k, aidx = len(opts), int(row["answer_idx"])
174
+ base = dict(item_id=iid, benchmark=bench, step=pc.STEPS[self.step], model=self.model,
175
+ n_options=k, ts=time.strftime("%F %T"))
176
+ try:
177
+ if self.step == 1:
178
+ out = self.blind(iid, row["question"], opts, k, aidx)
179
+ elif self.step == 4:
180
+ out = self.blind(iid, None, opts, k, aidx, opt_only=True)
181
+ else:
182
+ out = self.visual(iid, row, opts, k, aidx)
183
+ out.update(base)
184
+ out["status"] = "ok"
185
+ self.bump(items=1, removed=int(bool(out["remove"])))
186
+ return out
187
+ except Exception as e:
188
+ self.bump(errors=1)
189
+ return dict(base, status="error", error=f"{type(e).__name__}: {str(e)[:300]}")
190
+
191
+ def blind(self, iid, question, opts, k, aidx, opt_only=False):
192
+ perms = pc.permutations_for(iid, k)
193
+ recs, hits, margins, lat, ptok = [], 0, [], 0.0, 0
194
+ for perm in perms:
195
+ texts = [opts[i] for i in perm]
196
+ cpos = perm.index(aidx)
197
+ if opt_only: # step 4: option level of the pyramid -- no frames, no question text
198
+ prompt = pc.PROMPT_OPT_ONLY.format(intro=INTRO_OPT_ONLY, opts=pc.render_options(texts))
199
+ else:
200
+ prompt = pc.PROMPT.format(intro=INTRO_BLIND, q=question, opts=pc.render_options(texts))
201
+ r = self.forward(prompt, None, f"{iid}/{'opt_only' if opt_only else 'blind'}")
202
+ lp, missing, variants = pc.letter_logprobs(r["top"], k)
203
+ self.note_variants(variants)
204
+ am = pc.argmax_pos(lp)
205
+ m = pc.margin_of(lp, cpos)
206
+ hit = int(am == cpos and lp[am] > pc.LP_FLOOR)
207
+ hits += hit
208
+ margins.append(m)
209
+ lat += r["latency_s"]
210
+ ptok += r["prompt_tokens"]
211
+ self.bump(forwards=1, latency_s=r["latency_s"], prompt_tokens=r["prompt_tokens"],
212
+ missing_letter_forwards=int(bool(missing)))
213
+ recs.append(dict(order=perm, correct_pos=cpos, lp=[round(x, 4) for x in lp], argmax=am,
214
+ hit=hit, margin=round(m, 4), missing=missing, top1_token=r["top1_token"]))
215
+ acc = hits / len(perms)
216
+ margin = sum(margins) / len(margins)
217
+ remove = bool(margin > pc.LOG2 and hits >= len(perms) - 1)
218
+ pre = "opt" if opt_only else "blind"
219
+ out = dict(perms=recs, remove=remove, n_forwards=len(perms), latency_s=round(lat, 4), prompt_tokens=ptok)
220
+ out[f"{pre}_acc_4perm"] = round(acc, 4)
221
+ out[f"{pre}_margin"] = round(margin, 4)
222
+ return out
223
+
224
+ def visual(self, iid, row, opts, k, aidx):
225
+ vid, vpath = row["video_id"], row["video_path"]
226
+ info, images, keys = self.frames_b64(vid, vpath, "mid" if self.step == 2 else "all")
227
+ perm_seed = None
228
+ if self.step == 5: # order level: the same 32 frames, one fixed per-item shuffle (stage_p1_runner v_32_shuffle)
229
+ perm_seed = f"42|{iid}"
230
+ order = list(range(len(images)))
231
+ random.Random(perm_seed).shuffle(order)
232
+ images, keys = [images[i] for i in order], [keys[i] for i in order]
233
+ prompt = pc.PROMPT.format(intro=INTRO_VISUAL.format(n=len(images)), q=row["question"],
234
+ opts=pc.render_options(opts))
235
+ r = self.forward(prompt, images, f"{iid}/{pc.STEPS[self.step]}")
236
+ lp, missing, variants = pc.letter_logprobs(r["top"], k)
237
+ self.note_variants(variants)
238
+ am = pc.argmax_pos(lp)
239
+ m = pc.margin_of(lp, aidx)
240
+ correct = bool(am == aidx and lp[am] > pc.LP_FLOOR)
241
+ remove = bool(correct and m > pc.LOG2)
242
+ self.bump(forwards=1, latency_s=r["latency_s"], prompt_tokens=r["prompt_tokens"],
243
+ missing_letter_forwards=int(bool(missing)))
244
+ pre = {2: "sf", 3: "v32_2b", 5: "v32_2b_shuffle", 6: "v32_8b"}[self.step]
245
+ out = dict(video_id=vid, frame_keys=keys, n_frames=len(images), frame_wh=[info.get("w"), info.get("h")],
246
+ correct_pos=aidx, lp=[round(x, 4) for x in lp], argmax=am, missing=missing,
247
+ top1_token=r["top1_token"], remove=remove, n_forwards=1,
248
+ latency_s=r["latency_s"], prompt_tokens=r["prompt_tokens"])
249
+ if perm_seed:
250
+ out["perm_seed"] = perm_seed
251
+ out[f"{pre}_correct"] = correct
252
+ out[f"{pre}_margin"] = round(m, 4)
253
+ return out
254
+
255
+
256
+ def run_unit(runner, unit, rows_by_id, workers, deadline, flush_every=20):
257
+ bench, part, n_parts, ids = unit
258
+ path = pc.unit_file(runner.step, bench, part, n_parts)
259
+ rows = [rows_by_id[i] for i in ids]
260
+ if runner.step in pc.VISUAL_STEPS: # same-video items share the frame cache
261
+ rows.sort(key=lambda r: (r["video_id"], r["item_id"]))
262
+ buf, n_done, t0 = [], 0, time.time()
263
+ stopped = False
264
+ with ThreadPoolExecutor(max_workers=workers) as ex:
265
+ pending = set()
266
+ it = iter(rows)
267
+ while True:
268
+ while len(pending) < workers * 2 and not stopped:
269
+ if deadline and time.time() > deadline:
270
+ stopped = True
271
+ break
272
+ r = next(it, None)
273
+ if r is None:
274
+ stopped = True
275
+ break
276
+ pending.add(ex.submit(runner.run_item, r))
277
+ if not pending:
278
+ break
279
+ done = next(as_completed(pending))
280
+ pending.discard(done)
281
+ buf.append(done.result())
282
+ n_done += 1
283
+ if len(buf) >= flush_every:
284
+ pc.append_rows(path, buf)
285
+ buf = []
286
+ if n_done % 200 == 0:
287
+ st = runner.stats
288
+ el = time.time() - t0
289
+ log(f"{bench}.p{part}: {n_done}/{len(rows)} items, {st['forwards']} fwd total, "
290
+ f"{n_done / el:.2f} items/s, mean fwd latency {st['latency_s'] / max(st['forwards'], 1):.3f}s, "
291
+ f"errors={st['errors']}", f"step{runner.step}")
292
+ if buf:
293
+ pc.append_rows(path, buf)
294
+ return n_done, len(rows) - n_done
295
+
296
+
297
+ def main():
298
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
299
+ ap.add_argument("--step", type=int, required=True, choices=[1, 2, 3, 4, 5, 6])
300
+ ap.add_argument("--endpoint", default=None)
301
+ ap.add_argument("--workers", type=int, default=None)
302
+ ap.add_argument("--bench", default=None, help="comma list (default: all)")
303
+ ap.add_argument("--limit", type=int, default=None, help="first N eligible items per benchmark (smoke tests)")
304
+ ap.add_argument("--max-minutes", type=float, default=None, help="stop starting new items after M minutes")
305
+ ap.add_argument("--max-unit", type=int, default=20000)
306
+ ap.add_argument("--shard", default=None, help="i/k (default: Slurm array env or 0/1)")
307
+ ap.add_argument("--plan-only", action="store_true", help="print the remaining work of this shard and exit")
308
+ a = ap.parse_args()
309
+ pc.ensure_dirs()
310
+ step = a.step
311
+ model_name, _snap = pc.MODELS[pc.STEP_MODEL[step]]
312
+ workers = a.workers or DEFAULT_WORKERS[step]
313
+ t_start = time.time()
314
+
315
+ df = load_items()
316
+ elig, notes = eligible(step, df)
317
+ if a.bench:
318
+ want = {b.strip() for b in a.bench.split(",") if b.strip()}
319
+ elig = elig[elig["benchmark"].isin(want)]
320
+ ok, errs = pc.load_step_rows(step)
321
+ todo = elig[~elig["item_id"].isin(set(ok))]
322
+ perm_fail = {i for i, n in errs.items() if n >= pc.MAX_ERRORS_PER_ITEM}
323
+ todo = todo[~todo["item_id"].isin(perm_fail)]
324
+ if a.limit:
325
+ todo = todo.sort_values("item_id").groupby("benchmark", sort=False).head(a.limit)
326
+ work = [(b, list(g["item_id"])) for b, g in todo.groupby("benchmark", sort=True)]
327
+ units = pc.plan_units(work, a.max_unit)
328
+ if a.shard:
329
+ tid, n = (int(x) for x in a.shard.split("/"))
330
+ else:
331
+ tid, n = pc.slurm_task()
332
+ mine, loads = pc.assign_units(units, n, tid)
333
+ n_mine = sum(len(u[3]) for u in mine)
334
+ log(f"step {step} ({pc.STEPS[step]}, {model_name}): eligible={len(elig)} done={len(ok)} "
335
+ f"permanently_failed={len(perm_fail)} remaining={len(todo)}; shard {tid}/{n} -> {len(mine)} unit(s), "
336
+ f"{n_mine} items (max shard load {max(loads) if loads else 0:.0f}); {'; '.join(notes)}", f"step{step}")
337
+ if a.plan_only:
338
+ print(f"REMAINING_TOTAL={len(todo)} REMAINING_SHARD={n_mine} UNITS={len(mine)}")
339
+ return
340
+ if not mine:
341
+ log("nothing to do", f"step{step}")
342
+ print("INCOMPLETE=0")
343
+ return
344
+ if not a.endpoint:
345
+ sys.exit("--endpoint required")
346
+ runner = Runner(step, a.endpoint.rstrip("/"), model_name, workers)
347
+ rows_by_id = {r["item_id"]: r for r in todo.to_dict("records")}
348
+ deadline = (t_start + a.max_minutes * 60) if a.max_minutes else None
349
+ left_total = 0
350
+ for u in mine:
351
+ if deadline and time.time() > deadline:
352
+ left_total += len(u[3])
353
+ continue
354
+ n_done, left = run_unit(runner, u, rows_by_id, workers, deadline)
355
+ left_total += left
356
+ log(f"{u[0]}.p{u[1]}: done {n_done}, left {left}", f"step{step}")
357
+ st = runner.stats
358
+ wall = time.time() - t_start
359
+ summary = dict(ts=time.strftime("%F %T"), stage=f"step{step}", shard=f"{tid}/{n}", model=model_name,
360
+ items=st["items"], forwards=st["forwards"], errors=st["errors"], removed=st["removed"],
361
+ wall_s=round(wall, 1), mean_fwd_latency_s=round(st["latency_s"] / max(st["forwards"], 1), 4),
362
+ fwd_per_s=round(st["forwards"] / max(wall, 1e-9), 3),
363
+ items_per_s=round(st["items"] / max(wall, 1e-9), 3),
364
+ mean_prompt_tokens=round(st["prompt_tokens"] / max(st["forwards"], 1), 1),
365
+ missing_letter_forwards=st["missing_letter_forwards"], decode_s=round(st["decode_s"], 1),
366
+ workers=workers, token_variants=dict(sorted(runner.variants.items(), key=lambda kv: -kv[1])[:8]),
367
+ left=left_total, slurm_job=os.environ.get("SLURM_JOB_ID"))
368
+ with open(os.path.join(pc.LOG_DIR, "pool_timing.jsonl"), "a") as f:
369
+ f.write(json.dumps(summary) + "\n")
370
+ log(json.dumps(summary), f"step{step}")
371
+ print(f"INCOMPLETE={left_total}")
372
+
373
+
374
+ if __name__ == "__main__":
375
+ main()
supplement_20260910/code/exp/analysis/pool/step1_blind.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """TASK.md step 1 (blind) — thin wrapper: pool_steps.py --step 1 (see that module for the
3
+ rule, the log-prob extraction and the output row format). Output: exp/results/pool/step1/."""
4
+ import os
5
+ import sys
6
+
7
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
8
+ from pool_steps import main # noqa: E402
9
+
10
+ if __name__ == "__main__":
11
+ sys.argv = [sys.argv[0], "--step", "1"] + [x for x in sys.argv[1:] if x not in ("--step", "1")]
12
+ main()
supplement_20260910/code/exp/analysis/pool/step2_single_frame.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """TASK.md step 2 (single_frame) — thin wrapper: pool_steps.py --step 2 (see that module for the
3
+ rule, the log-prob extraction and the output row format). Output: exp/results/pool/step2/."""
4
+ import os
5
+ import sys
6
+
7
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
8
+ from pool_steps import main # noqa: E402
9
+
10
+ if __name__ == "__main__":
11
+ sys.argv = [sys.argv[0], "--step", "2"] + [x for x in sys.argv[1:] if x not in ("--step", "2")]
12
+ main()
supplement_20260910/code/exp/analysis/pool/step3_v32_2b.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """TASK.md step 3 (v32_2b) — thin wrapper: pool_steps.py --step 3 (see that module for the
3
+ rule, the log-prob extraction and the output row format). Output: exp/results/pool/step3/."""
4
+ import os
5
+ import sys
6
+
7
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
8
+ from pool_steps import main # noqa: E402
9
+
10
+ if __name__ == "__main__":
11
+ sys.argv = [sys.argv[0], "--step", "3"] + [x for x in sys.argv[1:] if x not in ("--step", "3")]
12
+ main()
supplement_20260910/code/requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # versions used on the origin cluster (Python 3.12.14); vLLM wheels for CUDA 12.8 (Blackwell B200 / RTX 5090 need torch 2.8 cu128)
2
+ vllm==0.11.0
3
+ torch==2.8.0
4
+ transformers==4.57.6
5
+ pyarrow>=17
6
+ pandas>=2.2
7
+ requests>=2.32
8
+ pillow>=10
9
+ huggingface_hub>=0.34
supplement_20260910/code/run_remote.sh ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # run_remote.sh — run one pool screening step on a multi-GPU machine (no Slurm).
3
+ # STEP=1 bash code/run_remote.sh # run step 1 on every GPU (one vLLM server + one client shard per GPU)
4
+ # STEP=2 bash code/run_remote.sh --plan-only # show the remaining work of a step, no GPU used
5
+ # Env (optional): NGPU (default: nvidia-smi count), WORKERS (client threads per GPU; defaults per step),
6
+ # VLLM (default: vllm on PATH), PY (default: python3), PORT0 (default 8001), GPU_UTIL (default 0.85)
7
+ # Layout: this script lives in <package>/code/; items are read from <package>/results/pool/ (copy items/* there
8
+ # once), frames from <package>/frames/pool_frames/<video_id>/, outputs go to <package>/results/pool/step<N>/.
9
+ set -u
10
+ CODE=$(cd "$(dirname "$0")" && pwd); ROOT=$(cd "$CODE/.." && pwd)
11
+ export POOL_BASE=${POOL_BASE:-$ROOT/work_base}
12
+ export POOL_FRAMES_DIR=${POOL_FRAMES_DIR:-$ROOT/frames/pool_frames}
13
+ export POOL_RESULTS_ROOT=${POOL_RESULTS_ROOT:-$ROOT/results/pool}
14
+ mkdir -p "$POOL_BASE" "$POOL_RESULTS_ROOT" "$ROOT/logs"
15
+ PY=${PY:-python3}; VLLM=${VLLM:-vllm}; PORT0=${PORT0:-8001}; GPU_UTIL=${GPU_UTIL:-0.85}
16
+ STEPS_PY="$CODE/exp/analysis/pool/pool_steps.py"
17
+ STEP=${STEP:?set STEP=1..6}
18
+ case "$STEP" in
19
+ 1) MODEL="Qwen/Qwen3-VL-8B-Instruct"; REV=0c351dd01ed87e9c1b53cbc748cba10e6187ff3b; MAX_LEN=8192; MAX_SEQS=64; MM_IMAGES=1; WORKERS=${WORKERS:-32};;
20
+ 2) MODEL="Qwen/Qwen3-VL-8B-Instruct"; REV=0c351dd01ed87e9c1b53cbc748cba10e6187ff3b; MAX_LEN=8192; MAX_SEQS=32; MM_IMAGES=1; WORKERS=${WORKERS:-16};;
21
+ 3) MODEL="Qwen/Qwen3-VL-2B-Instruct"; REV=89644892e4d85e24eaac8bacfd4f463576704203; MAX_LEN=16384; MAX_SEQS=16; MM_IMAGES=32; WORKERS=${WORKERS:-8};;
22
+ 4) MODEL="Qwen/Qwen3-VL-8B-Instruct"; REV=0c351dd01ed87e9c1b53cbc748cba10e6187ff3b; MAX_LEN=8192; MAX_SEQS=64; MM_IMAGES=1; WORKERS=${WORKERS:-32};;
23
+ 5) MODEL="Qwen/Qwen3-VL-2B-Instruct"; REV=89644892e4d85e24eaac8bacfd4f463576704203; MAX_LEN=16384; MAX_SEQS=16; MM_IMAGES=32; WORKERS=${WORKERS:-8};;
24
+ 6) MODEL="Qwen/Qwen3-VL-8B-Instruct"; REV=0c351dd01ed87e9c1b53cbc748cba10e6187ff3b; MAX_LEN=16384; MAX_SEQS=16; MM_IMAGES=32; WORKERS=${WORKERS:-8};;
25
+ *) echo "STEP must be 1..6"; exit 2;;
26
+ esac
27
+ [ ! -e "$POOL_RESULTS_ROOT/pool_items_base.parquet" ] && { echo "copy items/* into $POOL_RESULTS_ROOT first"; exit 2; }
28
+ if [ "${1:-}" = "--plan-only" ]; then "$PY" "$STEPS_PY" --step "$STEP" --plan-only --shard 0/1; exit $?; fi
29
+ NGPU=${NGPU:-$(nvidia-smi -L 2>/dev/null | wc -l)}
30
+ [ "$NGPU" -ge 1 ] || { echo "no GPU found"; exit 2; }
31
+ export VLLM_USE_FLASHINFER_SAMPLER=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True TOKENIZERS_PARALLELISM=false
32
+ PIDS=(); EPS=()
33
+ for i in $(seq 0 $((NGPU - 1))); do
34
+ PORT=$((PORT0 + i)); EPS+=("http://127.0.0.1:$PORT/v1")
35
+ CUDA_VISIBLE_DEVICES=$i "$VLLM" serve "$MODEL" --revision "$REV" --served-model-name "$MODEL" --host 127.0.0.1 --port "$PORT" \
36
+ --max-model-len "$MAX_LEN" --gpu-memory-utilization "$GPU_UTIL" --max-num-seqs "$MAX_SEQS" \
37
+ --limit-mm-per-prompt "{\"image\": $MM_IMAGES}" --mm-processor-cache-gb 0 --max-logprobs 20 \
38
+ > "$ROOT/logs/vllm_s${STEP}_gpu${i}.log" 2>&1 &
39
+ PIDS+=($!)
40
+ done
41
+ trap 'for p in "${PIDS[@]}"; do kill "$p" 2>/dev/null; done' EXIT
42
+ for i in $(seq 0 $((NGPU - 1))); do
43
+ for t in $(seq 1 180); do curl -sf "${EPS[$i]}/models" >/dev/null 2>&1 && break; kill -0 "${PIDS[$i]}" 2>/dev/null || { echo "vLLM on GPU $i died, see logs/vllm_s${STEP}_gpu${i}.log"; exit 1; }; sleep 10; done
44
+ echo "[run_remote] step $STEP: vLLM ready on GPU $i (${EPS[$i]})"
45
+ done
46
+ CPIDS=()
47
+ for i in $(seq 0 $((NGPU - 1))); do
48
+ "$PY" "$STEPS_PY" --step "$STEP" --endpoint "${EPS[$i]}" --shard "$i/$NGPU" --workers "$WORKERS" \
49
+ > "$ROOT/logs/client_s${STEP}_gpu${i}.log" 2>&1 &
50
+ CPIDS+=($!)
51
+ done
52
+ rc=0; for p in "${CPIDS[@]}"; do wait "$p" || rc=1; done
53
+ echo "[run_remote] step $STEP finished rc=$rc; remaining:"; "$PY" "$STEPS_PY" --step "$STEP" --plan-only --shard 0/1 | tail -1
54
+ exit $rc