AntonioJun commited on
Commit
27c1789
·
verified ·
1 Parent(s): 2f5ffdf

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. harness/A/__init__.py +54 -0
  2. harness/A/__pycache__/__init__.cpython-311.pyc +0 -0
  3. harness/A/__pycache__/frames.cpython-311.pyc +0 -0
  4. harness/A/__pycache__/launch.cpython-311.pyc +0 -0
  5. harness/A/__pycache__/models.cpython-311.pyc +0 -0
  6. harness/A/__pycache__/prompts.cpython-311.pyc +0 -0
  7. harness/A/__pycache__/run.cpython-311.pyc +0 -0
  8. harness/A/__pycache__/sweep.cpython-311.pyc +0 -0
  9. harness/A/frames.py +54 -0
  10. harness/A/launch.py +224 -0
  11. harness/A/models.py +343 -0
  12. harness/A/prompts.py +47 -0
  13. harness/A/run.py +339 -0
  14. harness/A/sweep.py +127 -0
  15. harness/B/__init__.py +42 -0
  16. harness/B/__pycache__/__init__.cpython-311.pyc +0 -0
  17. harness/B/__pycache__/launch.cpython-311.pyc +0 -0
  18. harness/B/__pycache__/prompts.cpython-311.pyc +0 -0
  19. harness/B/__pycache__/run.cpython-311.pyc +0 -0
  20. harness/B/__pycache__/spatial_codes.cpython-311.pyc +0 -0
  21. harness/B/__pycache__/sweep.cpython-311.pyc +0 -0
  22. harness/B/launch.py +218 -0
  23. harness/B/prompts.py +55 -0
  24. harness/B/run.py +281 -0
  25. harness/B/spatial_codes.py +31 -0
  26. harness/B/sweep.py +139 -0
  27. harness/C/__pycache__/__init__.cpython-311.pyc +0 -0
  28. harness/C/__pycache__/launch.cpython-311.pyc +0 -0
  29. harness/C/__pycache__/prompts.cpython-311.pyc +0 -0
  30. harness/C/__pycache__/run.cpython-311.pyc +0 -0
  31. harness/C/__pycache__/sweep.cpython-311.pyc +0 -0
  32. harness/C/launch.py +221 -0
  33. harness/C/prompts.py +48 -0
  34. harness/D/__pycache__/launch.cpython-311.pyc +0 -0
  35. harness/D/__pycache__/prompts.cpython-311.pyc +0 -0
  36. harness/D/__pycache__/run.cpython-311.pyc +0 -0
  37. harness/D/__pycache__/spatial_codes.cpython-311.pyc +0 -0
  38. harness/D/__pycache__/symbolic_eval.cpython-311.pyc +0 -0
  39. harness/__pycache__/__init__.cpython-311.pyc +0 -0
  40. tests/test_B/__init__.py +0 -0
  41. tests/test_B/__pycache__/test_launch.cpython-311-pytest-8.3.5.pyc +0 -0
  42. tests/test_B/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc +0 -0
  43. tests/test_B/__pycache__/test_spatial_codes.cpython-311-pytest-8.3.5.pyc +0 -0
  44. tests/test_B/conftest.py +12 -0
  45. tests/test_B/test_init.py +33 -0
  46. tests/test_B/test_launch.py +49 -0
  47. tests/test_B/test_sweep.py +55 -0
  48. tests/test_C/__init__.py +0 -0
  49. tests/test_C/__pycache__/__init__.cpython-311.pyc +0 -0
  50. tests/test_C/__pycache__/conftest.cpython-311-pytest-8.3.5.pyc +0 -0
harness/A/__init__.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Harness A: uniform/selective frame sampling + direct VLM inference calls.
2
+
3
+ Mirrors the frame-selection vocabulary already used by ``inference`` (uniform vs.
4
+ selective) and the exact generation protocol VSI-Bench's own harness
5
+ (``thinking-in-space/lmms_eval/tasks/vsibench/vsibench.yaml``) evaluates every model
6
+ under: greedy decoding (``do_sample=False``, temperature 0) and a hard 16-token output
7
+ cap. Model weights live under ``MODELS_ROOT`` next to the other model checkpoints
8
+ (``depth-anything-3``, ``sam3``) this workspace already downloads there.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ from pathlib import Path
15
+
16
+ DATA_ROOT = Path(os.environ.get("VSI_DATA_ROOT", "/root/data"))
17
+ MODELS_ROOT = Path(os.environ.get("VSI_MODELS_ROOT", "/root/models"))
18
+ VSI_ROOT = Path(os.environ.get("VSI_ROOT", DATA_ROOT / "VSI-Bench"))
19
+ JSONL = Path(os.environ.get("VSI_JSONL", VSI_ROOT / "test.jsonl"))
20
+ WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent
21
+ # One JSON per question, matching the layout results/symbolic/... already uses:
22
+ # results/A/<model>/<frame_selection>/<frame_count>/<scene>/<question_id>.json
23
+ RESULTS_DIR = Path(
24
+ os.environ.get("VSI_HARNESS_RESULTS_DIR", WORKSPACE_ROOT / "results" / "A")
25
+ )
26
+
27
+ # Same two selection strategies and vocabulary as inference.SAM3_FRAME_SELECTIONS:
28
+ # "uniform" (evenly spaced indices) or "selective" (the quality/redundancy/motion-
29
+ # filtered keyframe selector in inference.adapters, algorithm 5 by default).
30
+ FRAME_SELECTIONS = ("uniform", "selective")
31
+ DEFAULT_FRAME_SELECTION = "uniform"
32
+ FRAMES_PER_VIDEO = int(os.environ.get("VSI_HARNESS_FRAMES_PER_VIDEO", "32"))
33
+
34
+ # Fixed by the VSI-Bench protocol (vsibench.yaml generation_kwargs) -- not configurable
35
+ # per call, since comparing models under different decoding settings would be meaningless.
36
+ MAX_NEW_TOKENS = 16
37
+ TEMPERATURE = 0.0
38
+ DO_SAMPLE = False
39
+
40
+ # Extended-budget generation (VLMAdapter.answer_extended, harness.B/C's default protocol
41
+ # and harness.A's opt-in --extended flag): a much larger first-pass budget for the model
42
+ # to work through the input before answering, with a short forced second call only if it
43
+ # didn't conclude (hit the budget without emitting an end-of-sequence token) in that
44
+ # first pass. The forced call reuses MAX_NEW_TOKENS (16) -- the same short-answer budget
45
+ # the base protocol already uses -- since its whole job is to extract one terse answer,
46
+ # not to reason further.
47
+ EXTENDED_MAX_NEW_TOKENS = 2048
48
+ FORCE_ANSWER_PROMPT = "\nFinal answer:"
49
+
50
+ MODEL_PATHS = {
51
+ "qwen3.5-4b": MODELS_ROOT / "qwen3.5-4b",
52
+ "qwen3.5-2b": MODELS_ROOT / "qwen3.5-2b",
53
+ "internvl3.5-4b": MODELS_ROOT / "internvl3.5-4b",
54
+ }
harness/A/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (2.36 kB). View file
 
harness/A/__pycache__/frames.cpython-311.pyc ADDED
Binary file (3.67 kB). View file
 
harness/A/__pycache__/launch.cpython-311.pyc ADDED
Binary file (13.3 kB). View file
 
harness/A/__pycache__/models.cpython-311.pyc ADDED
Binary file (18 kB). View file
 
harness/A/__pycache__/prompts.cpython-311.pyc ADDED
Binary file (2.06 kB). View file
 
harness/A/__pycache__/run.cpython-311.pyc ADDED
Binary file (16.8 kB). View file
 
harness/A/__pycache__/sweep.cpython-311.pyc ADDED
Binary file (8.65 kB). View file
 
harness/A/frames.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Uniform / selective frame sampling for direct VLM calls.
2
+
3
+ Reuses ``inference.adapters._sample_video_frames`` -- the exact same decoder every
4
+ other model adapter in this workspace (DA3, SAM3, SegVGGT) already samples through --
5
+ so "uniform" and "selective" behave identically here and there, and the selective
6
+ (smart) keyframe indices share that module's on-disk cache instead of being recomputed.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+
13
+ import cv2
14
+ from PIL import Image
15
+
16
+ from harness.A import FRAME_SELECTIONS
17
+ from inference.adapters import _sample_video_frames
18
+
19
+
20
+ def sample_frames(video_path, frame_count, frame_selection):
21
+ """Return (``frame_count`` RGB frames as PIL images, their video timestamps in
22
+ seconds, their raw integer frame indices).
23
+
24
+ ``frame_selection="uniform"`` takes evenly spaced indices across the whole video.
25
+ ``frame_selection="selective"`` (the "smart" mode) takes the quality/redundancy/
26
+ motion-filtered keyframe indices from ``inference.adapters.select_video_frame_indices``,
27
+ downsampled to ``frame_count`` if the selector kept more frames than requested.
28
+ Both timestamps and indices are returned (not discarded) so callers can log exactly
29
+ which frames of the source video were fed to a model, for full-provenance result
30
+ records -- indices are exact (unlike timestamps, which lose precision through the
31
+ index/fps conversion _sample_video_frames itself performs).
32
+ """
33
+ if frame_selection not in FRAME_SELECTIONS:
34
+ raise ValueError(
35
+ f"unknown frame selection {frame_selection!r}; expected one of {FRAME_SELECTIONS}"
36
+ )
37
+ if frame_count < 1:
38
+ raise ValueError("frame_count must be positive")
39
+ if not Path(video_path).is_file():
40
+ raise FileNotFoundError(f"video not found: {video_path}")
41
+ frames, times = _sample_video_frames(video_path, frame_count, frame_selection)
42
+ capture = cv2.VideoCapture(video_path)
43
+ try:
44
+ fps = capture.get(cv2.CAP_PROP_FPS) or 1.0
45
+ finally:
46
+ capture.release()
47
+ # Inverse of the exact index/fps conversion _sample_video_frames applies, so this
48
+ # recovers the original integer indices without redoing frame selection.
49
+ indices = [int(round(float(t) * fps)) for t in times]
50
+ return (
51
+ [Image.fromarray(frame) for frame in frames],
52
+ [float(t) for t in times],
53
+ indices,
54
+ )
harness/A/launch.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Keep every visible GPU busy with persistent harness-A inference workers.
2
+
3
+ Same shape as ``inference/launch.py``: one persistent worker process per visible GPU,
4
+ pulling scenes off a shared queue, each loading its model exactly once and reusing it
5
+ for every scene it's assigned (via ``run.run(..., adapter=...)``) instead of paying the
6
+ load cost per scene. One invocation covers one (model, frame_selection, frame_count)
7
+ triple across every requested scene; sweep multiple triples by invoking this once per
8
+ triple (a shell loop), exactly how ``inference/launch.py`` is invoked once per mode.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import importlib.util
15
+ import json
16
+ import multiprocessing as mp
17
+ import os
18
+ from pathlib import Path
19
+ import sys
20
+ import traceback
21
+
22
+ HERE = Path(__file__).resolve().parent
23
+ WORKSPACE_ROOT = HERE.parent.parent
24
+ if str(WORKSPACE_ROOT) not in sys.path:
25
+ sys.path.insert(0, str(WORKSPACE_ROOT))
26
+
27
+ from harness.A import ( # noqa: E402
28
+ DEFAULT_FRAME_SELECTION,
29
+ EXTENDED_MAX_NEW_TOKENS,
30
+ FRAME_SELECTIONS,
31
+ FRAMES_PER_VIDEO,
32
+ JSONL,
33
+ MAX_NEW_TOKENS,
34
+ )
35
+ from harness.A import models as vlm_models # noqa: E402
36
+ from inference.launch import available_cpu_count, visible_gpus # noqa: E402
37
+
38
+
39
+ def _load_run_module():
40
+ spec = importlib.util.spec_from_file_location("_harness_A_run", HERE / "run.py")
41
+ module = importlib.util.module_from_spec(spec)
42
+ sys.modules[spec.name] = module
43
+ spec.loader.exec_module(module)
44
+ return module
45
+
46
+
47
+ def scenes():
48
+ """Return unique VSI-Bench scenes in their original manifest order."""
49
+ with open(JSONL) as manifest:
50
+ return list(dict.fromkeys(str(json.loads(line)["scene_name"]) for line in manifest))
51
+
52
+
53
+ def _worker(
54
+ tasks, results, model, frame_selection, frame_count, results_dir, gpu, cpu_threads,
55
+ extended, reasoning_budget, force_budget,
56
+ ):
57
+ if gpu is not None:
58
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
59
+ for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
60
+ os.environ[variable] = str(cpu_threads)
61
+ import cv2
62
+
63
+ cv2.setNumThreads(cpu_threads)
64
+ run = _load_run_module()
65
+ adapter = None
66
+ load_error = None
67
+ try:
68
+ adapter = vlm_models.get_adapter(model)
69
+ adapter.load_model("cuda:0" if gpu is not None else "cpu")
70
+ except Exception:
71
+ load_error = traceback.format_exc()
72
+ while True:
73
+ scene = tasks.get()
74
+ if scene is None:
75
+ return
76
+ if load_error is not None:
77
+ results.put((scene, False, load_error))
78
+ continue
79
+ try:
80
+ answered = run.run(
81
+ model,
82
+ frame_selection=frame_selection,
83
+ frame_count=frame_count,
84
+ scene=scene,
85
+ results_dir=results_dir,
86
+ adapter=adapter,
87
+ extended=extended,
88
+ reasoning_budget=reasoning_budget,
89
+ force_budget=force_budget,
90
+ )
91
+ mean_score = (
92
+ sum(r["score"] for r in answered) / len(answered) if answered else None
93
+ )
94
+ results.put(
95
+ (scene, True, f"{len(answered)} question(s), mean_score={mean_score}")
96
+ )
97
+ except Exception:
98
+ results.put((scene, False, traceback.format_exc()))
99
+
100
+
101
+ def launch(
102
+ model, frame_selection, frame_count, selected, results_dir=None, rebuild=False,
103
+ extended=False, reasoning_budget=EXTENDED_MAX_NEW_TOKENS, force_budget=MAX_NEW_TOKENS,
104
+ ):
105
+ """Answer every question for ``selected`` scenes, sharded across every visible GPU."""
106
+ condition = f"{model}/{frame_selection}/{frame_count}"
107
+ run = _load_run_module()
108
+ root = run.results_dir_for(model, frame_selection, frame_count, results_dir)
109
+ pending = []
110
+ completed = 0
111
+ for scene in selected:
112
+ rows = run.load_questions(scene=scene)
113
+ answered = all(
114
+ (root / scene / f"{row['id']}.json").is_file() for row in rows
115
+ )
116
+ if answered and not rebuild:
117
+ completed += 1
118
+ print(f"[{condition} {completed}/{len(selected)}] {scene}: skipped", flush=True)
119
+ else:
120
+ pending.append(scene)
121
+ if not pending:
122
+ print(f"[{condition}] DONE: {len(selected)} ok, 0 failed")
123
+ return
124
+
125
+ gpus = visible_gpus()
126
+ worker_count = min(len(pending), len(gpus) if gpus else 1)
127
+ assignments = gpus[:worker_count] if gpus else [None]
128
+ cpu_count = available_cpu_count()
129
+ cpu_threads = max(1, cpu_count // worker_count)
130
+ print(
131
+ f"[{condition}] starting {worker_count} persistent worker(s); "
132
+ f"GPUs={assignments}; CPU threads/worker={cpu_threads}",
133
+ flush=True,
134
+ )
135
+
136
+ context = mp.get_context("spawn")
137
+ tasks, results = context.Queue(), context.Queue()
138
+ for scene in pending:
139
+ tasks.put(scene)
140
+ for _ in range(worker_count):
141
+ tasks.put(None)
142
+ workers = [
143
+ context.Process(
144
+ target=_worker,
145
+ args=(
146
+ tasks, results, model, frame_selection, frame_count, results_dir,
147
+ gpu, cpu_threads, extended, reasoning_budget, force_budget,
148
+ ),
149
+ )
150
+ for gpu in assignments
151
+ ]
152
+ for worker in workers:
153
+ worker.start()
154
+ failed = []
155
+ for finished in range(1, len(pending) + 1):
156
+ scene, ok, detail = results.get()
157
+ if not ok:
158
+ failed.append(scene)
159
+ print(
160
+ f"[{condition} {completed + finished}/{len(selected)}] {scene}: "
161
+ f"{'done' if ok else 'FAILED'}\n{detail}",
162
+ flush=True,
163
+ )
164
+ for worker in workers:
165
+ worker.join()
166
+ print(
167
+ f"[{condition}] DONE: {len(pending) - len(failed)} answered, {completed} skipped, "
168
+ f"{len(failed)} failed"
169
+ )
170
+ if failed:
171
+ raise SystemExit(1)
172
+
173
+
174
+ def main():
175
+ parser = argparse.ArgumentParser()
176
+ parser.add_argument("scene", nargs="?")
177
+ parser.add_argument(
178
+ "--scenes", help="comma-separated scenes (cannot be combined with positional scene)"
179
+ )
180
+ parser.add_argument("--model", required=True, choices=vlm_models.available_models())
181
+ parser.add_argument(
182
+ "--frame-selection", default=DEFAULT_FRAME_SELECTION, choices=FRAME_SELECTIONS,
183
+ dest="frame_selection",
184
+ )
185
+ parser.add_argument("--frames", type=int, default=FRAMES_PER_VIDEO)
186
+ parser.add_argument("--results-dir", default=None)
187
+ parser.add_argument("--rebuild", action="store_true")
188
+ parser.add_argument(
189
+ "--extended",
190
+ action="store_true",
191
+ help=(
192
+ f"use a {EXTENDED_MAX_NEW_TOKENS}-token reasoning budget instead of the fixed "
193
+ f"{MAX_NEW_TOKENS}-token VSI-Bench protocol, with a short forced second call "
194
+ "only if the model doesn't conclude within it"
195
+ ),
196
+ )
197
+ parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
198
+ parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
199
+ args = parser.parse_args()
200
+ if args.scene and args.scenes:
201
+ parser.error("positional scene and --scenes cannot be used together")
202
+ if args.scenes is not None:
203
+ selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
204
+ if not selected:
205
+ parser.error("--scenes must contain at least one scene")
206
+ selected = list(dict.fromkeys(selected))
207
+ else:
208
+ selected = [args.scene] if args.scene else scenes()
209
+ if args.frames < 1:
210
+ parser.error("--frames must be positive")
211
+ if args.reasoning_budget < 1:
212
+ parser.error("--reasoning-budget must be positive")
213
+ if args.force_budget < 1:
214
+ parser.error("--force-budget must be positive")
215
+ launch(
216
+ args.model, args.frame_selection, args.frames, selected,
217
+ results_dir=args.results_dir, rebuild=args.rebuild,
218
+ extended=args.extended, reasoning_budget=args.reasoning_budget,
219
+ force_budget=args.force_budget,
220
+ )
221
+
222
+
223
+ if __name__ == "__main__":
224
+ main()
harness/A/models.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model adapters: load one VLM, answer one (frames, prompt) pair, greedy-decoded.
2
+
3
+ Same ``load_model`` / one-call-per-question shape as ``inference.adapters.InferenceAdapter``,
4
+ but returning generated text instead of preserving a native raw-feature cache. Every
5
+ adapter is forced to the fixed VSI-Bench decoding protocol from ``harness.A``
6
+ (``do_sample=False``, 16 new tokens) -- callers cannot override it, since comparing
7
+ models under different decoding settings defeats the point of a shared harness.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from abc import ABC, abstractmethod
13
+ from pathlib import Path
14
+
15
+ from harness.A import (
16
+ DO_SAMPLE,
17
+ EXTENDED_MAX_NEW_TOKENS,
18
+ FORCE_ANSWER_PROMPT,
19
+ MAX_NEW_TOKENS,
20
+ MODEL_PATHS,
21
+ TEMPERATURE,
22
+ )
23
+
24
+
25
+ def _numbered_content(frames, question):
26
+ """Interleave "Frame N:" labels with each image, then the question text.
27
+
28
+ Numbering frames (not just concatenating raw images) is the documented convention
29
+ for multi-image/video prompting with both model families here -- it is the only way
30
+ the model can recover frame ORDER, which several VSI-Bench question types
31
+ (obj_appearance_order, route_planning) directly depend on.
32
+ """
33
+ content = []
34
+ for index, frame in enumerate(frames, start=1):
35
+ content.append({"type": "text", "text": f"Frame {index}:"})
36
+ content.append({"type": "image", "image": frame})
37
+ content.append({"type": "text", "text": question})
38
+ return content
39
+
40
+
41
+ class VLMAdapter(ABC):
42
+ """Common interface implemented by every direct-inference VLM adapter."""
43
+
44
+ def __init__(self, model_path=None):
45
+ self.model_path = Path(model_path)
46
+ self.model = None
47
+ self.processor = None
48
+ self.device = None
49
+ self.dtype = None
50
+
51
+ @abstractmethod
52
+ def load_model(self, device="cuda"):
53
+ """Load model + processor weights once for repeated ``answer`` calls."""
54
+
55
+ @abstractmethod
56
+ def answer(self, frames, question):
57
+ """Return a full, untruncated record of one greedy-decoded response.
58
+
59
+ Every field a downstream result file needs is produced here, not reconstructed
60
+ later: the literal rendered prompt text, both the cleaned and fully raw decoded
61
+ response, the actual generated token ids/count, whether the token budget cut the
62
+ response off before a natural stop, and the exact generation config used.
63
+ """
64
+
65
+ @abstractmethod
66
+ def answer_extended(self, frames, question, reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
67
+ force_budget=MAX_NEW_TOKENS):
68
+ """Same record shape as ``answer``, but with a much larger first-pass budget to
69
+ work through the input before answering. If the model does not conclude within
70
+ that budget (hits it without emitting an end-of-sequence token), a short forced
71
+ second call -- continuing the exact same generation, not a new turn -- asks for
72
+ the final answer directly. Always records the full, untruncated first-pass text
73
+ too (``reasoning_text``), even when a forced second call supplies the answer
74
+ actually used for scoring.
75
+ """
76
+
77
+ def unload(self):
78
+ """Free GPU memory so another adapter can be loaded in its place."""
79
+ import torch
80
+
81
+ self.model = None
82
+ self.processor = None
83
+ torch.cuda.empty_cache()
84
+
85
+
86
+ class _TransformersVLMAdapter(VLMAdapter):
87
+ """Shared load/generate path for HF ``AutoModelForImageTextToText`` checkpoints."""
88
+
89
+ chat_template_kwargs = {}
90
+
91
+ def load_model(self, device="cuda"):
92
+ import torch
93
+ from transformers import AutoModelForImageTextToText, AutoProcessor
94
+
95
+ if not self.model_path.is_dir():
96
+ raise FileNotFoundError(f"model not found: {self.model_path}")
97
+ self.device = device
98
+ self.dtype = torch.bfloat16
99
+ self.processor = AutoProcessor.from_pretrained(
100
+ str(self.model_path), trust_remote_code=True
101
+ )
102
+ self.model = (
103
+ AutoModelForImageTextToText.from_pretrained(
104
+ str(self.model_path), dtype=self.dtype, trust_remote_code=True
105
+ )
106
+ .eval()
107
+ .to(device)
108
+ )
109
+
110
+ def _build_inputs(self, frames, question):
111
+ """Render one chat turn to both plain text and tokenized model inputs."""
112
+ messages = [{"role": "user", "content": _numbered_content(frames, question)}]
113
+ prompt_text = self.processor.apply_chat_template(
114
+ messages, add_generation_prompt=True, tokenize=False, **self.chat_template_kwargs,
115
+ )
116
+ inputs = self.processor.apply_chat_template(
117
+ messages, add_generation_prompt=True, tokenize=True,
118
+ return_dict=True, return_tensors="pt", **self.chat_template_kwargs,
119
+ ).to(self.device)
120
+ # Shapes of every non-text processor output (pixel_values, image_grid_thw, ...) --
121
+ # generic across model families instead of hunting each one's own vision placeholder
122
+ # token id, and still shows exactly how much visual input the model actually received.
123
+ vision_input_shapes = {
124
+ key: list(value.shape)
125
+ for key, value in inputs.items()
126
+ if key not in ("input_ids", "attention_mask") and hasattr(value, "shape")
127
+ }
128
+ return prompt_text, inputs, vision_input_shapes
129
+
130
+ def _eos_ids(self):
131
+ eos_ids = self.model.generation_config.eos_token_id
132
+ if eos_ids is None:
133
+ eos_ids = self.processor.tokenizer.eos_token_id
134
+ return [eos_ids] if isinstance(eos_ids, int) else list(eos_ids or [])
135
+
136
+ def _generate(self, inputs, max_new_tokens):
137
+ """Run one greedy generate() call. Returns (full sequence, elapsed seconds)."""
138
+ import time
139
+
140
+ import torch
141
+
142
+ start = time.monotonic()
143
+ with torch.no_grad():
144
+ generated = self.model.generate(
145
+ **inputs, max_new_tokens=max_new_tokens, do_sample=DO_SAMPLE,
146
+ temperature=None, top_p=None, top_k=None,
147
+ )
148
+ if self.device.startswith("cuda"):
149
+ torch.cuda.synchronize()
150
+ return generated, time.monotonic() - start
151
+
152
+ def _decode_new_tokens(self, generated, input_token_count, max_new_tokens, eos_ids):
153
+ """Split one generate() output into new-token ids + decoded text + hit-limit flag."""
154
+ output_token_ids = generated[0][input_token_count:].tolist()
155
+ hit_token_limit = (
156
+ len(output_token_ids) >= max_new_tokens
157
+ and (not output_token_ids or output_token_ids[-1] not in eos_ids)
158
+ )
159
+ answer_text = self.processor.decode(output_token_ids, skip_special_tokens=True).strip()
160
+ answer_raw = self.processor.decode(output_token_ids, skip_special_tokens=False)
161
+ return output_token_ids, hit_token_limit, answer_text, answer_raw
162
+
163
+ def _library_versions(self):
164
+ import torch
165
+ import transformers
166
+
167
+ return {"transformers": transformers.__version__, "torch": torch.__version__}
168
+
169
+ def answer(self, frames, question):
170
+ if self.model is None or self.processor is None:
171
+ raise RuntimeError("load_model() must be called before answer()")
172
+ prompt_text, inputs, vision_input_shapes = self._build_inputs(frames, question)
173
+ input_token_count = int(inputs["input_ids"].shape[1])
174
+ generated, generation_seconds = self._generate(inputs, MAX_NEW_TOKENS)
175
+ eos_ids = self._eos_ids()
176
+ output_token_ids, hit_token_limit, answer_text, answer_raw = self._decode_new_tokens(
177
+ generated, input_token_count, MAX_NEW_TOKENS, eos_ids
178
+ )
179
+
180
+ return {
181
+ "prompt_text": prompt_text,
182
+ "answer_text": answer_text,
183
+ "answer_raw": answer_raw,
184
+ "input_token_count": input_token_count,
185
+ "vision_input_shapes": vision_input_shapes,
186
+ "output_token_ids": output_token_ids,
187
+ "output_token_count": len(output_token_ids),
188
+ "hit_token_limit": hit_token_limit,
189
+ "eos_token_ids": eos_ids,
190
+ "generation_seconds": generation_seconds,
191
+ "device": self.device,
192
+ "dtype": str(self.dtype).removeprefix("torch."),
193
+ "library_versions": self._library_versions(),
194
+ "generation_config": {
195
+ "max_new_tokens": MAX_NEW_TOKENS,
196
+ "do_sample": DO_SAMPLE,
197
+ "temperature": TEMPERATURE,
198
+ "top_p": None,
199
+ "top_k": None,
200
+ **self.chat_template_kwargs,
201
+ },
202
+ }
203
+
204
+ def answer_extended(self, frames, question, reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
205
+ force_budget=MAX_NEW_TOKENS):
206
+ import torch
207
+
208
+ if self.model is None or self.processor is None:
209
+ raise RuntimeError("load_model() must be called before answer_extended()")
210
+ prompt_text, inputs, vision_input_shapes = self._build_inputs(frames, question)
211
+ input_token_count = int(inputs["input_ids"].shape[1])
212
+ eos_ids = self._eos_ids()
213
+
214
+ generated, reasoning_seconds = self._generate(inputs, reasoning_budget)
215
+ reasoning_token_ids, reasoning_hit_limit, reasoning_text, reasoning_raw = (
216
+ self._decode_new_tokens(generated, input_token_count, reasoning_budget, eos_ids)
217
+ )
218
+
219
+ forced = reasoning_hit_limit
220
+ generation_seconds = reasoning_seconds
221
+ if forced:
222
+ # Continue the SAME generation (not a new chat turn): the model's own partial
223
+ # response, plus an explicit instruction to answer now, then a short second
224
+ # budget to extract that answer. Multimodal tensors (pixel_values, etc.) must
225
+ # be resupplied -- the continued sequence still contains the original image
226
+ # placeholder tokens, and generate() recomputes their embeddings from scratch.
227
+ force_prompt_ids = self.processor.tokenizer(
228
+ FORCE_ANSWER_PROMPT, return_tensors="pt", add_special_tokens=False
229
+ )["input_ids"].to(self.device)
230
+ continued_ids = torch.cat([generated, force_prompt_ids], dim=1)
231
+ continued_mask = torch.ones_like(continued_ids)
232
+ added_length = int(continued_ids.shape[1]) - input_token_count
233
+ continued_inputs = {}
234
+ for key, value in inputs.items():
235
+ if key in ("input_ids", "attention_mask"):
236
+ continue
237
+ # Per-token multimodal metadata (e.g. Qwen's mm_token_type_ids) is sized to
238
+ # the ORIGINAL prompt length and must grow with it; every newly generated
239
+ # token (reasoning + the force prompt) is plain text, never an image
240
+ # placeholder, so pad with zeros. Per-patch tensors (pixel_values,
241
+ # image_grid_thw, ...) don't depend on sequence length at all and pass
242
+ # through unchanged -- this check is what tells the two apart.
243
+ if hasattr(value, "shape") and value.dim() >= 2 and value.shape[1] == input_token_count:
244
+ pad = value.new_zeros((value.shape[0], added_length) + tuple(value.shape[2:]))
245
+ value = torch.cat([value, pad], dim=1)
246
+ continued_inputs[key] = value
247
+ continued_inputs["input_ids"] = continued_ids
248
+ continued_inputs["attention_mask"] = continued_mask
249
+ forced_input_token_count = int(continued_ids.shape[1])
250
+
251
+ forced_generated, forced_seconds = self._generate(continued_inputs, force_budget)
252
+ output_token_ids, hit_token_limit, answer_text, answer_raw = self._decode_new_tokens(
253
+ forced_generated, forced_input_token_count, force_budget, eos_ids
254
+ )
255
+ generation_seconds += forced_seconds
256
+ else:
257
+ forced_input_token_count = None
258
+ output_token_ids, hit_token_limit = reasoning_token_ids, reasoning_hit_limit
259
+ answer_text, answer_raw = reasoning_text, reasoning_raw
260
+
261
+ return {
262
+ "prompt_text": prompt_text,
263
+ "answer_text": answer_text,
264
+ "answer_raw": answer_raw,
265
+ "input_token_count": input_token_count,
266
+ "vision_input_shapes": vision_input_shapes,
267
+ "output_token_ids": output_token_ids,
268
+ "output_token_count": len(output_token_ids),
269
+ "hit_token_limit": hit_token_limit,
270
+ "eos_token_ids": eos_ids,
271
+ "generation_seconds": generation_seconds,
272
+ "device": self.device,
273
+ "dtype": str(self.dtype).removeprefix("torch."),
274
+ "library_versions": self._library_versions(),
275
+ "generation_config": {
276
+ "max_new_tokens": reasoning_budget,
277
+ "force_answer_max_new_tokens": force_budget,
278
+ "do_sample": DO_SAMPLE,
279
+ "temperature": TEMPERATURE,
280
+ "top_p": None,
281
+ "top_k": None,
282
+ **self.chat_template_kwargs,
283
+ },
284
+ "reasoning_text": reasoning_text,
285
+ "reasoning_raw": reasoning_raw,
286
+ "reasoning_token_ids": reasoning_token_ids,
287
+ "reasoning_token_count": len(reasoning_token_ids),
288
+ "reasoning_hit_limit": reasoning_hit_limit,
289
+ "forced": forced,
290
+ "forced_input_token_count": forced_input_token_count,
291
+ }
292
+
293
+
294
+ class QwenVLAdapter(_TransformersVLMAdapter):
295
+ """Qwen3.5 (image-text-to-text): used for both the 4B and 2B checkpoints.
296
+
297
+ ``enable_thinking=False`` is required, not optional -- Qwen3.5's chat template
298
+ defaults to opening an unclosed ``<think>`` block before the answer, which would
299
+ consume the entire 16-token budget on reasoning preamble and never emit an answer.
300
+ """
301
+
302
+ chat_template_kwargs = {"enable_thinking": False}
303
+
304
+
305
+ class InternVLAdapter(_TransformersVLMAdapter):
306
+ """InternVL3.5 (image-text-to-text).
307
+
308
+ ``crop_to_patches=False`` is required, not optional -- InternVL's default image
309
+ processor dynamically tiles EACH image content item into up to ~13 sub-patches at
310
+ 448x448, meant for one high-resolution photo. Applied per FRAME (our multi-image
311
+ prompting, one item per frame -- see ``_numbered_content``), that explodes the
312
+ prompt to ~3300 tokens/frame; just 16 frames already exceeds this checkpoint's
313
+ 40960-token context window before generation can even start. Disabling tiling
314
+ drops that to ~265 tokens/frame (measured: 16 frames 53401 -> 4251 tokens),
315
+ letting every frame count up to 96 fit comfortably. (The "correct" fix -- passing
316
+ frames as one native ``{"type": "video"}`` content item, which HF's own video
317
+ preprocessor handles at a similarly low per-frame cost without this flag -- hits
318
+ an unrelated shape-mismatch bug in this transformers version's InternVL vision
319
+ pixel-shuffle path; this is the working equivalent, not a workaround of our own
320
+ logic.)
321
+ """
322
+
323
+ chat_template_kwargs = {"crop_to_patches": False}
324
+
325
+
326
+ _ADAPTERS = {
327
+ "qwen3.5-4b": QwenVLAdapter,
328
+ "qwen3.5-2b": QwenVLAdapter,
329
+ "internvl3.5-4b": InternVLAdapter,
330
+ }
331
+
332
+
333
+ def available_models():
334
+ """Return registered model names in stable order."""
335
+ return tuple(sorted(_ADAPTERS))
336
+
337
+
338
+ def get_adapter(model):
339
+ """Create one unloaded adapter bound to a registered model's checkpoint path."""
340
+ adapter_type = _ADAPTERS.get(model)
341
+ if adapter_type is None:
342
+ raise KeyError(f"unknown harness model {model!r}; expected one of {available_models()}")
343
+ return adapter_type(MODEL_PATHS[model])
harness/A/prompts.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """VSI-Bench prompt construction -- reproduces lmms_eval's own protocol exactly.
2
+
3
+ Mirrors ``thinking-in-space/lmms_eval/tasks/vsibench/utils.py::vsibench_doc_to_text``
4
+ and ``vsibench.yaml``'s ``lmms_eval_specific_kwargs.default`` profile verbatim (the
5
+ profile every non-API model, including local HF checkpoints, is scored under): the
6
+ same question-type split, the same pre/post prompt text, the same "\\n".join layout.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ # Verbatim from thinking-in-space/lmms_eval/tasks/vsibench/utils.py.
12
+ MCA_QUESTION_TYPES = (
13
+ "object_rel_direction_easy",
14
+ "object_rel_direction_medium",
15
+ "object_rel_direction_hard",
16
+ "object_rel_distance",
17
+ "route_planning",
18
+ "obj_appearance_order",
19
+ )
20
+ NA_QUESTION_TYPES = (
21
+ "object_abs_distance",
22
+ "object_counting",
23
+ "object_size_estimation",
24
+ "room_size_estimation",
25
+ )
26
+
27
+ # vsibench.yaml lmms_eval_specific_kwargs.default. pre_prompt is "" in the yaml, which
28
+ # the original doc_to_text treats as falsy and falls back to this text -- so this is
29
+ # the pre_prompt every non-API (incl. local HF) model is actually scored under.
30
+ PRE_PROMPT = "These are frames of a video."
31
+ NA_POST_PROMPT = "Please answer the question using a single word or phrase."
32
+ MCA_POST_PROMPT = "Answer with the option's letter from the given choices directly."
33
+
34
+
35
+ def build_prompt(question_type, question, options=None):
36
+ """Return the exact text prompt lmms_eval would send for one VSI-Bench question."""
37
+ if question_type in NA_QUESTION_TYPES:
38
+ return PRE_PROMPT + "\n" + question + "\n" + NA_POST_PROMPT
39
+ if question_type in MCA_QUESTION_TYPES:
40
+ if not options:
41
+ raise ValueError(f"question_type {question_type!r} requires options")
42
+ options_block = "Options:\n" + "\n".join(options)
43
+ return "\n".join([PRE_PROMPT, question, options_block, MCA_POST_PROMPT])
44
+ raise ValueError(
45
+ f"unknown question_type {question_type!r}; "
46
+ f"expected one of {MCA_QUESTION_TYPES + NA_QUESTION_TYPES}"
47
+ )
harness/A/run.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run one VLM over VSI-Bench questions through harness A's frame sampling + adapters.
2
+
3
+ Writes one JSON file per question -- the same one-file-per-question layout
4
+ ``symbolic/run.py`` uses for the spatial-code pipeline -- with the FULL, untruncated
5
+ record: the exact prompt text sent, the cleaned and fully raw decoded response, the
6
+ actual output token ids/count, whether the 16-token budget cut generation off before a
7
+ natural stop, the exact generation config used, per-question latency, and full
8
+ provenance (video path, frame indices/timestamps, device/dtype, library versions).
9
+ Nothing here is summarized or truncated for display; printing to stdout is a separate,
10
+ lossy convenience only.
11
+
12
+ Scoring reuses the real, unmodified official scorer
13
+ (``thinking-in-space/lmms_eval/tasks/vsibench/utils.py``), the same convention
14
+ ``symbolic/run.py`` already follows, so results here are directly comparable to those.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import importlib.util
21
+ import json
22
+ import os
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent
27
+ if str(WORKSPACE_ROOT) not in sys.path:
28
+ sys.path.insert(0, str(WORKSPACE_ROOT))
29
+
30
+ import inference as inference_config # noqa: E402
31
+ from harness.A import ( # noqa: E402
32
+ DEFAULT_FRAME_SELECTION,
33
+ EXTENDED_MAX_NEW_TOKENS,
34
+ FRAME_SELECTIONS,
35
+ FRAMES_PER_VIDEO,
36
+ JSONL,
37
+ MAX_NEW_TOKENS,
38
+ RESULTS_DIR,
39
+ )
40
+ from harness.A import frames as frame_sampling # noqa: E402
41
+ from harness.A import models as vlm_models # noqa: E402
42
+ from harness.A import prompts as vsi_prompts # noqa: E402
43
+
44
+ _OFFICIAL_EVAL = os.environ.get(
45
+ "HARNESS_OFFICIAL_EVAL",
46
+ "/root/data/thinking-in-space/lmms_eval/tasks/vsibench/utils.py",
47
+ )
48
+
49
+
50
+ def _load_official_eval(path):
51
+ # Loaded under a unique module name (not the bare "utils" symbolic/run.py itself
52
+ # uses) so the two never fight over sys.modules["utils"] when both are imported in
53
+ # the same process, e.g. across the test suite.
54
+ spec = importlib.util.spec_from_file_location("harness_A_vsi_official_eval", path)
55
+ module = importlib.util.module_from_spec(spec)
56
+ spec.loader.exec_module(module)
57
+ return module
58
+
59
+
60
+ vsi_official_eval = _load_official_eval(_OFFICIAL_EVAL)
61
+
62
+
63
+ def _scalar_score(question_type, score_doc):
64
+ """Return (metric_name, value) -- the one numeric metric attached by the scorer."""
65
+ if question_type in vsi_official_eval.MCA_QUESTION_TYPES:
66
+ metric_keys = vsi_official_eval.METRICS_FOR_MCA
67
+ elif question_type in vsi_official_eval.NA_QUESTION_TYPES:
68
+ metric_keys = vsi_official_eval.METRICS_FOR_NA
69
+ else:
70
+ raise ValueError(
71
+ f"unknown question_type {question_type!r}; "
72
+ f"expected one of {vsi_official_eval.MCA_QUESTION_TYPES + vsi_official_eval.NA_QUESTION_TYPES}"
73
+ )
74
+ (metric_key,) = metric_keys.keys()
75
+ return metric_key, score_doc[metric_key]
76
+
77
+
78
+ def load_questions(jsonl_path=None, scene=None, scenes=None, limit=None):
79
+ """Return VSI-Bench question rows, optionally filtered to one/many scenes / capped."""
80
+ if scene is not None and scenes is not None:
81
+ raise ValueError("scene and scenes cannot both be given")
82
+ allowed = {scene} if scene is not None else (set(scenes) if scenes is not None else None)
83
+ jsonl_path = jsonl_path or JSONL
84
+ rows = []
85
+ with open(jsonl_path) as stream:
86
+ for line in stream:
87
+ row = json.loads(line)
88
+ if allowed is not None and row["scene_name"] not in allowed:
89
+ continue
90
+ rows.append(row)
91
+ if limit is not None and len(rows) >= limit:
92
+ break
93
+ return rows
94
+
95
+
96
+ def results_dir_for(model, frame_selection, frame_count, results_dir=None):
97
+ """Return the result root isolated by model + frame-selection + frame-count."""
98
+ if results_dir is not None:
99
+ return Path(results_dir)
100
+ return RESULTS_DIR / model / frame_selection / str(frame_count)
101
+
102
+
103
+ def _build_record(row, prompt, answer, metric_name, score, model, model_path, frame_info):
104
+ """Assemble one question's full, untruncated result record (nothing summarized)."""
105
+ return {
106
+ "model": model,
107
+ "model_path": str(model_path),
108
+ "device": answer["device"],
109
+ "dtype": answer["dtype"],
110
+ "library_versions": answer["library_versions"],
111
+ "condition": f"{frame_info['frame_selection']}:{frame_info['frame_count']}",
112
+ "frame_selection": frame_info["frame_selection"],
113
+ "frame_count": frame_info["frame_count"],
114
+ "video_path": frame_info["video_path"],
115
+ "frame_indices": frame_info["frame_indices"],
116
+ "frame_timestamps_seconds": frame_info["frame_timestamps"],
117
+ "scene": row["scene_name"],
118
+ "dataset": row.get("dataset"),
119
+ "question_id": row["id"],
120
+ "question_type": row["question_type"],
121
+ "question": row["question"],
122
+ "options": row.get("options"),
123
+ "full_prompt": prompt,
124
+ "rendered_prompt": answer["prompt_text"],
125
+ "answer_expected": row["ground_truth"],
126
+ "answer_given": answer["answer_text"],
127
+ "answer_raw": answer["answer_raw"],
128
+ "input_token_count": answer["input_token_count"],
129
+ "vision_input_shapes": answer["vision_input_shapes"],
130
+ "output_token_ids": answer["output_token_ids"],
131
+ "output_token_count": answer["output_token_count"],
132
+ "hit_token_limit": answer["hit_token_limit"],
133
+ "eos_token_ids": answer["eos_token_ids"],
134
+ "generation_seconds": answer["generation_seconds"],
135
+ "generation_config": answer["generation_config"],
136
+ "reasoning_text": answer.get("reasoning_text"),
137
+ "reasoning_raw": answer.get("reasoning_raw"),
138
+ "reasoning_token_ids": answer.get("reasoning_token_ids"),
139
+ "reasoning_token_count": answer.get("reasoning_token_count"),
140
+ "reasoning_hit_limit": answer.get("reasoning_hit_limit"),
141
+ "forced": answer.get("forced", False),
142
+ "forced_input_token_count": answer.get("forced_input_token_count"),
143
+ "metric": metric_name,
144
+ "score": score,
145
+ }
146
+
147
+
148
+ def write_question_result(
149
+ row, prompt, answer, metric_name, score, model, model_path, frame_info, results_dir=None
150
+ ):
151
+ """Write one question's full, untruncated result record. Return (path, record)."""
152
+ record = _build_record(
153
+ row, prompt, answer, metric_name, score, model, model_path, frame_info
154
+ )
155
+ root = results_dir_for(
156
+ model, frame_info["frame_selection"], frame_info["frame_count"], results_dir
157
+ )
158
+ scene_dir = root / record["scene"]
159
+ scene_dir.mkdir(parents=True, exist_ok=True)
160
+ path = scene_dir / f"{row['id']}.json"
161
+ with path.open("w", encoding="utf-8") as stream:
162
+ json.dump(record, stream, indent=1)
163
+ return path, record
164
+
165
+
166
+ def run(
167
+ model,
168
+ frame_selection=DEFAULT_FRAME_SELECTION,
169
+ frame_count=FRAMES_PER_VIDEO,
170
+ scene=None,
171
+ scenes=None,
172
+ limit=None,
173
+ device="cuda",
174
+ jsonl_path=None,
175
+ results_dir=None,
176
+ write_results=True,
177
+ adapter=None,
178
+ extended=False,
179
+ reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
180
+ force_budget=MAX_NEW_TOKENS,
181
+ ):
182
+ """Answer every matching question with one model, scored via the official scorer.
183
+
184
+ Each question's full record is written to its own JSON file as soon as it is
185
+ answered (unless ``write_results=False``); the in-memory list returned holds the
186
+ same full records for callers that want them without re-reading from disk.
187
+
188
+ Pass a pre-loaded ``adapter`` (as ``harness.A.launch``'s persistent per-GPU workers
189
+ do) to reuse one already-loaded model across many calls instead of paying the load
190
+ cost per call; the caller then owns unloading it. Without one, ``run`` loads and
191
+ unloads its own adapter, same as before.
192
+
193
+ ``extended=True`` switches from the fixed 16-token VSI-Bench protocol to
194
+ ``adapter.answer_extended`` -- a much larger first-pass budget (``reasoning_budget``)
195
+ with a short forced second call (``force_budget``) only if the model doesn't
196
+ conclude within it. Opt-in per call/CLI invocation, not a change to the default
197
+ protocol every other harness.A caller and test still exercises.
198
+ """
199
+ rows = load_questions(jsonl_path, scene, scenes, limit)
200
+ if not rows:
201
+ return []
202
+ owns_adapter = adapter is None
203
+ if owns_adapter:
204
+ adapter = vlm_models.get_adapter(model)
205
+ adapter.load_model(device)
206
+ frame_cache = {}
207
+ results = []
208
+ try:
209
+ for row in rows:
210
+ scene_id = row["scene_name"]
211
+ if scene_id not in frame_cache:
212
+ video_path = inference_config.video_path(scene_id, row.get("dataset"))
213
+ frame_images, frame_timestamps, frame_indices = frame_sampling.sample_frames(
214
+ video_path, frame_count, frame_selection
215
+ )
216
+ frame_cache[scene_id] = {
217
+ "video_path": video_path,
218
+ "frame_images": frame_images,
219
+ "frame_timestamps": frame_timestamps,
220
+ "frame_indices": frame_indices,
221
+ "frame_selection": frame_selection,
222
+ "frame_count": frame_count,
223
+ }
224
+ cached = frame_cache[scene_id]
225
+ prompt = vsi_prompts.build_prompt(
226
+ row["question_type"], row["question"], row.get("options")
227
+ )
228
+ answer = (
229
+ adapter.answer_extended(
230
+ cached["frame_images"], prompt,
231
+ reasoning_budget=reasoning_budget, force_budget=force_budget,
232
+ )
233
+ if extended
234
+ else adapter.answer(cached["frame_images"], prompt)
235
+ )
236
+ doc = {"question_type": row["question_type"], "ground_truth": row["ground_truth"]}
237
+ score_doc = vsi_official_eval.vsibench_process_results(
238
+ doc, [answer["answer_text"]]
239
+ )["vsibench_score"]
240
+ metric_name, score = _scalar_score(row["question_type"], score_doc)
241
+ frame_info = {
242
+ "video_path": cached["video_path"],
243
+ "frame_timestamps": cached["frame_timestamps"],
244
+ "frame_indices": cached["frame_indices"],
245
+ "frame_selection": frame_selection,
246
+ "frame_count": frame_count,
247
+ }
248
+ if write_results:
249
+ path, record = write_question_result(
250
+ row, prompt, answer, metric_name, score, model, adapter.model_path,
251
+ frame_info, results_dir,
252
+ )
253
+ else:
254
+ path = None
255
+ record = _build_record(
256
+ row, prompt, answer, metric_name, score, model, adapter.model_path, frame_info
257
+ )
258
+ record["result_path"] = str(path) if path else None
259
+ results.append(record)
260
+ finally:
261
+ if owns_adapter:
262
+ adapter.unload()
263
+ return results
264
+
265
+
266
+ def main():
267
+ parser = argparse.ArgumentParser()
268
+ parser.add_argument("--model", required=True, choices=vlm_models.available_models())
269
+ parser.add_argument("--scene", default=None, help="restrict to one VSI-Bench scene")
270
+ parser.add_argument(
271
+ "--frame-selection",
272
+ default=DEFAULT_FRAME_SELECTION,
273
+ choices=FRAME_SELECTIONS,
274
+ dest="frame_selection",
275
+ )
276
+ parser.add_argument("--frames", type=int, default=FRAMES_PER_VIDEO)
277
+ parser.add_argument("--limit", type=int, default=None, help="cap the number of questions")
278
+ parser.add_argument("--device", default="cuda")
279
+ parser.add_argument(
280
+ "--results-dir",
281
+ default=None,
282
+ help="override the default results/A/<model>/<selection>/<frames> root",
283
+ )
284
+ parser.add_argument(
285
+ "--no-write",
286
+ action="store_true",
287
+ help="skip writing per-question JSON files; print/score only",
288
+ )
289
+ parser.add_argument(
290
+ "--extended",
291
+ action="store_true",
292
+ help=(
293
+ f"use a {EXTENDED_MAX_NEW_TOKENS}-token reasoning budget instead of the fixed "
294
+ f"{MAX_NEW_TOKENS}-token VSI-Bench protocol, with a short forced second call "
295
+ "only if the model doesn't conclude within it"
296
+ ),
297
+ )
298
+ parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
299
+ parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
300
+ args = parser.parse_args()
301
+ if args.frames < 1:
302
+ parser.error("--frames must be positive")
303
+ if args.reasoning_budget < 1:
304
+ parser.error("--reasoning-budget must be positive")
305
+ if args.force_budget < 1:
306
+ parser.error("--force-budget must be positive")
307
+
308
+ results = run(
309
+ args.model,
310
+ frame_selection=args.frame_selection,
311
+ frame_count=args.frames,
312
+ scene=args.scene,
313
+ limit=args.limit,
314
+ device=args.device,
315
+ results_dir=args.results_dir,
316
+ write_results=not args.no_write,
317
+ extended=args.extended,
318
+ reasoning_budget=args.reasoning_budget,
319
+ force_budget=args.force_budget,
320
+ )
321
+
322
+ for result in results:
323
+ print(
324
+ f"[{result['scene']}#{result['question_id']}] {result['question_type']}: "
325
+ f"pred={result['answer_given']!r} gt={result['answer_expected']!r} "
326
+ f"score={result['score']} ({result['generation_seconds']:.2f}s) -> "
327
+ f"{result['result_path']}"
328
+ )
329
+ if results:
330
+ mean_score = sum(r["score"] for r in results) / len(results)
331
+ total_seconds = sum(r["generation_seconds"] for r in results)
332
+ print(
333
+ f"\n{len(results)} questions, mean vsibench_score={mean_score:.4f}, "
334
+ f"total generation time={total_seconds:.1f}s"
335
+ )
336
+
337
+
338
+ if __name__ == "__main__":
339
+ main()
harness/A/sweep.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sweep any set of models x frame-selections x frame-counts, one command.
2
+
3
+ Every (model, frame_selection, frame_count) triple in the sweep is run through
4
+ ``harness.A.launch.launch`` in turn, so each triple individually saturates every
5
+ visible GPU (persistent per-GPU workers, one model load per worker, scenes sharded off
6
+ a shared queue) before the next triple starts. Triples aren't run concurrently with
7
+ each other -- each already uses every GPU on its own, so there is nothing to gain by
8
+ overlapping them, and it keeps peak GPU memory bounded to one model at a time.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ from pathlib import Path
15
+ import sys
16
+
17
+ HERE = Path(__file__).resolve().parent
18
+ WORKSPACE_ROOT = HERE.parent.parent
19
+ if str(WORKSPACE_ROOT) not in sys.path:
20
+ sys.path.insert(0, str(WORKSPACE_ROOT))
21
+
22
+ from harness.A import FRAME_SELECTIONS # noqa: E402
23
+ from harness.A import launch as harness_launch # noqa: E402
24
+ from harness.A import models as vlm_models # noqa: E402
25
+
26
+
27
+ def _parse_csv_choice(value, valid, flag):
28
+ """Split a comma-separated ``--flag`` value; ``"all"`` expands to every ``valid``."""
29
+ items = [item.strip() for item in value.split(",") if item.strip()]
30
+ if not items:
31
+ raise ValueError(f"{flag} must name at least one value")
32
+ if len(items) == 1 and items[0].lower() == "all":
33
+ return list(valid)
34
+ unknown = [item for item in items if item not in valid]
35
+ if unknown:
36
+ raise ValueError(f"unknown {flag} value(s) {unknown}; expected one of {valid} (or 'all')")
37
+ return list(dict.fromkeys(items))
38
+
39
+
40
+ def _parse_frame_counts(value):
41
+ items = [item.strip() for item in value.split(",") if item.strip()]
42
+ if not items:
43
+ raise ValueError("--frames must name at least one frame count")
44
+ counts = []
45
+ for item in items:
46
+ try:
47
+ count = int(item)
48
+ except ValueError:
49
+ raise ValueError(f"--frames value {item!r} is not an integer") from None
50
+ if count < 1:
51
+ raise ValueError(f"--frames value {count} must be positive")
52
+ counts.append(count)
53
+ return list(dict.fromkeys(counts))
54
+
55
+
56
+ def build_plan(models, frame_selections, frame_counts):
57
+ """Return every (model, frame_selection, frame_count) triple in the sweep, in a
58
+ stable, cheapest-first-ish order (frame count is the dominant cost driver, so
59
+ sorting by it surfaces comparable results across every model/selection soonest)."""
60
+ return [
61
+ (model, selection, frame_count)
62
+ for frame_count in sorted(frame_counts)
63
+ for model in models
64
+ for selection in frame_selections
65
+ ]
66
+
67
+
68
+ def sweep(models, frame_selections, frame_counts, selected_scenes, results_dir=None, rebuild=False):
69
+ """Run every (model, frame_selection, frame_count) triple across all visible GPUs."""
70
+ plan = build_plan(models, frame_selections, frame_counts)
71
+ for index, (model, frame_selection, frame_count) in enumerate(plan, start=1):
72
+ print(f"=== sweep {index}/{len(plan)}: {model}/{frame_selection}/{frame_count} ===", flush=True)
73
+ harness_launch.launch(
74
+ model, frame_selection, frame_count, selected_scenes,
75
+ results_dir=results_dir, rebuild=rebuild,
76
+ )
77
+
78
+
79
+ def main():
80
+ parser = argparse.ArgumentParser()
81
+ parser.add_argument("scene", nargs="?")
82
+ parser.add_argument(
83
+ "--scenes", help="comma-separated scenes (cannot be combined with positional scene)"
84
+ )
85
+ parser.add_argument(
86
+ "--models", required=True,
87
+ help=f"comma-separated models (or 'all'); one of {vlm_models.available_models()}",
88
+ )
89
+ parser.add_argument(
90
+ "--frame-selections", required=True, dest="frame_selections",
91
+ help=f"comma-separated selections (or 'all'); one of {FRAME_SELECTIONS}",
92
+ )
93
+ parser.add_argument(
94
+ "--frames", required=True,
95
+ help="comma-separated frame counts, e.g. 16,32,64",
96
+ )
97
+ parser.add_argument("--results-dir", default=None)
98
+ parser.add_argument("--rebuild", action="store_true")
99
+ args = parser.parse_args()
100
+ if args.scene and args.scenes:
101
+ parser.error("positional scene and --scenes cannot be used together")
102
+
103
+ try:
104
+ models = _parse_csv_choice(args.models, vlm_models.available_models(), "--models")
105
+ frame_selections = _parse_csv_choice(
106
+ args.frame_selections, FRAME_SELECTIONS, "--frame-selections"
107
+ )
108
+ frame_counts = _parse_frame_counts(args.frames)
109
+ except ValueError as exc:
110
+ parser.error(str(exc))
111
+
112
+ if args.scenes is not None:
113
+ selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
114
+ if not selected:
115
+ parser.error("--scenes must contain at least one scene")
116
+ selected = list(dict.fromkeys(selected))
117
+ else:
118
+ selected = [args.scene] if args.scene else harness_launch.scenes()
119
+
120
+ sweep(
121
+ models, frame_selections, frame_counts, selected,
122
+ results_dir=args.results_dir, rebuild=args.rebuild,
123
+ )
124
+
125
+
126
+ if __name__ == "__main__":
127
+ main()
harness/B/__init__.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Harness B: route a scene's on-disk spatial code (explicit or compact) -- as TEXT,
2
+ no video frames -- to all three models, for every VSI-Bench question.
3
+
4
+ Reuses harness.A's model registry/adapters and fixed generation protocol exactly; only
5
+ what is fed to the model differs (spatial-code text instead of frame images). Results
6
+ are written in the identical per-question JSON shape harness.A uses, so B's records are
7
+ directly comparable to A's -- the frame-provenance fields are simply replaced with
8
+ spatial-code provenance fields (see harness.B.run._build_record).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ from pathlib import Path
15
+
16
+ from encoder.config import DEPTH_VARIANTS, TRACKING_MODES
17
+
18
+ from harness.A import DO_SAMPLE, JSONL, MAX_NEW_TOKENS, MODEL_PATHS, TEMPERATURE, WORKSPACE_ROOT
19
+
20
+ # Same two on-disk spatial-code schemas encoder/geometric.py can build.
21
+ SPATIAL_CODE_FORMATS = ("explicit", "compact")
22
+ DEFAULT_SPATIAL_CODE_FORMAT = "explicit"
23
+
24
+ # Same vocabulary as inference.SAM3_FRAME_SELECTIONS / harness.A.FRAME_SELECTIONS --
25
+ # which raw video sampling the on-disk spatial code was itself built from.
26
+ INPUT_SELECTIONS = ("uniform", "selective")
27
+ DEFAULT_INPUT_SELECTION = "uniform"
28
+
29
+ # Same depth/tracking vocabulary encoder.config uses to lay out spatial codes on disk --
30
+ # real sweepable axes here too (see sweep.py's --depths/--trackings), not fixed
31
+ # constants; DEFAULT_DEPTH/DEFAULT_TRACKING are just the single-value default when a
32
+ # caller doesn't ask to sweep them, matching this workspace's shipped production config.
33
+ DEFAULT_DEPTH = "metric"
34
+ DEFAULT_TRACKING = "tracking"
35
+
36
+ FRAMES_PER_VIDEO = int(os.environ.get("VSI_HARNESS_B_FRAMES_PER_VIDEO", "32"))
37
+
38
+ # One JSON per question, matching harness.A's layout:
39
+ # results/B/<model>/<spatial_code_format>/<depth>/<tracking>/<input_selection>/<frame_count>/<scene>/<question_id>.json
40
+ RESULTS_DIR = Path(
41
+ os.environ.get("VSI_HARNESS_B_RESULTS_DIR", WORKSPACE_ROOT / "results" / "B")
42
+ )
harness/B/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (1.79 kB). View file
 
harness/B/__pycache__/launch.cpython-311.pyc ADDED
Binary file (12.7 kB). View file
 
harness/B/__pycache__/prompts.cpython-311.pyc ADDED
Binary file (2.54 kB). View file
 
harness/B/__pycache__/run.cpython-311.pyc ADDED
Binary file (14.1 kB). View file
 
harness/B/__pycache__/spatial_codes.cpython-311.pyc ADDED
Binary file (1.87 kB). View file
 
harness/B/__pycache__/sweep.cpython-311.pyc ADDED
Binary file (7.79 kB). View file
 
harness/B/launch.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Keep every visible GPU busy with persistent harness-B inference workers.
2
+
3
+ Same shape as ``harness.A.launch``: one persistent worker process per visible GPU,
4
+ pulling scenes off a shared queue, each loading its model exactly once and reusing it
5
+ for every scene it's assigned (via ``run.run(..., adapter=...)``). One invocation covers
6
+ one (model, spatial_code_format, input_selection, frame_count) quadruple across every
7
+ requested scene; sweep multiple quadruples by invoking this once per quadruple (see
8
+ harness.B.sweep, or a shell loop).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import importlib.util
15
+ import multiprocessing as mp
16
+ import os
17
+ from pathlib import Path
18
+ import sys
19
+ import traceback
20
+
21
+ HERE = Path(__file__).resolve().parent
22
+ WORKSPACE_ROOT = HERE.parent.parent
23
+ if str(WORKSPACE_ROOT) not in sys.path:
24
+ sys.path.insert(0, str(WORKSPACE_ROOT))
25
+
26
+ from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402
27
+ from harness.A import models as vlm_models # noqa: E402
28
+ from harness.A.launch import scenes # noqa: E402
29
+ from harness.B import ( # noqa: E402
30
+ DEFAULT_DEPTH,
31
+ DEFAULT_INPUT_SELECTION,
32
+ DEFAULT_SPATIAL_CODE_FORMAT,
33
+ DEFAULT_TRACKING,
34
+ DEPTH_VARIANTS,
35
+ FRAMES_PER_VIDEO,
36
+ INPUT_SELECTIONS,
37
+ SPATIAL_CODE_FORMATS,
38
+ TRACKING_MODES,
39
+ )
40
+ from inference.launch import available_cpu_count, visible_gpus # noqa: E402
41
+
42
+
43
+ def _load_run_module():
44
+ spec = importlib.util.spec_from_file_location("_harness_B_run", HERE / "run.py")
45
+ module = importlib.util.module_from_spec(spec)
46
+ sys.modules[spec.name] = module
47
+ spec.loader.exec_module(module)
48
+ return module
49
+
50
+
51
+ def _worker(
52
+ tasks, results, model, spatial_code_format, input_selection, frame_count, depth, tracking,
53
+ results_dir, gpu, cpu_threads, reasoning_budget, force_budget,
54
+ ):
55
+ if gpu is not None:
56
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
57
+ for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
58
+ os.environ[variable] = str(cpu_threads)
59
+ run = _load_run_module()
60
+ adapter = None
61
+ load_error = None
62
+ try:
63
+ adapter = vlm_models.get_adapter(model)
64
+ adapter.load_model("cuda:0" if gpu is not None else "cpu")
65
+ except Exception:
66
+ load_error = traceback.format_exc()
67
+ while True:
68
+ scene = tasks.get()
69
+ if scene is None:
70
+ return
71
+ if load_error is not None:
72
+ results.put((scene, False, load_error))
73
+ continue
74
+ try:
75
+ answered = run.run(
76
+ model,
77
+ spatial_code_format=spatial_code_format,
78
+ input_selection=input_selection,
79
+ frame_count=frame_count,
80
+ depth=depth,
81
+ tracking=tracking,
82
+ scene=scene,
83
+ results_dir=results_dir,
84
+ adapter=adapter,
85
+ reasoning_budget=reasoning_budget,
86
+ force_budget=force_budget,
87
+ )
88
+ mean_score = (
89
+ sum(r["score"] for r in answered) / len(answered) if answered else None
90
+ )
91
+ results.put(
92
+ (scene, True, f"{len(answered)} question(s), mean_score={mean_score}")
93
+ )
94
+ except Exception:
95
+ results.put((scene, False, traceback.format_exc()))
96
+
97
+
98
+ def launch(
99
+ model, spatial_code_format, input_selection, frame_count, selected,
100
+ depth=DEFAULT_DEPTH, tracking=DEFAULT_TRACKING, results_dir=None, rebuild=False,
101
+ reasoning_budget=EXTENDED_MAX_NEW_TOKENS, force_budget=MAX_NEW_TOKENS,
102
+ ):
103
+ """Answer every question for ``selected`` scenes, sharded across every visible GPU."""
104
+ condition = f"{model}/{spatial_code_format}/{depth}/{tracking}/{input_selection}/{frame_count}"
105
+ run = _load_run_module()
106
+ root = run.results_dir_for(
107
+ model, spatial_code_format, depth, tracking, input_selection, frame_count, results_dir
108
+ )
109
+ pending = []
110
+ completed = 0
111
+ for scene in selected:
112
+ rows = run.load_questions(scene=scene)
113
+ answered = all((root / scene / f"{row['id']}.json").is_file() for row in rows)
114
+ if answered and not rebuild:
115
+ completed += 1
116
+ print(f"[{condition} {completed}/{len(selected)}] {scene}: skipped", flush=True)
117
+ else:
118
+ pending.append(scene)
119
+ if not pending:
120
+ print(f"[{condition}] DONE: {len(selected)} ok, 0 failed")
121
+ return
122
+
123
+ gpus = visible_gpus()
124
+ worker_count = min(len(pending), len(gpus) if gpus else 1)
125
+ assignments = gpus[:worker_count] if gpus else [None]
126
+ cpu_count = available_cpu_count()
127
+ cpu_threads = max(1, cpu_count // worker_count)
128
+ print(
129
+ f"[{condition}] starting {worker_count} persistent worker(s); "
130
+ f"GPUs={assignments}; CPU threads/worker={cpu_threads}",
131
+ flush=True,
132
+ )
133
+
134
+ context = mp.get_context("spawn")
135
+ tasks, results = context.Queue(), context.Queue()
136
+ for scene in pending:
137
+ tasks.put(scene)
138
+ for _ in range(worker_count):
139
+ tasks.put(None)
140
+ workers = [
141
+ context.Process(
142
+ target=_worker,
143
+ args=(
144
+ tasks, results, model, spatial_code_format, input_selection, frame_count,
145
+ depth, tracking, results_dir, gpu, cpu_threads, reasoning_budget, force_budget,
146
+ ),
147
+ )
148
+ for gpu in assignments
149
+ ]
150
+ for worker in workers:
151
+ worker.start()
152
+ failed = []
153
+ for finished in range(1, len(pending) + 1):
154
+ scene, ok, detail = results.get()
155
+ if not ok:
156
+ failed.append(scene)
157
+ print(
158
+ f"[{condition} {completed + finished}/{len(selected)}] {scene}: "
159
+ f"{'done' if ok else 'FAILED'}\n{detail}",
160
+ flush=True,
161
+ )
162
+ for worker in workers:
163
+ worker.join()
164
+ print(
165
+ f"[{condition}] DONE: {len(pending) - len(failed)} answered, {completed} skipped, "
166
+ f"{len(failed)} failed"
167
+ )
168
+ if failed:
169
+ raise SystemExit(1)
170
+
171
+
172
+ def main():
173
+ parser = argparse.ArgumentParser()
174
+ parser.add_argument("scene", nargs="?")
175
+ parser.add_argument(
176
+ "--scenes", help="comma-separated scenes (cannot be combined with positional scene)"
177
+ )
178
+ parser.add_argument("--model", required=True, choices=vlm_models.available_models())
179
+ parser.add_argument(
180
+ "--spatial-code-format", default=DEFAULT_SPATIAL_CODE_FORMAT,
181
+ choices=SPATIAL_CODE_FORMATS, dest="spatial_code_format",
182
+ )
183
+ parser.add_argument(
184
+ "--input-selection", default=DEFAULT_INPUT_SELECTION,
185
+ choices=INPUT_SELECTIONS, dest="input_selection",
186
+ )
187
+ parser.add_argument("--frames", type=int, default=FRAMES_PER_VIDEO)
188
+ parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS)
189
+ parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES)
190
+ parser.add_argument("--results-dir", default=None)
191
+ parser.add_argument("--rebuild", action="store_true")
192
+ parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
193
+ parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
194
+ args = parser.parse_args()
195
+ if args.scene and args.scenes:
196
+ parser.error("positional scene and --scenes cannot be used together")
197
+ if args.scenes is not None:
198
+ selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
199
+ if not selected:
200
+ parser.error("--scenes must contain at least one scene")
201
+ selected = list(dict.fromkeys(selected))
202
+ else:
203
+ selected = [args.scene] if args.scene else scenes()
204
+ if args.frames < 1:
205
+ parser.error("--frames must be positive")
206
+ if args.reasoning_budget < 1:
207
+ parser.error("--reasoning-budget must be positive")
208
+ if args.force_budget < 1:
209
+ parser.error("--force-budget must be positive")
210
+ launch(
211
+ args.model, args.spatial_code_format, args.input_selection, args.frames, selected,
212
+ depth=args.depth, tracking=args.tracking, results_dir=args.results_dir, rebuild=args.rebuild,
213
+ reasoning_budget=args.reasoning_budget, force_budget=args.force_budget,
214
+ )
215
+
216
+
217
+ if __name__ == "__main__":
218
+ main()
harness/B/prompts.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """VSI-Bench prompt construction with a spatial code (as text) instead of video frames.
2
+
3
+ Reuses harness.A.prompts's exact question-type split and post-prompts verbatim -- only
4
+ the pre-prompt context line changes (there are no frames to describe), and the spatial
5
+ code's own JSON text is inserted between that context line and the question.
6
+
7
+ CODE_DESCRIPTION deliberately says nothing about where the code came from (not "based on
8
+ an analysis of a video", not "ground truth annotation") -- the model is never told
9
+ whether it's reading a perceived or ground-truth code, in either harness.B (perceived)
10
+ or harness.D (ground truth), which is exactly what makes a B-vs-D comparison a clean
11
+ read of perception error alone, not a comparison the model could game by knowing which
12
+ condition it's in.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+
19
+ from harness.A.prompts import MCA_POST_PROMPT, MCA_QUESTION_TYPES, NA_POST_PROMPT, NA_QUESTION_TYPES
20
+
21
+ # Deliberately vague about which fields are present -- compact and explicit carry
22
+ # different fields (e.g. only explicit has a distance table and appearance order; only
23
+ # compact has per-instance orientation vectors), and this line has to describe both
24
+ # without over- or under-claiming either one. The code's own "spatial code schema" key
25
+ # is what actually documents every field present in a given call.
26
+ #
27
+ # CODE_DESCRIPTION is factored out (not just inlined into PRE_PROMPT) so that
28
+ # harness.C.prompts and harness.D.prompts can build their own context lines by literally
29
+ # reusing this exact string -- guaranteeing the frames-only, code-only, and
30
+ # frames+code conditions never drift into differently-worded descriptions of the same
31
+ # spatial code, and guaranteeing B and D (perceived vs. ground-truth code, otherwise the
32
+ # same condition) get a byte-identical prompt, which would be a real, avoidable wording
33
+ # confound between conditions if it ever drifted.
34
+ CODE_DESCRIPTION = (
35
+ "a structured JSON description of a room and its objects. The schema included in "
36
+ "it explains every field."
37
+ )
38
+ PRE_PROMPT = "This is a spatial code: " + CODE_DESCRIPTION
39
+
40
+
41
+ def build_prompt(spatial_code, question_type, question, options=None):
42
+ """Return the full text prompt: context line, the spatial code itself, the question,
43
+ and the same VSI-Bench post-prompt harness.A uses for the same question_type."""
44
+ code_text = json.dumps(spatial_code, indent=1)
45
+ if question_type in NA_QUESTION_TYPES:
46
+ return "\n".join([PRE_PROMPT, code_text, question, NA_POST_PROMPT])
47
+ if question_type in MCA_QUESTION_TYPES:
48
+ if not options:
49
+ raise ValueError(f"question_type {question_type!r} requires options")
50
+ options_block = "Options:\n" + "\n".join(options)
51
+ return "\n".join([PRE_PROMPT, code_text, question, options_block, MCA_POST_PROMPT])
52
+ raise ValueError(
53
+ f"unknown question_type {question_type!r}; "
54
+ f"expected one of {MCA_QUESTION_TYPES + NA_QUESTION_TYPES}"
55
+ )
harness/B/run.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run one VLM over VSI-Bench questions through harness B's spatial-code-as-text routing.
2
+
3
+ Writes one JSON file per question in the identical shape harness.A uses (same
4
+ provenance-heavy, nothing-truncated philosophy) -- the frame-provenance fields are
5
+ simply replaced with spatial-code provenance fields (spatial_code_format,
6
+ input_selection, frame_count, depth, tracking, spatial_code_path), since B has no
7
+ video frames at all. Scoring reuses the same real, unmodified official scorer harness.A
8
+ and symbolic/run.py both use.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import json
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent
19
+ if str(WORKSPACE_ROOT) not in sys.path:
20
+ sys.path.insert(0, str(WORKSPACE_ROOT))
21
+
22
+ from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402
23
+ from harness.A import models as vlm_models # noqa: E402
24
+ from harness.A.run import _scalar_score, load_questions, vsi_official_eval # noqa: E402
25
+ from harness.B import ( # noqa: E402
26
+ DEFAULT_DEPTH,
27
+ DEFAULT_INPUT_SELECTION,
28
+ DEFAULT_SPATIAL_CODE_FORMAT,
29
+ DEFAULT_TRACKING,
30
+ DEPTH_VARIANTS,
31
+ FRAMES_PER_VIDEO,
32
+ INPUT_SELECTIONS,
33
+ RESULTS_DIR,
34
+ SPATIAL_CODE_FORMATS,
35
+ TRACKING_MODES,
36
+ )
37
+ from harness.B import prompts as code_prompts # noqa: E402
38
+ from harness.B import spatial_codes # noqa: E402
39
+
40
+
41
+ def results_dir_for(
42
+ model, spatial_code_format, depth, tracking, input_selection, frame_count, results_dir=None
43
+ ):
44
+ """Return the result root isolated by model + spatial-code-format + depth +
45
+ tracking + input + frames."""
46
+ if results_dir is not None:
47
+ return Path(results_dir)
48
+ return (
49
+ RESULTS_DIR / model / spatial_code_format / depth / tracking
50
+ / input_selection / str(frame_count)
51
+ )
52
+
53
+
54
+ def _build_record(row, prompt, answer, metric_name, score, model, model_path, code_info):
55
+ """Assemble one question's full, untruncated result record (nothing summarized)."""
56
+ return {
57
+ "model": model,
58
+ "model_path": str(model_path),
59
+ "device": answer["device"],
60
+ "dtype": answer["dtype"],
61
+ "library_versions": answer["library_versions"],
62
+ "condition": (
63
+ f"{code_info['spatial_code_format']}:{code_info['depth']}:"
64
+ f"{code_info['tracking']}:{code_info['input_selection']}:"
65
+ f"{code_info['frame_count']}"
66
+ ),
67
+ "spatial_code_format": code_info["spatial_code_format"],
68
+ "input_selection": code_info["input_selection"],
69
+ "frame_count": code_info["frame_count"],
70
+ "depth": code_info["depth"],
71
+ "tracking": code_info["tracking"],
72
+ "spatial_code_path": code_info["spatial_code_path"],
73
+ "scene": row["scene_name"],
74
+ "dataset": row.get("dataset"),
75
+ "question_id": row["id"],
76
+ "question_type": row["question_type"],
77
+ "question": row["question"],
78
+ "options": row.get("options"),
79
+ "full_prompt": prompt,
80
+ "rendered_prompt": answer["prompt_text"],
81
+ "answer_expected": row["ground_truth"],
82
+ "answer_given": answer["answer_text"],
83
+ "answer_raw": answer["answer_raw"],
84
+ "input_token_count": answer["input_token_count"],
85
+ "vision_input_shapes": answer["vision_input_shapes"],
86
+ "output_token_ids": answer["output_token_ids"],
87
+ "output_token_count": answer["output_token_count"],
88
+ "hit_token_limit": answer["hit_token_limit"],
89
+ "eos_token_ids": answer["eos_token_ids"],
90
+ "generation_seconds": answer["generation_seconds"],
91
+ "generation_config": answer["generation_config"],
92
+ "reasoning_text": answer.get("reasoning_text"),
93
+ "reasoning_raw": answer.get("reasoning_raw"),
94
+ "reasoning_token_ids": answer.get("reasoning_token_ids"),
95
+ "reasoning_token_count": answer.get("reasoning_token_count"),
96
+ "reasoning_hit_limit": answer.get("reasoning_hit_limit"),
97
+ "forced": answer.get("forced", False),
98
+ "forced_input_token_count": answer.get("forced_input_token_count"),
99
+ "metric": metric_name,
100
+ "score": score,
101
+ }
102
+
103
+
104
+ def write_question_result(
105
+ row, prompt, answer, metric_name, score, model, model_path, code_info, results_dir=None
106
+ ):
107
+ """Write one question's full, untruncated result record. Return (path, record)."""
108
+ record = _build_record(row, prompt, answer, metric_name, score, model, model_path, code_info)
109
+ root = results_dir_for(
110
+ model,
111
+ code_info["spatial_code_format"],
112
+ code_info["depth"],
113
+ code_info["tracking"],
114
+ code_info["input_selection"],
115
+ code_info["frame_count"],
116
+ results_dir,
117
+ )
118
+ scene_dir = root / record["scene"]
119
+ scene_dir.mkdir(parents=True, exist_ok=True)
120
+ path = scene_dir / f"{row['id']}.json"
121
+ with path.open("w", encoding="utf-8") as stream:
122
+ json.dump(record, stream, indent=1)
123
+ return path, record
124
+
125
+
126
+ def run(
127
+ model,
128
+ spatial_code_format=DEFAULT_SPATIAL_CODE_FORMAT,
129
+ input_selection=DEFAULT_INPUT_SELECTION,
130
+ frame_count=FRAMES_PER_VIDEO,
131
+ depth=DEFAULT_DEPTH,
132
+ tracking=DEFAULT_TRACKING,
133
+ scene=None,
134
+ scenes=None,
135
+ limit=None,
136
+ device="cuda",
137
+ jsonl_path=None,
138
+ results_dir=None,
139
+ write_results=True,
140
+ adapter=None,
141
+ reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
142
+ force_budget=MAX_NEW_TOKENS,
143
+ ):
144
+ """Answer every matching question with one model, given its scene's spatial code as
145
+ text (no video frames). Each question's full record is written to its own JSON file
146
+ as soon as it is answered (unless ``write_results=False``).
147
+
148
+ Uses ``adapter.answer_extended`` (a large ``reasoning_budget`` first pass, with a
149
+ short forced second call only if the model doesn't conclude within it) as the
150
+ standing default protocol -- not harness.A's fixed 16-token budget -- since working
151
+ through a full spatial-code JSON before answering benefits from more room than a
152
+ short visual caption does.
153
+
154
+ Pass a pre-loaded ``adapter`` (as harness.B.launch's persistent per-GPU workers do)
155
+ to reuse one already-loaded model across many calls; the caller then owns unloading
156
+ it. Without one, ``run`` loads and unloads its own adapter, same as harness.A.
157
+ """
158
+ rows = load_questions(jsonl_path, scene, scenes, limit)
159
+ if not rows:
160
+ return []
161
+ owns_adapter = adapter is None
162
+ if owns_adapter:
163
+ adapter = vlm_models.get_adapter(model)
164
+ adapter.load_model(device)
165
+ code_cache = {}
166
+ results = []
167
+ try:
168
+ for row in rows:
169
+ scene_id = row["scene_name"]
170
+ if scene_id not in code_cache:
171
+ code, path = spatial_codes.load_spatial_code(
172
+ scene_id, depth, input_selection, tracking, frame_count, spatial_code_format
173
+ )
174
+ code_cache[scene_id] = {"code": code, "path": path}
175
+ cached = code_cache[scene_id]
176
+ prompt = code_prompts.build_prompt(
177
+ cached["code"], row["question_type"], row["question"], row.get("options")
178
+ )
179
+ answer = adapter.answer_extended(
180
+ [], prompt, reasoning_budget=reasoning_budget, force_budget=force_budget
181
+ )
182
+ doc = {"question_type": row["question_type"], "ground_truth": row["ground_truth"]}
183
+ score_doc = vsi_official_eval.vsibench_process_results(
184
+ doc, [answer["answer_text"]]
185
+ )["vsibench_score"]
186
+ metric_name, score = _scalar_score(row["question_type"], score_doc)
187
+ code_info = {
188
+ "spatial_code_format": spatial_code_format,
189
+ "input_selection": input_selection,
190
+ "frame_count": frame_count,
191
+ "depth": depth,
192
+ "tracking": tracking,
193
+ "spatial_code_path": cached["path"],
194
+ }
195
+ if write_results:
196
+ path, record = write_question_result(
197
+ row, prompt, answer, metric_name, score, model, adapter.model_path,
198
+ code_info, results_dir,
199
+ )
200
+ else:
201
+ path = None
202
+ record = _build_record(
203
+ row, prompt, answer, metric_name, score, model, adapter.model_path, code_info
204
+ )
205
+ record["result_path"] = str(path) if path else None
206
+ results.append(record)
207
+ finally:
208
+ if owns_adapter:
209
+ adapter.unload()
210
+ return results
211
+
212
+
213
+ def main():
214
+ parser = argparse.ArgumentParser()
215
+ parser.add_argument("--model", required=True, choices=vlm_models.available_models())
216
+ parser.add_argument("--scene", default=None, help="restrict to one VSI-Bench scene")
217
+ parser.add_argument(
218
+ "--spatial-code-format", default=DEFAULT_SPATIAL_CODE_FORMAT,
219
+ choices=SPATIAL_CODE_FORMATS, dest="spatial_code_format",
220
+ )
221
+ parser.add_argument(
222
+ "--input-selection", default=DEFAULT_INPUT_SELECTION,
223
+ choices=INPUT_SELECTIONS, dest="input_selection",
224
+ )
225
+ parser.add_argument("--frames", type=int, default=FRAMES_PER_VIDEO)
226
+ parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS)
227
+ parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES)
228
+ parser.add_argument("--limit", type=int, default=None, help="cap the number of questions")
229
+ parser.add_argument("--device", default="cuda")
230
+ parser.add_argument(
231
+ "--results-dir", default=None,
232
+ help="override the default results/B/<model>/<format>/<depth>/<tracking>/<input>/<frames> root",
233
+ )
234
+ parser.add_argument(
235
+ "--no-write", action="store_true",
236
+ help="skip writing per-question JSON files; print/score only",
237
+ )
238
+ parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
239
+ parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
240
+ args = parser.parse_args()
241
+ if args.frames < 1:
242
+ parser.error("--frames must be positive")
243
+ if args.reasoning_budget < 1:
244
+ parser.error("--reasoning-budget must be positive")
245
+ if args.force_budget < 1:
246
+ parser.error("--force-budget must be positive")
247
+
248
+ results = run(
249
+ args.model,
250
+ spatial_code_format=args.spatial_code_format,
251
+ input_selection=args.input_selection,
252
+ frame_count=args.frames,
253
+ depth=args.depth,
254
+ tracking=args.tracking,
255
+ scene=args.scene,
256
+ limit=args.limit,
257
+ device=args.device,
258
+ results_dir=args.results_dir,
259
+ write_results=not args.no_write,
260
+ reasoning_budget=args.reasoning_budget,
261
+ force_budget=args.force_budget,
262
+ )
263
+
264
+ for result in results:
265
+ print(
266
+ f"[{result['scene']}#{result['question_id']}] {result['question_type']}: "
267
+ f"pred={result['answer_given']!r} gt={result['answer_expected']!r} "
268
+ f"score={result['score']} ({result['generation_seconds']:.2f}s) -> "
269
+ f"{result['result_path']}"
270
+ )
271
+ if results:
272
+ mean_score = sum(r["score"] for r in results) / len(results)
273
+ total_seconds = sum(r["generation_seconds"] for r in results)
274
+ print(
275
+ f"\n{len(results)} questions, mean vsibench_score={mean_score:.4f}, "
276
+ f"total generation time={total_seconds:.1f}s"
277
+ )
278
+
279
+
280
+ if __name__ == "__main__":
281
+ main()
harness/B/spatial_codes.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load one scene's on-disk spatial code (explicit or compact) as plain JSON.
2
+
3
+ No solver-side adaptation (symbolic.adapters.adapt_spatial_code): the model is shown
4
+ literally the same file encoder/geometric.py wrote to disk -- schema legend included --
5
+ not a derived, answer-oriented shape a solver would compute from it.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from pathlib import Path
12
+
13
+ from encoder.config import spatial_code_path
14
+
15
+ from harness.B import SPATIAL_CODE_FORMATS
16
+
17
+
18
+ def load_spatial_code(scene, depth, input_selection, tracking, frame_count, spatial_code_format):
19
+ """Return (spatial code dict, path it was loaded from)."""
20
+ if spatial_code_format not in SPATIAL_CODE_FORMATS:
21
+ raise ValueError(
22
+ f"unknown spatial-code format {spatial_code_format!r}; "
23
+ f"expected one of {SPATIAL_CODE_FORMATS}"
24
+ )
25
+ path = spatial_code_path(
26
+ scene, depth, input_selection, tracking, frame_count, spatial_code_format
27
+ )
28
+ if not Path(path).is_file():
29
+ raise FileNotFoundError(f"no spatial code found for scene {scene!r} at {path}")
30
+ with open(path, encoding="utf-8") as stream:
31
+ return json.load(stream), path
harness/B/sweep.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sweep any set of models x spatial-code-formats x depths x trackings x
2
+ input-selections x frame-counts.
3
+
4
+ Every (model, spatial_code_format, depth, tracking, input_selection, frame_count)
5
+ 6-tuple in the sweep is run through ``harness.B.launch.launch`` in turn, so each
6
+ combination individually saturates every visible GPU before the next one starts.
7
+ Depth/tracking default to this workspace's single shipped production config
8
+ (DEFAULT_DEPTH/DEFAULT_TRACKING) when --depths/--trackings aren't given, but are real
9
+ sweepable axes like every other dimension here -- pass --depths all / --trackings all
10
+ (or an explicit comma list) to sweep them too.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ from pathlib import Path
17
+ import sys
18
+
19
+ HERE = Path(__file__).resolve().parent
20
+ WORKSPACE_ROOT = HERE.parent.parent
21
+ if str(WORKSPACE_ROOT) not in sys.path:
22
+ sys.path.insert(0, str(WORKSPACE_ROOT))
23
+
24
+ from harness.A import models as vlm_models # noqa: E402
25
+ from harness.A.sweep import _parse_csv_choice, _parse_frame_counts # noqa: E402
26
+ from harness.B import ( # noqa: E402
27
+ DEFAULT_DEPTH,
28
+ DEFAULT_TRACKING,
29
+ DEPTH_VARIANTS,
30
+ INPUT_SELECTIONS,
31
+ SPATIAL_CODE_FORMATS,
32
+ TRACKING_MODES,
33
+ )
34
+ from harness.B import launch as harness_launch # noqa: E402
35
+
36
+
37
+ def build_plan(models, spatial_code_formats, input_selections, frame_counts, depths, trackings):
38
+ """Return every (model, spatial_code_format, depth, tracking, input_selection,
39
+ frame_count) 6-tuple in the sweep, in a stable, cheapest-first-ish order (frame
40
+ count sorted first)."""
41
+ return [
42
+ (model, spatial_code_format, depth, tracking, input_selection, frame_count)
43
+ for frame_count in sorted(frame_counts)
44
+ for model in models
45
+ for spatial_code_format in spatial_code_formats
46
+ for depth in depths
47
+ for tracking in trackings
48
+ for input_selection in input_selections
49
+ ]
50
+
51
+
52
+ def sweep(
53
+ models, spatial_code_formats, input_selections, frame_counts, selected_scenes,
54
+ depths=(DEFAULT_DEPTH,), trackings=(DEFAULT_TRACKING,), results_dir=None, rebuild=False,
55
+ ):
56
+ """Run every sweep combination across all visible GPUs."""
57
+ plan = build_plan(models, spatial_code_formats, input_selections, frame_counts, depths, trackings)
58
+ for index, (model, spatial_code_format, depth, tracking, input_selection, frame_count) in enumerate(
59
+ plan, start=1
60
+ ):
61
+ print(
62
+ f"=== sweep {index}/{len(plan)}: "
63
+ f"{model}/{spatial_code_format}/{depth}/{tracking}/{input_selection}/{frame_count} ===",
64
+ flush=True,
65
+ )
66
+ harness_launch.launch(
67
+ model, spatial_code_format, input_selection, frame_count, selected_scenes,
68
+ depth=depth, tracking=tracking, results_dir=results_dir, rebuild=rebuild,
69
+ )
70
+
71
+
72
+ def main():
73
+ parser = argparse.ArgumentParser()
74
+ parser.add_argument("scene", nargs="?")
75
+ parser.add_argument(
76
+ "--scenes", help="comma-separated scenes (cannot be combined with positional scene)"
77
+ )
78
+ parser.add_argument(
79
+ "--models", required=True,
80
+ help=f"comma-separated models (or 'all'); one of {vlm_models.available_models()}",
81
+ )
82
+ parser.add_argument(
83
+ "--spatial-code-formats", required=True, dest="spatial_code_formats",
84
+ help=f"comma-separated formats (or 'all'); one of {SPATIAL_CODE_FORMATS}",
85
+ )
86
+ parser.add_argument(
87
+ "--input-selections", required=True, dest="input_selections",
88
+ help=f"comma-separated selections (or 'all'); one of {INPUT_SELECTIONS}",
89
+ )
90
+ parser.add_argument(
91
+ "--frames", required=True, help="comma-separated frame counts, e.g. 16,32,64"
92
+ )
93
+ parser.add_argument(
94
+ "--depths", default=DEFAULT_DEPTH,
95
+ help=f"comma-separated depths (or 'all'); one of {DEPTH_VARIANTS}",
96
+ )
97
+ parser.add_argument(
98
+ "--trackings", default=DEFAULT_TRACKING,
99
+ help=f"comma-separated tracking modes (or 'all'); one of {TRACKING_MODES}",
100
+ )
101
+ parser.add_argument("--results-dir", default=None)
102
+ parser.add_argument("--rebuild", action="store_true")
103
+ args = parser.parse_args()
104
+ if args.scene and args.scenes:
105
+ parser.error("positional scene and --scenes cannot be used together")
106
+
107
+ try:
108
+ models = _parse_csv_choice(args.models, vlm_models.available_models(), "--models")
109
+ spatial_code_formats = _parse_csv_choice(
110
+ args.spatial_code_formats, SPATIAL_CODE_FORMATS, "--spatial-code-formats"
111
+ )
112
+ input_selections = _parse_csv_choice(
113
+ args.input_selections, INPUT_SELECTIONS, "--input-selections"
114
+ )
115
+ depths = _parse_csv_choice(args.depths, DEPTH_VARIANTS, "--depths")
116
+ trackings = _parse_csv_choice(args.trackings, TRACKING_MODES, "--trackings")
117
+ frame_counts = _parse_frame_counts(args.frames)
118
+ except ValueError as exc:
119
+ parser.error(str(exc))
120
+
121
+ if args.scenes is not None:
122
+ selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
123
+ if not selected:
124
+ parser.error("--scenes must contain at least one scene")
125
+ selected = list(dict.fromkeys(selected))
126
+ else:
127
+ from harness.A.launch import scenes
128
+
129
+ selected = [args.scene] if args.scene else scenes()
130
+
131
+ sweep(
132
+ models, spatial_code_formats, input_selections, frame_counts, selected,
133
+ depths=depths, trackings=trackings,
134
+ results_dir=args.results_dir, rebuild=args.rebuild,
135
+ )
136
+
137
+
138
+ if __name__ == "__main__":
139
+ main()
harness/C/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (2.26 kB). View file
 
harness/C/__pycache__/launch.cpython-311.pyc ADDED
Binary file (12.8 kB). View file
 
harness/C/__pycache__/prompts.cpython-311.pyc ADDED
Binary file (2.36 kB). View file
 
harness/C/__pycache__/run.cpython-311.pyc ADDED
Binary file (14.7 kB). View file
 
harness/C/__pycache__/sweep.cpython-311.pyc ADDED
Binary file (7.8 kB). View file
 
harness/C/launch.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Keep every visible GPU busy with persistent harness-C inference workers.
2
+
3
+ Same shape as ``harness.A.launch`` / ``harness.B.launch``: one persistent worker
4
+ process per visible GPU, pulling scenes off a shared queue, each loading its model
5
+ exactly once and reusing it for every scene it's assigned (via ``run.run(...,
6
+ adapter=...)``). One invocation covers one (model, spatial_code_format,
7
+ input_selection, frame_count) quadruple across every requested scene; sweep multiple
8
+ quadruples via harness.C.sweep.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import importlib.util
15
+ import multiprocessing as mp
16
+ import os
17
+ from pathlib import Path
18
+ import sys
19
+ import traceback
20
+
21
+ HERE = Path(__file__).resolve().parent
22
+ WORKSPACE_ROOT = HERE.parent.parent
23
+ if str(WORKSPACE_ROOT) not in sys.path:
24
+ sys.path.insert(0, str(WORKSPACE_ROOT))
25
+
26
+ from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402
27
+ from harness.A import models as vlm_models # noqa: E402
28
+ from harness.A.launch import scenes # noqa: E402
29
+ from harness.B import ( # noqa: E402
30
+ DEFAULT_DEPTH,
31
+ DEFAULT_INPUT_SELECTION,
32
+ DEFAULT_SPATIAL_CODE_FORMAT,
33
+ DEFAULT_TRACKING,
34
+ DEPTH_VARIANTS,
35
+ INPUT_SELECTIONS,
36
+ SPATIAL_CODE_FORMATS,
37
+ TRACKING_MODES,
38
+ )
39
+ from harness.C import FRAMES_PER_VIDEO # noqa: E402
40
+ from inference.launch import available_cpu_count, visible_gpus # noqa: E402
41
+
42
+
43
+ def _load_run_module():
44
+ spec = importlib.util.spec_from_file_location("_harness_C_run", HERE / "run.py")
45
+ module = importlib.util.module_from_spec(spec)
46
+ sys.modules[spec.name] = module
47
+ spec.loader.exec_module(module)
48
+ return module
49
+
50
+
51
+ def _worker(
52
+ tasks, results, model, spatial_code_format, input_selection, frame_count, depth, tracking,
53
+ results_dir, gpu, cpu_threads, reasoning_budget, force_budget,
54
+ ):
55
+ if gpu is not None:
56
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
57
+ for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
58
+ os.environ[variable] = str(cpu_threads)
59
+ import cv2
60
+
61
+ cv2.setNumThreads(cpu_threads)
62
+ run = _load_run_module()
63
+ adapter = None
64
+ load_error = None
65
+ try:
66
+ adapter = vlm_models.get_adapter(model)
67
+ adapter.load_model("cuda:0" if gpu is not None else "cpu")
68
+ except Exception:
69
+ load_error = traceback.format_exc()
70
+ while True:
71
+ scene = tasks.get()
72
+ if scene is None:
73
+ return
74
+ if load_error is not None:
75
+ results.put((scene, False, load_error))
76
+ continue
77
+ try:
78
+ answered = run.run(
79
+ model,
80
+ spatial_code_format=spatial_code_format,
81
+ input_selection=input_selection,
82
+ frame_count=frame_count,
83
+ depth=depth,
84
+ tracking=tracking,
85
+ scene=scene,
86
+ results_dir=results_dir,
87
+ adapter=adapter,
88
+ reasoning_budget=reasoning_budget,
89
+ force_budget=force_budget,
90
+ )
91
+ mean_score = (
92
+ sum(r["score"] for r in answered) / len(answered) if answered else None
93
+ )
94
+ results.put(
95
+ (scene, True, f"{len(answered)} question(s), mean_score={mean_score}")
96
+ )
97
+ except Exception:
98
+ results.put((scene, False, traceback.format_exc()))
99
+
100
+
101
+ def launch(
102
+ model, spatial_code_format, input_selection, frame_count, selected,
103
+ depth=DEFAULT_DEPTH, tracking=DEFAULT_TRACKING, results_dir=None, rebuild=False,
104
+ reasoning_budget=EXTENDED_MAX_NEW_TOKENS, force_budget=MAX_NEW_TOKENS,
105
+ ):
106
+ """Answer every question for ``selected`` scenes, sharded across every visible GPU."""
107
+ condition = f"{model}/{spatial_code_format}/{depth}/{tracking}/{input_selection}/{frame_count}"
108
+ run = _load_run_module()
109
+ root = run.results_dir_for(
110
+ model, spatial_code_format, depth, tracking, input_selection, frame_count, results_dir
111
+ )
112
+ pending = []
113
+ completed = 0
114
+ for scene in selected:
115
+ rows = run.load_questions(scene=scene)
116
+ answered = all((root / scene / f"{row['id']}.json").is_file() for row in rows)
117
+ if answered and not rebuild:
118
+ completed += 1
119
+ print(f"[{condition} {completed}/{len(selected)}] {scene}: skipped", flush=True)
120
+ else:
121
+ pending.append(scene)
122
+ if not pending:
123
+ print(f"[{condition}] DONE: {len(selected)} ok, 0 failed")
124
+ return
125
+
126
+ gpus = visible_gpus()
127
+ worker_count = min(len(pending), len(gpus) if gpus else 1)
128
+ assignments = gpus[:worker_count] if gpus else [None]
129
+ cpu_count = available_cpu_count()
130
+ cpu_threads = max(1, cpu_count // worker_count)
131
+ print(
132
+ f"[{condition}] starting {worker_count} persistent worker(s); "
133
+ f"GPUs={assignments}; CPU threads/worker={cpu_threads}",
134
+ flush=True,
135
+ )
136
+
137
+ context = mp.get_context("spawn")
138
+ tasks, results = context.Queue(), context.Queue()
139
+ for scene in pending:
140
+ tasks.put(scene)
141
+ for _ in range(worker_count):
142
+ tasks.put(None)
143
+ workers = [
144
+ context.Process(
145
+ target=_worker,
146
+ args=(
147
+ tasks, results, model, spatial_code_format, input_selection, frame_count,
148
+ depth, tracking, results_dir, gpu, cpu_threads, reasoning_budget, force_budget,
149
+ ),
150
+ )
151
+ for gpu in assignments
152
+ ]
153
+ for worker in workers:
154
+ worker.start()
155
+ failed = []
156
+ for finished in range(1, len(pending) + 1):
157
+ scene, ok, detail = results.get()
158
+ if not ok:
159
+ failed.append(scene)
160
+ print(
161
+ f"[{condition} {completed + finished}/{len(selected)}] {scene}: "
162
+ f"{'done' if ok else 'FAILED'}\n{detail}",
163
+ flush=True,
164
+ )
165
+ for worker in workers:
166
+ worker.join()
167
+ print(
168
+ f"[{condition}] DONE: {len(pending) - len(failed)} answered, {completed} skipped, "
169
+ f"{len(failed)} failed"
170
+ )
171
+ if failed:
172
+ raise SystemExit(1)
173
+
174
+
175
+ def main():
176
+ parser = argparse.ArgumentParser()
177
+ parser.add_argument("scene", nargs="?")
178
+ parser.add_argument(
179
+ "--scenes", help="comma-separated scenes (cannot be combined with positional scene)"
180
+ )
181
+ parser.add_argument("--model", required=True, choices=vlm_models.available_models())
182
+ parser.add_argument(
183
+ "--spatial-code-format", default=DEFAULT_SPATIAL_CODE_FORMAT,
184
+ choices=SPATIAL_CODE_FORMATS, dest="spatial_code_format",
185
+ )
186
+ parser.add_argument(
187
+ "--input-selection", default=DEFAULT_INPUT_SELECTION,
188
+ choices=INPUT_SELECTIONS, dest="input_selection",
189
+ )
190
+ parser.add_argument("--frames", type=int, default=FRAMES_PER_VIDEO)
191
+ parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS)
192
+ parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES)
193
+ parser.add_argument("--results-dir", default=None)
194
+ parser.add_argument("--rebuild", action="store_true")
195
+ parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
196
+ parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
197
+ args = parser.parse_args()
198
+ if args.scene and args.scenes:
199
+ parser.error("positional scene and --scenes cannot be used together")
200
+ if args.scenes is not None:
201
+ selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
202
+ if not selected:
203
+ parser.error("--scenes must contain at least one scene")
204
+ selected = list(dict.fromkeys(selected))
205
+ else:
206
+ selected = [args.scene] if args.scene else scenes()
207
+ if args.frames < 1:
208
+ parser.error("--frames must be positive")
209
+ if args.reasoning_budget < 1:
210
+ parser.error("--reasoning-budget must be positive")
211
+ if args.force_budget < 1:
212
+ parser.error("--force-budget must be positive")
213
+ launch(
214
+ args.model, args.spatial_code_format, args.input_selection, args.frames, selected,
215
+ depth=args.depth, tracking=args.tracking, results_dir=args.results_dir, rebuild=args.rebuild,
216
+ reasoning_budget=args.reasoning_budget, force_budget=args.force_budget,
217
+ )
218
+
219
+
220
+ if __name__ == "__main__":
221
+ main()
harness/C/prompts.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Combined video-frames + spatial-code-as-text prompt construction.
2
+
3
+ Reuses harness.A.prompts's exact question-type split and post-prompts verbatim. The
4
+ returned text becomes the ONE trailing content item passed to
5
+ harness.A.models._numbered_content(frames, this_text) -- since that helper already puts
6
+ every numbered frame image first and appends a single text block last, the resulting
7
+ model input order is exactly: frames (numbered) -> spatial code text -> question.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+
14
+ from harness.A.prompts import (
15
+ MCA_POST_PROMPT,
16
+ MCA_QUESTION_TYPES,
17
+ NA_POST_PROMPT,
18
+ NA_QUESTION_TYPES,
19
+ PRE_PROMPT as FRAMES_PRE_PROMPT,
20
+ )
21
+ from harness.B.prompts import CODE_DESCRIPTION
22
+
23
+ # Built by literally concatenating harness.A's frames sentence with harness.B's spatial
24
+ # code sentence (not independently reworded) -- so a reviewer can see the frames-only,
25
+ # code-only, and frames+code context lines never describe the same content in different
26
+ # words. This is the ONE deliberate difference from B's context line (mentioning frames
27
+ # at all); everything describing the spatial code itself is the identical CODE_DESCRIPTION
28
+ # string B uses.
29
+ PRE_PROMPT = FRAMES_PRE_PROMPT + " Also provided is a spatial code: " + CODE_DESCRIPTION
30
+
31
+
32
+ def build_prompt(spatial_code, question_type, question, options=None):
33
+ """Return the full trailing text block: context line, the spatial code itself, the
34
+ question, and the same VSI-Bench post-prompt harness.A uses for the same
35
+ question_type. Frames themselves are prepended separately by the caller via
36
+ harness.A.models._numbered_content."""
37
+ code_text = json.dumps(spatial_code, indent=1)
38
+ if question_type in NA_QUESTION_TYPES:
39
+ return "\n".join([PRE_PROMPT, code_text, question, NA_POST_PROMPT])
40
+ if question_type in MCA_QUESTION_TYPES:
41
+ if not options:
42
+ raise ValueError(f"question_type {question_type!r} requires options")
43
+ options_block = "Options:\n" + "\n".join(options)
44
+ return "\n".join([PRE_PROMPT, code_text, question, options_block, MCA_POST_PROMPT])
45
+ raise ValueError(
46
+ f"unknown question_type {question_type!r}; "
47
+ f"expected one of {MCA_QUESTION_TYPES + NA_QUESTION_TYPES}"
48
+ )
harness/D/__pycache__/launch.cpython-311.pyc ADDED
Binary file (12.3 kB). View file
 
harness/D/__pycache__/prompts.cpython-311.pyc ADDED
Binary file (2.13 kB). View file
 
harness/D/__pycache__/run.cpython-311.pyc ADDED
Binary file (12.2 kB). View file
 
harness/D/__pycache__/spatial_codes.cpython-311.pyc ADDED
Binary file (1.91 kB). View file
 
harness/D/__pycache__/symbolic_eval.cpython-311.pyc ADDED
Binary file (7.7 kB). View file
 
harness/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (275 Bytes). View file
 
tests/test_B/__init__.py ADDED
File without changes
tests/test_B/__pycache__/test_launch.cpython-311-pytest-8.3.5.pyc ADDED
Binary file (7.03 kB). View file
 
tests/test_B/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc ADDED
Binary file (20.2 kB). View file
 
tests/test_B/__pycache__/test_spatial_codes.cpython-311-pytest-8.3.5.pyc ADDED
Binary file (6.99 kB). View file
 
tests/test_B/conftest.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared import setup for harness.B tests."""
2
+
3
+ from pathlib import Path
4
+ import sys
5
+
6
+ ROOT = Path(__file__).resolve().parents[2]
7
+ if str(ROOT) not in sys.path:
8
+ sys.path.insert(0, str(ROOT))
9
+
10
+
11
+ def pytest_configure(config):
12
+ config.option.importmode = "importlib"
tests/test_B/test_init.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/B/__init__.py -- shared config constants."""
2
+
3
+ from harness import A, B
4
+
5
+
6
+ def test_spatial_code_formats_match_the_two_on_disk_schemas():
7
+ assert B.SPATIAL_CODE_FORMATS == ("explicit", "compact")
8
+ assert B.DEFAULT_SPATIAL_CODE_FORMAT in B.SPATIAL_CODE_FORMATS
9
+
10
+
11
+ def test_input_selections_match_harness_a_vocabulary():
12
+ assert B.INPUT_SELECTIONS == A.FRAME_SELECTIONS
13
+ assert B.DEFAULT_INPUT_SELECTION in B.INPUT_SELECTIONS
14
+
15
+
16
+ def test_reuses_harness_a_model_paths_and_generation_protocol():
17
+ assert B.MODEL_PATHS is A.MODEL_PATHS
18
+ assert B.MAX_NEW_TOKENS == A.MAX_NEW_TOKENS
19
+ assert B.DO_SAMPLE == A.DO_SAMPLE
20
+ assert B.TEMPERATURE == A.TEMPERATURE
21
+
22
+
23
+ def test_results_dir_defaults_under_workspace_results():
24
+ assert B.RESULTS_DIR == B.WORKSPACE_ROOT / "results" / "B"
25
+
26
+
27
+ def test_depth_and_tracking_reuse_encoder_config_vocabulary():
28
+ from encoder.config import DEPTH_VARIANTS, TRACKING_MODES
29
+
30
+ assert B.DEPTH_VARIANTS == DEPTH_VARIANTS
31
+ assert B.TRACKING_MODES == TRACKING_MODES
32
+ assert B.DEFAULT_DEPTH in B.DEPTH_VARIANTS
33
+ assert B.DEFAULT_TRACKING in B.TRACKING_MODES
tests/test_B/test_launch.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/B/launch.py -- multi-GPU scene sharding across workers."""
2
+
3
+ from harness.A.run import load_questions as harness_a_load_questions
4
+ from harness.B import launch
5
+
6
+
7
+ def test_launcher_imports():
8
+ assert callable(launch.main)
9
+
10
+
11
+ def test_launch_skips_scene_already_fully_answered(tmp_path, capsys):
12
+ scene = "13c3e046d7"
13
+ rows = harness_a_load_questions(scene=scene)
14
+ assert rows, "fixture scene must have real questions in the VSI-Bench manifest"
15
+
16
+ scene_dir = tmp_path / scene
17
+ scene_dir.mkdir()
18
+ for row in rows:
19
+ (scene_dir / f"{row['id']}.json").write_text("{}")
20
+
21
+ launch.launch("qwen3.5-2b", "explicit", "selective", 64, [scene], results_dir=tmp_path)
22
+
23
+ output = capsys.readouterr().out
24
+ assert "skipped" in output
25
+ assert "DONE: 1 ok, 0 failed" in output
26
+
27
+
28
+ def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch):
29
+ scene = "13c3e046d7"
30
+ rows = harness_a_load_questions(scene=scene)
31
+ scene_dir = tmp_path / scene
32
+ scene_dir.mkdir()
33
+ for row in rows:
34
+ (scene_dir / f"{row['id']}.json").write_text("{}")
35
+
36
+ monkeypatch.setattr(launch, "visible_gpus", lambda: [])
37
+ monkeypatch.setattr(
38
+ launch.mp, "get_context",
39
+ lambda *_: (_ for _ in ()).throw(RuntimeError("rebuild correctly reached worker dispatch")),
40
+ )
41
+ try:
42
+ launch.launch(
43
+ "qwen3.5-2b", "explicit", "selective", 64, [scene],
44
+ results_dir=tmp_path, rebuild=True,
45
+ )
46
+ except RuntimeError as exc:
47
+ assert "rebuild correctly reached worker dispatch" in str(exc)
48
+ else:
49
+ raise AssertionError("expected rebuild to force scene into the pending path")
tests/test_B/test_sweep.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/B/sweep.py -- multi-config sweep planning."""
2
+
3
+ import pytest
4
+
5
+ from harness.A import models as vlm_models
6
+ from harness.B import sweep
7
+
8
+
9
+ def test_build_plan_covers_every_combination():
10
+ plan = sweep.build_plan(
11
+ ["qwen3.5-2b", "qwen3.5-4b"], ["explicit", "compact"], ["uniform", "selective"],
12
+ [16, 32], ["metric"], ["tracking"],
13
+ )
14
+ assert len(plan) == 2 * 2 * 2 * 2
15
+ assert ("qwen3.5-2b", "explicit", "metric", "tracking", "uniform", 16) in plan
16
+ assert ("qwen3.5-4b", "compact", "metric", "tracking", "selective", 32) in plan
17
+
18
+
19
+ def test_build_plan_sweeps_depth_and_tracking_too():
20
+ plan = sweep.build_plan(
21
+ ["qwen3.5-2b"], ["explicit"], ["uniform"], [16],
22
+ ["metric", "relative"], ["tracking", "no tracking"],
23
+ )
24
+ assert len(plan) == 4
25
+ assert ("qwen3.5-2b", "explicit", "relative", "no tracking", "uniform", 16) in plan
26
+
27
+
28
+ def test_build_plan_orders_by_frame_count_first():
29
+ plan = sweep.build_plan(
30
+ ["qwen3.5-2b"], ["explicit"], ["uniform"], [64, 16, 32], ["metric"], ["tracking"]
31
+ )
32
+ assert [frame_count for *_rest, frame_count in plan] == [16, 32, 64]
33
+
34
+
35
+ def test_build_plan_with_all_registered_models():
36
+ plan = sweep.build_plan(
37
+ list(vlm_models.available_models()), ["explicit"], ["uniform"], [16],
38
+ ["metric"], ["tracking"],
39
+ )
40
+ assert len(plan) == len(vlm_models.available_models())
41
+
42
+
43
+ def test_sweep_parser_rejects_unknown_spatial_code_format():
44
+ with pytest.raises(ValueError):
45
+ sweep._parse_csv_choice("bogus", ("explicit", "compact"), "--spatial-code-formats")
46
+
47
+
48
+ def test_sweep_parser_rejects_unknown_depth():
49
+ with pytest.raises(ValueError):
50
+ sweep._parse_csv_choice("bogus", sweep.DEPTH_VARIANTS, "--depths")
51
+
52
+
53
+ def test_sweep_parser_rejects_unknown_tracking():
54
+ with pytest.raises(ValueError):
55
+ sweep._parse_csv_choice("bogus", sweep.TRACKING_MODES, "--trackings")
tests/test_C/__init__.py ADDED
File without changes
tests/test_C/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (144 Bytes). View file
 
tests/test_C/__pycache__/conftest.cpython-311-pytest-8.3.5.pyc ADDED
Binary file (941 Bytes). View file