AntonioJun commited on
Commit
72c2042
·
verified ·
1 Parent(s): 529f0a2

Replace harness with local workspace contents

Browse files
harness/A/__init__.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(os.environ.get("VSI_HARNESS_RESULTS_DIR", "/root/results/A"))
24
+
25
+ # Same two selection strategies and vocabulary as inference.SAM3_FRAME_SELECTIONS:
26
+ # "uniform" (evenly spaced indices) or "selective" (the quality/redundancy/motion-
27
+ # filtered keyframe selector in inference.adapters, algorithm 5 by default).
28
+ FRAME_SELECTIONS = ("uniform", "selective")
29
+ DEFAULT_FRAME_SELECTION = "uniform"
30
+ FRAMES_PER_VIDEO = int(os.environ.get("VSI_HARNESS_FRAMES_PER_VIDEO", "32"))
31
+
32
+ # Fixed by the VSI-Bench protocol (vsibench.yaml generation_kwargs) -- not configurable
33
+ # per call, since comparing models under different decoding settings would be meaningless.
34
+ MAX_NEW_TOKENS = 16
35
+ TEMPERATURE = 0.0
36
+ DO_SAMPLE = False
37
+
38
+ # Thinking-protocol generation: a larger first-pass budget for the model
39
+ # to work through the input before answering, with a short forced second call only if it
40
+ # didn't conclude (hit the budget without emitting an end-of-sequence token) in that
41
+ # first pass. The forced call reuses MAX_NEW_TOKENS (16) -- the same short-answer budget
42
+ # the base protocol already uses -- since its whole job is to extract one terse answer,
43
+ # not to reason further.
44
+ EXTENDED_MAX_NEW_TOKENS = 2048
45
+ FORCE_ANSWER_PROMPT = "\nFinal answer:"
46
+
47
+ # Fixed experiment policy. Edit these two values to switch which question group
48
+ # receives which generation protocol; every VLM harness imports this one mapping.
49
+ QUESTION_PROTOCOLS = {
50
+ "numerical": "base",
51
+ "multiple_choice": "thinking",
52
+ }
53
+ PROTOCOLS = ("base", "thinking")
54
+
55
+ NUMERICAL_QUESTION_TYPES = frozenset(
56
+ {
57
+ "object_abs_distance",
58
+ "object_counting",
59
+ "object_size_estimation",
60
+ "room_size_estimation",
61
+ }
62
+ )
63
+ MULTIPLE_CHOICE_QUESTION_TYPES = frozenset(
64
+ {
65
+ "object_rel_direction_easy",
66
+ "object_rel_direction_medium",
67
+ "object_rel_direction_hard",
68
+ "object_rel_distance",
69
+ "route_planning",
70
+ "obj_appearance_order",
71
+ }
72
+ )
73
+
74
+
75
+ def question_group(question_type):
76
+ """Return the fixed experiment group for one VSI-Bench question type."""
77
+ if question_type in NUMERICAL_QUESTION_TYPES:
78
+ return "numerical"
79
+ if question_type in MULTIPLE_CHOICE_QUESTION_TYPES:
80
+ return "multiple_choice"
81
+ raise ValueError(f"unknown VSI-Bench question type {question_type!r}")
82
+
83
+
84
+ def protocol_for_question(question_type):
85
+ """Return the hardcoded protocol for one VSI-Bench question type."""
86
+ return QUESTION_PROTOCOLS[question_group(question_type)]
87
+
88
+
89
+ def resolve_protocol_budgets(parser, args):
90
+ """Validate budgets used only by questions mapped to thinking."""
91
+ requested_reasoning = args.reasoning_budget
92
+ requested_force = getattr(args, "force_budget", None)
93
+ if requested_reasoning is not None and requested_reasoning < 1:
94
+ parser.error("--reasoning-budget must be positive")
95
+ if requested_force is not None and requested_force < 1:
96
+ parser.error("--force-budget must be positive")
97
+ args.reasoning_budget = (
98
+ EXTENDED_MAX_NEW_TOKENS if requested_reasoning is None else requested_reasoning
99
+ )
100
+ if hasattr(args, "force_budget"):
101
+ args.force_budget = (
102
+ MAX_NEW_TOKENS if requested_force is None else requested_force
103
+ )
104
+
105
+
106
+ MODEL_PATHS = {
107
+ "qwen3.5-4b": MODELS_ROOT / "qwen3.5-4b",
108
+ "qwen3.5-2b": MODELS_ROOT / "qwen3.5-2b",
109
+ "internvl3.5-4b": MODELS_ROOT / "internvl3.5-4b",
110
+ "internvl3.5-2b": MODELS_ROOT / "internvl3.5-2b",
111
+ }
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,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 harness.A import resolve_protocol_budgets # noqa: E402
37
+ from inference.launch import available_cpu_count, visible_gpus # noqa: E402
38
+
39
+
40
+ def _load_run_module():
41
+ spec = importlib.util.spec_from_file_location("_harness_A_run", HERE / "run.py")
42
+ module = importlib.util.module_from_spec(spec)
43
+ sys.modules[spec.name] = module
44
+ spec.loader.exec_module(module)
45
+ return module
46
+
47
+
48
+ def scenes():
49
+ """Return unique VSI-Bench scenes in their original manifest order."""
50
+ with open(JSONL) as manifest:
51
+ return list(
52
+ dict.fromkeys(str(json.loads(line)["scene_name"]) for line in manifest)
53
+ )
54
+
55
+
56
+ def _worker(
57
+ tasks,
58
+ results,
59
+ model,
60
+ frame_selection,
61
+ frame_count,
62
+ video,
63
+ results_dir,
64
+ gpu,
65
+ cpu_threads,
66
+ extended,
67
+ reasoning_budget,
68
+ force_budget,
69
+ ):
70
+ if gpu is not None:
71
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
72
+ for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
73
+ os.environ[variable] = str(cpu_threads)
74
+ import cv2
75
+
76
+ cv2.setNumThreads(cpu_threads)
77
+ run = _load_run_module()
78
+ adapter = None
79
+ load_error = None
80
+ try:
81
+ adapter = vlm_models.get_adapter(model)
82
+ adapter.load_model("cuda:0" if gpu is not None else "cpu")
83
+ except Exception:
84
+ load_error = traceback.format_exc()
85
+ while True:
86
+ scene = tasks.get()
87
+ if scene is None:
88
+ return
89
+ if load_error is not None:
90
+ results.put((scene, False, load_error))
91
+ continue
92
+ try:
93
+ answered = run.run(
94
+ model,
95
+ frame_selection=frame_selection,
96
+ frame_count=frame_count,
97
+ video=video,
98
+ scene=scene,
99
+ results_dir=results_dir,
100
+ adapter=adapter,
101
+ extended=extended,
102
+ reasoning_budget=reasoning_budget,
103
+ force_budget=force_budget,
104
+ )
105
+ mean_score = (
106
+ sum(r["score"] for r in answered) / len(answered) if answered else None
107
+ )
108
+ results.put(
109
+ (scene, True, f"{len(answered)} question(s), mean_score={mean_score}")
110
+ )
111
+ except Exception:
112
+ results.put((scene, False, traceback.format_exc()))
113
+
114
+
115
+ def launch(
116
+ model,
117
+ frame_selection,
118
+ frame_count,
119
+ selected,
120
+ video=False,
121
+ results_dir=None,
122
+ rebuild=False,
123
+ extended=True,
124
+ reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
125
+ force_budget=MAX_NEW_TOKENS,
126
+ ):
127
+ """Answer every question for ``selected`` scenes, sharded across visible GPUs."""
128
+ if video:
129
+ frame_selection = "video"
130
+ frame_count = None
131
+ elif frame_count is None or frame_count < 1:
132
+ raise ValueError("frame_count must be positive in frames mode")
133
+ mode = "video" if video else f"{frame_selection}/{frame_count}"
134
+ condition = f"{model}/{mode}"
135
+ run = _load_run_module()
136
+ root = run.results_dir_for(model, None, frame_selection, frame_count, results_dir)
137
+ pending = []
138
+ completed = 0
139
+ for scene in selected:
140
+ rows = run.load_questions(scene=scene)
141
+ if not rows:
142
+ raise ValueError(
143
+ f"no questions found for scene {scene!r}; check the manifest/scene selection"
144
+ )
145
+ answered = all((root / scene / f"{row['id']}.json").is_file() for row in rows)
146
+ if answered and not rebuild:
147
+ completed += 1
148
+ print(
149
+ f"[{condition} {completed}/{len(selected)}] {scene}: skipped",
150
+ flush=True,
151
+ )
152
+ else:
153
+ pending.append(scene)
154
+ if not pending:
155
+ print(f"[{condition}] DONE: {len(selected)} ok, 0 failed")
156
+ return
157
+
158
+ gpus = visible_gpus()
159
+ worker_count = min(len(pending), len(gpus) if gpus else 1)
160
+ assignments = gpus[:worker_count] if gpus else [None]
161
+ cpu_count = available_cpu_count()
162
+ cpu_threads = max(1, cpu_count // worker_count)
163
+ print(
164
+ f"[{condition}] starting {worker_count} persistent worker(s); "
165
+ f"GPUs={assignments}; CPU threads/worker={cpu_threads}",
166
+ flush=True,
167
+ )
168
+
169
+ context = mp.get_context("spawn")
170
+ tasks, results = context.Queue(), context.Queue()
171
+ for scene in pending:
172
+ tasks.put(scene)
173
+ for _ in range(worker_count):
174
+ tasks.put(None)
175
+ workers = [
176
+ context.Process(
177
+ target=_worker,
178
+ args=(
179
+ tasks,
180
+ results,
181
+ model,
182
+ frame_selection,
183
+ frame_count,
184
+ video,
185
+ results_dir,
186
+ gpu,
187
+ cpu_threads,
188
+ extended,
189
+ reasoning_budget,
190
+ force_budget,
191
+ ),
192
+ )
193
+ for gpu in assignments
194
+ ]
195
+ for worker in workers:
196
+ worker.start()
197
+ failed = []
198
+ for finished in range(1, len(pending) + 1):
199
+ scene, ok, detail = results.get()
200
+ if not ok:
201
+ failed.append(scene)
202
+ print(
203
+ f"[{condition} {completed + finished}/{len(selected)}] {scene}: "
204
+ f"{'done' if ok else 'FAILED'}\n{detail}",
205
+ flush=True,
206
+ )
207
+ for worker in workers:
208
+ worker.join()
209
+ print(
210
+ f"[{condition}] DONE: {len(pending) - len(failed)} answered, {completed} skipped, "
211
+ f"{len(failed)} failed"
212
+ )
213
+ if failed:
214
+ raise SystemExit(1)
215
+
216
+
217
+ def main():
218
+ parser = argparse.ArgumentParser()
219
+ parser.add_argument("scene", nargs="?")
220
+ parser.add_argument(
221
+ "--scenes",
222
+ help="comma-separated scenes (cannot be combined with positional scene)",
223
+ )
224
+ parser.add_argument("--model", required=True, choices=vlm_models.available_models())
225
+ parser.add_argument(
226
+ "--frame-selection",
227
+ default=None,
228
+ choices=FRAME_SELECTIONS,
229
+ dest="frame_selection",
230
+ )
231
+ input_mode = parser.add_mutually_exclusive_group(required=True)
232
+ input_mode.add_argument("--frames", type=int)
233
+ input_mode.add_argument("--video", action="store_true")
234
+ parser.add_argument("--results-dir", default=None)
235
+ parser.add_argument("--rebuild", action="store_true")
236
+ parser.add_argument(
237
+ "--reasoning-budget",
238
+ type=int,
239
+ default=None,
240
+ help="thinking mode only (default: 2048)",
241
+ )
242
+ parser.add_argument(
243
+ "--force-budget",
244
+ type=int,
245
+ default=None,
246
+ help="thinking mode only (default: 16)",
247
+ )
248
+ args = parser.parse_args()
249
+ if args.scene and args.scenes:
250
+ parser.error("positional scene and --scenes cannot be used together")
251
+ if args.scenes is not None:
252
+ selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
253
+ if not selected:
254
+ parser.error("--scenes must contain at least one scene")
255
+ selected = list(dict.fromkeys(selected))
256
+ else:
257
+ selected = [args.scene] if args.scene else scenes()
258
+ if args.video:
259
+ if args.frame_selection is not None:
260
+ parser.error("--frame-selection cannot be used with --video")
261
+ else:
262
+ if args.frame_selection is None:
263
+ parser.error("--frame-selection is required with --frames")
264
+ if args.frames < 1:
265
+ parser.error("--frames must be positive")
266
+ resolve_protocol_budgets(parser, args)
267
+ launch(
268
+ args.model,
269
+ args.frame_selection,
270
+ args.frames,
271
+ selected,
272
+ video=args.video,
273
+ results_dir=args.results_dir,
274
+ rebuild=args.rebuild,
275
+ extended=True,
276
+ reasoning_budget=args.reasoning_budget,
277
+ force_budget=args.force_budget,
278
+ )
279
+
280
+
281
+ if __name__ == "__main__":
282
+ main()
harness/A/models.py ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Build one visual question from either sampled frames or a native video path.
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
+ if isinstance(frames, (str, Path)):
34
+ return [
35
+ {"type": "video", "video": str(frames)},
36
+ {"type": "text", "text": question},
37
+ ]
38
+ content = []
39
+ for index, frame in enumerate(frames, start=1):
40
+ content.append({"type": "text", "text": f"Frame {index}:"})
41
+ content.append({"type": "image", "image": frame})
42
+ content.append({"type": "text", "text": question})
43
+ return content
44
+
45
+
46
+ def _split_think(text):
47
+ """Split a thinking-mode generation into (think_content, answer_after_think).
48
+ Returns (None, text) when no closed think block is present -- the caller then
49
+ treats the whole text as reasoning that never concluded."""
50
+ if "</think>" in text:
51
+ think, _, answer = text.partition("</think>")
52
+ return think.replace("<think>", "").strip(), answer.strip()
53
+ return None, text
54
+
55
+
56
+ class VLMAdapter(ABC):
57
+ """Common interface implemented by every direct-inference VLM adapter."""
58
+
59
+ def __init__(self, model_path=None):
60
+ self.model_path = Path(model_path)
61
+ self.model = None
62
+ self.processor = None
63
+ self.device = None
64
+ self.dtype = None
65
+
66
+ @abstractmethod
67
+ def load_model(self, device="cuda"):
68
+ """Load model + processor weights once for repeated ``answer`` calls."""
69
+
70
+ @abstractmethod
71
+ def answer(self, frames, question, max_new_tokens=None):
72
+ """Return a full, untruncated record of one greedy-decoded response.
73
+
74
+ Every field a downstream result file needs is produced here, not reconstructed
75
+ later: the literal rendered prompt text, both the cleaned and fully raw decoded
76
+ response, the actual generated token ids/count, whether the token budget cut the
77
+ response off before a natural stop, and the exact generation config used.
78
+
79
+ ``max_new_tokens`` defaults to MAX_NEW_TOKENS (the VSI-Bench-standard 16-token
80
+ base protocol). Passing a larger cap runs this SAME single-generation,
81
+ no-rescue mechanism at a bigger truncation window -- the raw-budget arm
82
+ (analysis/preregistration.md): mimics the base protocol's exact behavior (no
83
+ forced second pass), just with more room before truncation.
84
+ """
85
+
86
+ @abstractmethod
87
+ def answer_extended(
88
+ self,
89
+ frames,
90
+ question,
91
+ reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
92
+ force_budget=MAX_NEW_TOKENS,
93
+ ):
94
+ """Same record shape as ``answer``, but with a much larger first-pass budget to
95
+ work through the input before answering. If the model does not conclude within
96
+ that budget (hits it without emitting an end-of-sequence token), a short forced
97
+ second call -- continuing the exact same generation, not a new turn -- asks for
98
+ the final answer directly. Always records the full, untruncated first-pass text
99
+ too (``reasoning_text``), even when a forced second call supplies the answer
100
+ actually used for scoring.
101
+ """
102
+
103
+ def unload(self):
104
+ """Free GPU memory so another adapter can be loaded in its place."""
105
+ import torch
106
+
107
+ self.model = None
108
+ self.processor = None
109
+ torch.cuda.empty_cache()
110
+
111
+
112
+ class _TransformersVLMAdapter(VLMAdapter):
113
+ """Shared load/generate path for HF ``AutoModelForImageTextToText`` checkpoints."""
114
+
115
+ chat_template_kwargs = {}
116
+
117
+ def load_model(self, device="cuda"):
118
+ import torch
119
+ from transformers import AutoModelForImageTextToText, AutoProcessor
120
+
121
+ if not self.model_path.is_dir():
122
+ raise FileNotFoundError(f"model not found: {self.model_path}")
123
+ self.device = device
124
+ self.dtype = torch.bfloat16
125
+ self.processor = AutoProcessor.from_pretrained(
126
+ str(self.model_path), trust_remote_code=True
127
+ )
128
+ self.model = (
129
+ AutoModelForImageTextToText.from_pretrained(
130
+ str(self.model_path), dtype=self.dtype, trust_remote_code=True
131
+ )
132
+ .eval()
133
+ .to(device)
134
+ )
135
+
136
+ def _build_inputs(self, frames, question):
137
+ """Render one chat turn to both plain text and tokenized model inputs."""
138
+ messages = [{"role": "user", "content": _numbered_content(frames, question)}]
139
+ prompt_text = self.processor.apply_chat_template(
140
+ messages,
141
+ add_generation_prompt=True,
142
+ tokenize=False,
143
+ **self.chat_template_kwargs,
144
+ )
145
+ inputs = self.processor.apply_chat_template(
146
+ messages,
147
+ add_generation_prompt=True,
148
+ tokenize=True,
149
+ return_dict=True,
150
+ return_tensors="pt",
151
+ **self.chat_template_kwargs,
152
+ ).to(self.device)
153
+ # Shapes of every non-text processor output (pixel_values, image_grid_thw, ...) --
154
+ # generic across model families instead of hunting each one's own vision placeholder
155
+ # token id, and still shows exactly how much visual input the model actually received.
156
+ vision_input_shapes = {
157
+ key: list(value.shape)
158
+ for key, value in inputs.items()
159
+ if key not in ("input_ids", "attention_mask") and hasattr(value, "shape")
160
+ }
161
+ return prompt_text, inputs, vision_input_shapes
162
+
163
+ def _eos_ids(self):
164
+ eos_ids = self.model.generation_config.eos_token_id
165
+ if eos_ids is None:
166
+ eos_ids = self.processor.tokenizer.eos_token_id
167
+ return [eos_ids] if isinstance(eos_ids, int) else list(eos_ids or [])
168
+
169
+ def _generate(self, inputs, max_new_tokens):
170
+ """Run one greedy generate() call. Returns (full sequence, elapsed seconds)."""
171
+ import time
172
+
173
+ import torch
174
+
175
+ start = time.monotonic()
176
+ with torch.no_grad():
177
+ generated = self.model.generate(
178
+ **inputs,
179
+ max_new_tokens=max_new_tokens,
180
+ do_sample=DO_SAMPLE,
181
+ temperature=None,
182
+ top_p=None,
183
+ top_k=None,
184
+ )
185
+ if self.device.startswith("cuda"):
186
+ torch.cuda.synchronize()
187
+ return generated, time.monotonic() - start
188
+
189
+ def _decode_new_tokens(self, generated, input_token_count, max_new_tokens, eos_ids):
190
+ """Split one generate() output into new-token ids + decoded text + hit-limit flag."""
191
+ output_token_ids = generated[0][input_token_count:].tolist()
192
+ hit_token_limit = len(output_token_ids) >= max_new_tokens and (
193
+ not output_token_ids or output_token_ids[-1] not in eos_ids
194
+ )
195
+ answer_text = self.processor.decode(
196
+ output_token_ids, skip_special_tokens=True
197
+ ).strip()
198
+ answer_raw = self.processor.decode(output_token_ids, skip_special_tokens=False)
199
+ return output_token_ids, hit_token_limit, answer_text, answer_raw
200
+
201
+ def _library_versions(self):
202
+ import torch
203
+ import transformers
204
+
205
+ return {"transformers": transformers.__version__, "torch": torch.__version__}
206
+
207
+ def answer(self, frames, question, max_new_tokens=None):
208
+ if self.model is None or self.processor is None:
209
+ raise RuntimeError("load_model() must be called before answer()")
210
+ cap = MAX_NEW_TOKENS if max_new_tokens is None else max_new_tokens
211
+ prompt_text, inputs, vision_input_shapes = self._build_inputs(frames, question)
212
+ input_token_count = int(inputs["input_ids"].shape[1])
213
+ generated, generation_seconds = self._generate(inputs, cap)
214
+ eos_ids = self._eos_ids()
215
+ output_token_ids, hit_token_limit, answer_text, answer_raw = (
216
+ self._decode_new_tokens(generated, input_token_count, cap, eos_ids)
217
+ )
218
+
219
+ return {
220
+ "prompt_text": prompt_text,
221
+ "answer_text": answer_text,
222
+ "answer_raw": answer_raw,
223
+ "input_token_count": input_token_count,
224
+ "vision_input_shapes": vision_input_shapes,
225
+ "output_token_ids": output_token_ids,
226
+ "output_token_count": len(output_token_ids),
227
+ "hit_token_limit": hit_token_limit,
228
+ "eos_token_ids": eos_ids,
229
+ "generation_seconds": generation_seconds,
230
+ "device": self.device,
231
+ "dtype": str(self.dtype).removeprefix("torch."),
232
+ "library_versions": self._library_versions(),
233
+ "generation_config": {
234
+ "max_new_tokens": cap,
235
+ "do_sample": DO_SAMPLE,
236
+ "temperature": TEMPERATURE,
237
+ "top_p": None,
238
+ "top_k": None,
239
+ **self.chat_template_kwargs,
240
+ },
241
+ }
242
+
243
+ def answer_extended(
244
+ self,
245
+ frames,
246
+ question,
247
+ reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
248
+ force_budget=MAX_NEW_TOKENS,
249
+ ):
250
+ import torch
251
+
252
+ if self.model is None or self.processor is None:
253
+ raise RuntimeError("load_model() must be called before answer_extended()")
254
+ prompt_text, inputs, vision_input_shapes = self._build_inputs(frames, question)
255
+ input_token_count = int(inputs["input_ids"].shape[1])
256
+ eos_ids = self._eos_ids()
257
+
258
+ generated, reasoning_seconds = self._generate(inputs, reasoning_budget)
259
+ reasoning_token_ids, reasoning_hit_limit, reasoning_text, reasoning_raw = (
260
+ self._decode_new_tokens(
261
+ generated, input_token_count, reasoning_budget, eos_ids
262
+ )
263
+ )
264
+
265
+ thinking = bool(self.chat_template_kwargs.get("enable_thinking"))
266
+ think_closed = thinking and "</think>" in reasoning_text
267
+ # With thinking ON, a natural stop whose think block never closed is as
268
+ # unusable as hitting the limit -- force the commit either way, closing the
269
+ # block the way the template expects.
270
+ forced = reasoning_hit_limit or (thinking and not think_closed)
271
+ generation_seconds = reasoning_seconds
272
+ if forced:
273
+ # Continue the SAME generation (not a new chat turn): the model's own partial
274
+ # response, plus an explicit instruction to answer now, then a short second
275
+ # budget to extract that answer. Multimodal tensors (pixel_values, etc.) must
276
+ # be resupplied -- the continued sequence still contains the original image
277
+ # placeholder tokens, and generate() recomputes their embeddings from scratch.
278
+ force_text = (
279
+ ("\n</think>\n" + FORCE_ANSWER_PROMPT)
280
+ if (thinking and not think_closed)
281
+ else FORCE_ANSWER_PROMPT
282
+ )
283
+ force_prompt_ids = self.processor.tokenizer(
284
+ force_text, return_tensors="pt", add_special_tokens=False
285
+ )["input_ids"].to(self.device)
286
+ continued_ids = torch.cat([generated, force_prompt_ids], dim=1)
287
+ continued_mask = torch.ones_like(continued_ids)
288
+ added_length = int(continued_ids.shape[1]) - input_token_count
289
+ continued_inputs = {}
290
+ for key, value in inputs.items():
291
+ if key in ("input_ids", "attention_mask"):
292
+ continue
293
+ # Per-token multimodal metadata (e.g. Qwen's mm_token_type_ids) is sized to
294
+ # the ORIGINAL prompt length and must grow with it; every newly generated
295
+ # token (reasoning + the force prompt) is plain text, never an image
296
+ # placeholder, so pad with zeros. Per-patch tensors (pixel_values,
297
+ # image_grid_thw, ...) don't depend on sequence length at all and pass
298
+ # through unchanged -- this check is what tells the two apart.
299
+ if (
300
+ hasattr(value, "shape")
301
+ and value.dim() >= 2
302
+ and value.shape[1] == input_token_count
303
+ ):
304
+ pad = value.new_zeros(
305
+ (value.shape[0], added_length) + tuple(value.shape[2:])
306
+ )
307
+ value = torch.cat([value, pad], dim=1)
308
+ continued_inputs[key] = value
309
+ continued_inputs["input_ids"] = continued_ids
310
+ continued_inputs["attention_mask"] = continued_mask
311
+ forced_input_token_count = int(continued_ids.shape[1])
312
+
313
+ forced_generated, forced_seconds = self._generate(
314
+ continued_inputs, force_budget
315
+ )
316
+ output_token_ids, hit_token_limit, answer_text, answer_raw = (
317
+ self._decode_new_tokens(
318
+ forced_generated, forced_input_token_count, force_budget, eos_ids
319
+ )
320
+ )
321
+ generation_seconds += forced_seconds
322
+ else:
323
+ forced_input_token_count = None
324
+ output_token_ids, hit_token_limit = reasoning_token_ids, reasoning_hit_limit
325
+ answer_text, answer_raw = reasoning_text, reasoning_raw
326
+ if thinking and think_closed:
327
+ # Score only what follows the closed think block; the full trace stays
328
+ # in reasoning_text/reasoning_raw below, untruncated.
329
+ _think, answer_text = _split_think(reasoning_text)
330
+
331
+ return {
332
+ "prompt_text": prompt_text,
333
+ "answer_text": answer_text,
334
+ "answer_raw": answer_raw,
335
+ "input_token_count": input_token_count,
336
+ "vision_input_shapes": vision_input_shapes,
337
+ "output_token_ids": output_token_ids,
338
+ "output_token_count": len(output_token_ids),
339
+ "hit_token_limit": hit_token_limit,
340
+ "eos_token_ids": eos_ids,
341
+ "generation_seconds": generation_seconds,
342
+ "device": self.device,
343
+ "dtype": str(self.dtype).removeprefix("torch."),
344
+ "library_versions": self._library_versions(),
345
+ "generation_config": {
346
+ "max_new_tokens": reasoning_budget,
347
+ "force_answer_max_new_tokens": force_budget,
348
+ "do_sample": DO_SAMPLE,
349
+ "temperature": TEMPERATURE,
350
+ "top_p": None,
351
+ "top_k": None,
352
+ **self.chat_template_kwargs,
353
+ },
354
+ "reasoning_text": reasoning_text,
355
+ "reasoning_raw": reasoning_raw,
356
+ "reasoning_token_ids": reasoning_token_ids,
357
+ "reasoning_token_count": len(reasoning_token_ids),
358
+ "reasoning_hit_limit": reasoning_hit_limit,
359
+ "forced": forced,
360
+ "forced_input_token_count": forced_input_token_count,
361
+ }
362
+
363
+
364
+ class QwenVLAdapter(_TransformersVLMAdapter):
365
+ """Qwen3.5 (image-text-to-text): used for both the 4B and 2B checkpoints.
366
+
367
+ ``enable_thinking=False`` is required, not optional -- Qwen3.5's chat template
368
+ defaults to opening an unclosed ``<think>`` block before the answer, which would
369
+ consume the entire 16-token budget on reasoning preamble and never emit an answer.
370
+ """
371
+
372
+ chat_template_kwargs = {"enable_thinking": False}
373
+
374
+
375
+ class InternVLAdapter(_TransformersVLMAdapter):
376
+ """InternVL3.5 (image-text-to-text).
377
+
378
+ ``crop_to_patches=False`` is required, not optional -- InternVL's default image
379
+ processor dynamically tiles EACH image content item into up to ~13 sub-patches at
380
+ 448x448, meant for one high-resolution photo. Applied per FRAME (our multi-image
381
+ prompting, one item per frame -- see ``_numbered_content``), that explodes the
382
+ prompt to ~3300 tokens/frame; just 16 frames already exceeds this checkpoint's
383
+ 40960-token context window before generation can even start. Disabling tiling
384
+ drops that to ~265 tokens/frame (measured: 16 frames 53401 -> 4251 tokens),
385
+ letting every frame count up to 96 fit comfortably. (The "correct" fix -- passing
386
+ frames as one native ``{"type": "video"}`` content item, which HF's own video
387
+ preprocessor handles at a similarly low per-frame cost without this flag -- hits
388
+ an unrelated shape-mismatch bug in this transformers version's InternVL vision
389
+ pixel-shuffle path; this is the working equivalent, not a workaround of our own
390
+ logic.)
391
+ """
392
+
393
+ chat_template_kwargs = {"crop_to_patches": False}
394
+
395
+
396
+ _ADAPTERS = {
397
+ "qwen3.5-4b": QwenVLAdapter,
398
+ "qwen3.5-2b": QwenVLAdapter,
399
+ "internvl3.5-4b": InternVLAdapter,
400
+ "internvl3.5-2b": InternVLAdapter,
401
+ }
402
+
403
+
404
+ def available_models():
405
+ """Return registered model names in stable order."""
406
+ return tuple(sorted(_ADAPTERS))
407
+
408
+
409
+ def get_adapter(model):
410
+ """Create one unloaded adapter bound to a registered model's checkpoint path."""
411
+ adapter_type = _ADAPTERS.get(model)
412
+ if adapter_type is None:
413
+ raise KeyError(
414
+ f"unknown harness model {model!r}; expected one of {available_models()}"
415
+ )
416
+ return adapter_type(MODEL_PATHS[model])
harness/A/prompts.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """VSI-Bench prompt construction with the shared step-by-step reasoning instruction.
2
+
3
+ Keeps lmms_eval's question-type split and final-answer constraints, but deliberately
4
+ adds an explicit reasoning instruction before the final-answer line.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ # Verbatim from thinking-in-space/lmms_eval/tasks/vsibench/utils.py.
10
+ MCA_QUESTION_TYPES = (
11
+ "object_rel_direction_easy",
12
+ "object_rel_direction_medium",
13
+ "object_rel_direction_hard",
14
+ "object_rel_distance",
15
+ "route_planning",
16
+ "obj_appearance_order",
17
+ )
18
+ NA_QUESTION_TYPES = (
19
+ "object_abs_distance",
20
+ "object_counting",
21
+ "object_size_estimation",
22
+ "room_size_estimation",
23
+ )
24
+
25
+ # vsibench.yaml lmms_eval_specific_kwargs.default. pre_prompt is "" in the yaml, which
26
+ # the original doc_to_text treats as falsy and falls back to this text -- so this is
27
+ # the pre_prompt every non-API (incl. local HF) model is actually scored under.
28
+ PRE_PROMPT = "These are frames of a video."
29
+ VIDEO_PRE_PROMPT = "This is a video."
30
+ STEP_BY_STEP_REASONING_PROMPT = "Think step by step and explain your reasoning briefly before giving the final answer."
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, video=False):
36
+ """Return one VSI-Bench prompt with the shared reasoning instruction."""
37
+ pre_prompt = VIDEO_PRE_PROMPT if video else PRE_PROMPT
38
+ if question_type in NA_QUESTION_TYPES:
39
+ return "\n".join(
40
+ [pre_prompt, question, STEP_BY_STEP_REASONING_PROMPT, NA_POST_PROMPT]
41
+ )
42
+ if question_type in MCA_QUESTION_TYPES:
43
+ if not options:
44
+ raise ValueError(f"question_type {question_type!r} requires options")
45
+ options_block = "Options:\n" + "\n".join(options)
46
+ return "\n".join(
47
+ [
48
+ pre_prompt,
49
+ question,
50
+ options_block,
51
+ STEP_BY_STEP_REASONING_PROMPT,
52
+ MCA_POST_PROMPT,
53
+ ]
54
+ )
55
+ raise ValueError(
56
+ f"unknown question_type {question_type!r}; "
57
+ f"expected one of {MCA_QUESTION_TYPES + NA_QUESTION_TYPES}"
58
+ )
harness/A/run.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 (
43
+ protocol_for_question,
44
+ question_group,
45
+ resolve_protocol_budgets,
46
+ ) # noqa: E402
47
+ from harness.A import prompts as vsi_prompts # noqa: E402
48
+
49
+ _OFFICIAL_EVAL = os.environ.get(
50
+ "HARNESS_OFFICIAL_EVAL",
51
+ "/root/data/thinking-in-space/lmms_eval/tasks/vsibench/utils.py",
52
+ )
53
+
54
+
55
+ def _load_official_eval(path):
56
+ # Loaded under a unique module name (not the bare "utils" symbolic/run.py itself
57
+ # uses) so the two never fight over sys.modules["utils"] when both are imported in
58
+ # the same process, e.g. across the test suite.
59
+ spec = importlib.util.spec_from_file_location("harness_A_vsi_official_eval", path)
60
+ module = importlib.util.module_from_spec(spec)
61
+ spec.loader.exec_module(module)
62
+ return module
63
+
64
+
65
+ vsi_official_eval = _load_official_eval(_OFFICIAL_EVAL)
66
+
67
+
68
+ def _scalar_score(question_type, score_doc):
69
+ """Return (metric_name, value) -- the one numeric metric attached by the scorer."""
70
+ if question_type in vsi_official_eval.MCA_QUESTION_TYPES:
71
+ metric_keys = vsi_official_eval.METRICS_FOR_MCA
72
+ elif question_type in vsi_official_eval.NA_QUESTION_TYPES:
73
+ metric_keys = vsi_official_eval.METRICS_FOR_NA
74
+ else:
75
+ raise ValueError(
76
+ f"unknown question_type {question_type!r}; "
77
+ f"expected one of {vsi_official_eval.MCA_QUESTION_TYPES + vsi_official_eval.NA_QUESTION_TYPES}"
78
+ )
79
+ (metric_key,) = metric_keys.keys()
80
+ return metric_key, score_doc[metric_key]
81
+
82
+
83
+ def load_questions(jsonl_path=None, scene=None, scenes=None, limit=None):
84
+ """Return VSI-Bench question rows, optionally filtered to one/many scenes / capped."""
85
+ if scene is not None and scenes is not None:
86
+ raise ValueError("scene and scenes cannot both be given")
87
+ allowed = (
88
+ {scene} if scene is not None else (set(scenes) if scenes is not None else None)
89
+ )
90
+ jsonl_path = jsonl_path or JSONL
91
+ rows = []
92
+ with open(jsonl_path) as stream:
93
+ for line in stream:
94
+ row = json.loads(line)
95
+ if allowed is not None and row["scene_name"] not in allowed:
96
+ continue
97
+ rows.append(row)
98
+ if limit is not None and len(rows) >= limit:
99
+ break
100
+ return rows
101
+
102
+
103
+ def results_dir_for(model, protocol, frame_selection, frame_count, results_dir=None):
104
+ """Return the result root isolated by model + protocol + frame-selection +
105
+ frame-count. ``protocol`` is "base" (16-token) or "<reasoning budget>"
106
+ (e.g. "512") -- a real path segment, so records from different protocols
107
+ OR different reasoning budgets can never collide on disk."""
108
+ if results_dir is not None:
109
+ return Path(results_dir)
110
+ root = RESULTS_DIR / model
111
+ if frame_selection == "video":
112
+ return root / "video"
113
+ return root / frame_selection / str(frame_count)
114
+
115
+
116
+ def _build_record(
117
+ row, prompt, answer, metric_name, score, model, model_path, frame_info
118
+ ):
119
+ """Assemble one question's full, untruncated result record (nothing summarized)."""
120
+ return {
121
+ "model": model,
122
+ "model_path": str(model_path),
123
+ "device": answer["device"],
124
+ "dtype": answer["dtype"],
125
+ "library_versions": answer["library_versions"],
126
+ "condition": (
127
+ f"{frame_info['protocol']}:video"
128
+ if frame_info["frame_selection"] == "video"
129
+ else (
130
+ f"{frame_info['protocol']}:{frame_info['frame_selection']}:"
131
+ f"{frame_info['frame_count']}"
132
+ )
133
+ ),
134
+ "protocol": frame_info["protocol"],
135
+ "question_group": question_group(row["question_type"]),
136
+ "frame_selection": frame_info["frame_selection"],
137
+ "frame_count": frame_info["frame_count"],
138
+ "video_path": frame_info["video_path"],
139
+ "frame_indices": frame_info["frame_indices"],
140
+ "frame_timestamps_seconds": frame_info["frame_timestamps"],
141
+ "scene": row["scene_name"],
142
+ "dataset": row.get("dataset"),
143
+ "question_id": row["id"],
144
+ "question_type": row["question_type"],
145
+ "question": row["question"],
146
+ "options": row.get("options"),
147
+ "full_prompt": prompt,
148
+ "rendered_prompt": answer["prompt_text"],
149
+ "answer_expected": row["ground_truth"],
150
+ "answer_given": answer["answer_text"],
151
+ "answer_raw": answer["answer_raw"],
152
+ "input_token_count": answer["input_token_count"],
153
+ "vision_input_shapes": answer["vision_input_shapes"],
154
+ "output_token_ids": answer["output_token_ids"],
155
+ "output_token_count": answer["output_token_count"],
156
+ "hit_token_limit": answer["hit_token_limit"],
157
+ "eos_token_ids": answer["eos_token_ids"],
158
+ "generation_seconds": answer["generation_seconds"],
159
+ "generation_config": answer["generation_config"],
160
+ "reasoning_text": answer.get("reasoning_text"),
161
+ "reasoning_raw": answer.get("reasoning_raw"),
162
+ "reasoning_token_ids": answer.get("reasoning_token_ids"),
163
+ "reasoning_token_count": answer.get("reasoning_token_count"),
164
+ "reasoning_hit_limit": answer.get("reasoning_hit_limit"),
165
+ "forced": answer.get("forced", False),
166
+ "forced_input_token_count": answer.get("forced_input_token_count"),
167
+ "metric": metric_name,
168
+ "score": score,
169
+ }
170
+
171
+
172
+ def write_question_result(
173
+ row,
174
+ prompt,
175
+ answer,
176
+ metric_name,
177
+ score,
178
+ model,
179
+ model_path,
180
+ frame_info,
181
+ results_dir=None,
182
+ ):
183
+ """Write one question's full, untruncated result record. Return (path, record)."""
184
+ record = _build_record(
185
+ row, prompt, answer, metric_name, score, model, model_path, frame_info
186
+ )
187
+ root = results_dir_for(
188
+ model,
189
+ frame_info["protocol"],
190
+ frame_info["frame_selection"],
191
+ frame_info["frame_count"],
192
+ results_dir,
193
+ )
194
+ scene_dir = root / record["scene"]
195
+ scene_dir.mkdir(parents=True, exist_ok=True)
196
+ path = scene_dir / f"{row['id']}.json"
197
+ with path.open("w", encoding="utf-8") as stream:
198
+ json.dump(record, stream, indent=1)
199
+ return path, record
200
+
201
+
202
+ def run(
203
+ model,
204
+ frame_selection=DEFAULT_FRAME_SELECTION,
205
+ frame_count=FRAMES_PER_VIDEO,
206
+ video=False,
207
+ scene=None,
208
+ scenes=None,
209
+ limit=None,
210
+ device="cuda",
211
+ jsonl_path=None,
212
+ results_dir=None,
213
+ write_results=True,
214
+ adapter=None,
215
+ extended=True,
216
+ reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
217
+ force_budget=MAX_NEW_TOKENS,
218
+ ):
219
+ """Answer every matching question with one model, scored via the official scorer.
220
+
221
+ Each question's full record is written to its own JSON file as soon as it is
222
+ answered (unless ``write_results=False``); the in-memory list returned holds the
223
+ same full records for callers that want them without re-reading from disk.
224
+
225
+ Pass a pre-loaded ``adapter`` (as ``harness.A.launch``'s persistent per-GPU workers
226
+ do) to reuse one already-loaded model across many calls instead of paying the load
227
+ cost per call; the caller then owns unloading it. Without one, ``run`` loads and
228
+ unloads its own adapter, same as before.
229
+
230
+ ``extended=True`` uses ``adapter.answer_extended`` -- a larger first-pass
231
+ budget (``reasoning_budget``) with a short forced second call only if the model
232
+ does not conclude within it. The complete visible first-pass response is stored
233
+ in ``reasoning_text`` and ``reasoning_raw``.
234
+ """
235
+ if video:
236
+ frame_selection = "video"
237
+ frame_count = None
238
+ elif frame_count is None or frame_count < 1:
239
+ raise ValueError("frame_count must be positive in frames mode")
240
+ rows = load_questions(jsonl_path, scene, scenes, limit)
241
+ if not rows:
242
+ return []
243
+ owns_adapter = adapter is None
244
+ if owns_adapter:
245
+ adapter = vlm_models.get_adapter(model)
246
+ adapter.load_model(device)
247
+ frame_cache = {}
248
+ results = []
249
+ try:
250
+ for row in rows:
251
+ protocol = protocol_for_question(row["question_type"])
252
+ scene_id = row["scene_name"]
253
+ if scene_id not in frame_cache:
254
+ video_path = inference_config.video_path(scene_id, row.get("dataset"))
255
+ if video:
256
+ frame_images = video_path
257
+ frame_timestamps = None
258
+ frame_indices = None
259
+ else:
260
+ frame_images, frame_timestamps, frame_indices = (
261
+ frame_sampling.sample_frames(
262
+ video_path, frame_count, frame_selection
263
+ )
264
+ )
265
+ frame_cache[scene_id] = {
266
+ "video_path": video_path,
267
+ "frame_images": frame_images,
268
+ "frame_timestamps": frame_timestamps,
269
+ "frame_indices": frame_indices,
270
+ "frame_selection": frame_selection,
271
+ "frame_count": frame_count,
272
+ }
273
+ cached = frame_cache[scene_id]
274
+ prompt = vsi_prompts.build_prompt(
275
+ row["question_type"], row["question"], row.get("options"), video=video
276
+ )
277
+ answer = (
278
+ adapter.answer_extended(
279
+ cached["frame_images"],
280
+ prompt,
281
+ reasoning_budget=reasoning_budget,
282
+ force_budget=force_budget,
283
+ )
284
+ if protocol == "thinking"
285
+ else adapter.answer(
286
+ cached["frame_images"], prompt, max_new_tokens=MAX_NEW_TOKENS
287
+ )
288
+ )
289
+ doc = {
290
+ "question_type": row["question_type"],
291
+ "ground_truth": row["ground_truth"],
292
+ }
293
+ score_doc = vsi_official_eval.vsibench_process_results(
294
+ doc, [answer["answer_text"]]
295
+ )["vsibench_score"]
296
+ metric_name, score = _scalar_score(row["question_type"], score_doc)
297
+ frame_info = {
298
+ "protocol": protocol,
299
+ "video_path": cached["video_path"],
300
+ "frame_timestamps": cached["frame_timestamps"],
301
+ "frame_indices": cached["frame_indices"],
302
+ "frame_selection": frame_selection,
303
+ "frame_count": frame_count,
304
+ }
305
+ if write_results:
306
+ path, record = write_question_result(
307
+ row,
308
+ prompt,
309
+ answer,
310
+ metric_name,
311
+ score,
312
+ model,
313
+ adapter.model_path,
314
+ frame_info,
315
+ results_dir,
316
+ )
317
+ else:
318
+ path = None
319
+ record = _build_record(
320
+ row,
321
+ prompt,
322
+ answer,
323
+ metric_name,
324
+ score,
325
+ model,
326
+ adapter.model_path,
327
+ frame_info,
328
+ )
329
+ record["result_path"] = str(path) if path else None
330
+ results.append(record)
331
+ finally:
332
+ if owns_adapter:
333
+ adapter.unload()
334
+ return results
335
+
336
+
337
+ def main():
338
+ parser = argparse.ArgumentParser()
339
+ parser.add_argument("--model", required=True, choices=vlm_models.available_models())
340
+ parser.add_argument("--scene", default=None, help="restrict to one VSI-Bench scene")
341
+ parser.add_argument(
342
+ "--frame-selection",
343
+ default=None,
344
+ choices=FRAME_SELECTIONS,
345
+ dest="frame_selection",
346
+ )
347
+ input_mode = parser.add_mutually_exclusive_group(required=True)
348
+ input_mode.add_argument("--frames", type=int)
349
+ input_mode.add_argument("--video", action="store_true")
350
+ parser.add_argument(
351
+ "--limit", type=int, default=None, help="cap the number of questions"
352
+ )
353
+ parser.add_argument("--device", default="cuda")
354
+ parser.add_argument(
355
+ "--results-dir",
356
+ default=None,
357
+ help="override the default results/A/<model>/{<selection>/<frames>|video} root",
358
+ )
359
+ parser.add_argument(
360
+ "--no-write",
361
+ action="store_true",
362
+ help="skip writing per-question JSON files; print/score only",
363
+ )
364
+ parser.add_argument(
365
+ "--reasoning-budget",
366
+ type=int,
367
+ default=None,
368
+ help="thinking questions only (default: 2048)",
369
+ )
370
+ parser.add_argument(
371
+ "--force-budget",
372
+ type=int,
373
+ default=None,
374
+ help="thinking questions only (default: 16)",
375
+ )
376
+ args = parser.parse_args()
377
+ if args.video:
378
+ if args.frame_selection is not None:
379
+ parser.error("--frame-selection cannot be used with --video")
380
+ else:
381
+ if args.frame_selection is None:
382
+ parser.error("--frame-selection is required with --frames")
383
+ if args.frames < 1:
384
+ parser.error("--frames must be positive")
385
+ resolve_protocol_budgets(parser, args)
386
+
387
+ results = run(
388
+ args.model,
389
+ frame_selection=args.frame_selection,
390
+ frame_count=args.frames,
391
+ video=args.video,
392
+ scene=args.scene,
393
+ limit=args.limit,
394
+ device=args.device,
395
+ results_dir=args.results_dir,
396
+ write_results=not args.no_write,
397
+ extended=True,
398
+ reasoning_budget=args.reasoning_budget,
399
+ force_budget=args.force_budget,
400
+ )
401
+
402
+ for result in results:
403
+ print(
404
+ f"[{result['scene']}#{result['question_id']}] {result['question_type']}: "
405
+ f"pred={result['answer_given']!r} gt={result['answer_expected']!r} "
406
+ f"score={result['score']} ({result['generation_seconds']:.2f}s) -> "
407
+ f"{result['result_path']}"
408
+ )
409
+ if results:
410
+ mean_score = sum(r["score"] for r in results) / len(results)
411
+ total_seconds = sum(r["generation_seconds"] for r in results)
412
+ print(
413
+ f"\n{len(results)} questions, mean vsibench_score={mean_score:.4f}, "
414
+ f"total generation time={total_seconds:.1f}s"
415
+ )
416
+
417
+
418
+ if __name__ == "__main__":
419
+ main()
harness/A/sweep.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 EXTENDED_MAX_NEW_TOKENS, 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
+ from harness.A import resolve_protocol_budgets # noqa: E402
26
+
27
+
28
+ def _parse_csv_choice(value, valid, flag):
29
+ """Split a comma-separated ``--flag`` value; ``"all"`` expands to every ``valid``."""
30
+ items = [item.strip() for item in value.split(",") if item.strip()]
31
+ if not items:
32
+ raise ValueError(f"{flag} must name at least one value")
33
+ if len(items) == 1 and items[0].lower() == "all":
34
+ return list(valid)
35
+ unknown = [item for item in items if item not in valid]
36
+ if unknown:
37
+ raise ValueError(
38
+ f"unknown {flag} value(s) {unknown}; expected one of {valid} (or 'all')"
39
+ )
40
+ return list(dict.fromkeys(items))
41
+
42
+
43
+ def _parse_frame_counts(value):
44
+ items = [item.strip() for item in value.split(",") if item.strip()]
45
+ if not items:
46
+ raise ValueError("--frames must name at least one frame count")
47
+ counts = []
48
+ for item in items:
49
+ try:
50
+ count = int(item)
51
+ except ValueError:
52
+ raise ValueError(f"--frames value {item!r} is not an integer") from None
53
+ if count < 1:
54
+ raise ValueError(f"--frames value {count} must be positive")
55
+ counts.append(count)
56
+ return list(dict.fromkeys(counts))
57
+
58
+
59
+ def build_plan(models, frame_selections, frame_counts):
60
+ """Return every (model, frame_selection, frame_count) triple in the sweep, in a
61
+ stable, cheapest-first-ish order (frame count is the dominant cost driver, so
62
+ sorting by it surfaces comparable results across every model/selection soonest)."""
63
+ return [
64
+ (model, selection, frame_count)
65
+ for frame_count in sorted(frame_counts)
66
+ for model in models
67
+ for selection in frame_selections
68
+ ]
69
+
70
+
71
+ def sweep(
72
+ models,
73
+ frame_selections,
74
+ frame_counts,
75
+ selected_scenes,
76
+ video=False,
77
+ results_dir=None,
78
+ rebuild=False,
79
+ extended=True,
80
+ reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
81
+ ):
82
+ """Run every (model, frame_selection, frame_count) triple across all visible GPUs."""
83
+ plan = (
84
+ [(model, "video", None) for model in models]
85
+ if video
86
+ else build_plan(models, frame_selections, frame_counts)
87
+ )
88
+ for index, (model, frame_selection, frame_count) in enumerate(plan, start=1):
89
+ print(
90
+ f"=== sweep {index}/{len(plan)}: {model}/"
91
+ + ("video" if video else f"{frame_selection}/{frame_count}")
92
+ + " ===",
93
+ flush=True,
94
+ )
95
+ harness_launch.launch(
96
+ model,
97
+ frame_selection,
98
+ frame_count,
99
+ selected_scenes,
100
+ video=video,
101
+ results_dir=results_dir,
102
+ rebuild=rebuild,
103
+ extended=extended,
104
+ reasoning_budget=reasoning_budget,
105
+ )
106
+
107
+
108
+ def main():
109
+ parser = argparse.ArgumentParser()
110
+ parser.add_argument("scene", nargs="?")
111
+ parser.add_argument(
112
+ "--scenes",
113
+ help="comma-separated scenes (cannot be combined with positional scene)",
114
+ )
115
+ parser.add_argument(
116
+ "--models",
117
+ required=True,
118
+ help=f"comma-separated models (or 'all'); one of {vlm_models.available_models()}",
119
+ )
120
+ parser.add_argument(
121
+ "--frame-selections",
122
+ required=False,
123
+ dest="frame_selections",
124
+ help=f"comma-separated selections (or 'all'); one of {FRAME_SELECTIONS}",
125
+ )
126
+ input_mode = parser.add_mutually_exclusive_group(required=True)
127
+ input_mode.add_argument(
128
+ "--frames", help="comma-separated frame counts, e.g. 16,32,64"
129
+ )
130
+ input_mode.add_argument("--video", action="store_true")
131
+ parser.add_argument("--results-dir", default=None)
132
+ parser.add_argument("--rebuild", action="store_true")
133
+ parser.add_argument(
134
+ "--reasoning-budget",
135
+ type=int,
136
+ default=None,
137
+ dest="reasoning_budget",
138
+ help="thinking-protocol first-pass budget (the calibrated value from "
139
+ "analysis/preregistration.md, e.g. 512)",
140
+ )
141
+ args = parser.parse_args()
142
+ resolve_protocol_budgets(parser, args)
143
+ if args.scene and args.scenes:
144
+ parser.error("positional scene and --scenes cannot be used together")
145
+
146
+ try:
147
+ models = _parse_csv_choice(
148
+ args.models, vlm_models.available_models(), "--models"
149
+ )
150
+ if args.video:
151
+ if args.frame_selections is not None:
152
+ raise ValueError("--frame-selections cannot be used with --video")
153
+ frame_selections = ["video"]
154
+ frame_counts = [None]
155
+ else:
156
+ if args.frame_selections is None:
157
+ raise ValueError("--frame-selections is required with --frames")
158
+ frame_selections = _parse_csv_choice(
159
+ args.frame_selections, FRAME_SELECTIONS, "--frame-selections"
160
+ )
161
+ frame_counts = _parse_frame_counts(args.frames)
162
+ except ValueError as exc:
163
+ parser.error(str(exc))
164
+
165
+ if args.scenes is not None:
166
+ selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
167
+ if not selected:
168
+ parser.error("--scenes must contain at least one scene")
169
+ selected = list(dict.fromkeys(selected))
170
+ else:
171
+ selected = [args.scene] if args.scene else harness_launch.scenes()
172
+
173
+ sweep(
174
+ models,
175
+ frame_selections,
176
+ frame_counts,
177
+ selected,
178
+ video=args.video,
179
+ results_dir=args.results_dir,
180
+ rebuild=args.rebuild,
181
+ extended=True,
182
+ reasoning_budget=args.reasoning_budget,
183
+ )
184
+
185
+
186
+ if __name__ == "__main__":
187
+ main()
harness/B/__init__.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Harness B: route a scene's on-disk explicit spatial code -- 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 (
19
+ DO_SAMPLE,
20
+ JSONL,
21
+ MAX_NEW_TOKENS,
22
+ MODEL_PATHS,
23
+ TEMPERATURE,
24
+ WORKSPACE_ROOT,
25
+ )
26
+
27
+ # The harness consumes the encoder's fixed explicit spatial-code output.
28
+ SPATIAL_CODE_FORMATS = ("explicit",)
29
+ DEFAULT_SPATIAL_CODE_FORMAT = "explicit"
30
+
31
+ # Same vocabulary as inference.SAM3_FRAME_SELECTIONS / harness.A.FRAME_SELECTIONS --
32
+ # which raw video sampling the on-disk spatial code was itself built from.
33
+ INPUT_SELECTIONS = ("uniform", "selective")
34
+ DEFAULT_INPUT_SELECTION = "uniform"
35
+
36
+ # Same depth/tracking vocabulary encoder.config uses to lay out spatial codes on disk --
37
+ # real sweepable axes here too (see sweep.py's --depths/--trackings), not fixed
38
+ # constants; DEFAULT_DEPTH/DEFAULT_TRACKING are just the single-value default when a
39
+ # caller doesn't ask to sweep them, matching this workspace's shipped production config.
40
+ DEFAULT_DEPTH = "metric"
41
+ DEFAULT_TRACKING = "tracking"
42
+
43
+ FRAMES_PER_VIDEO = int(os.environ.get("VSI_HARNESS_B_FRAMES_PER_VIDEO", "32"))
44
+
45
+ # One JSON per question, matching harness.A's layout:
46
+ # results/B/<model>/<spatial_code_format>/<depth>/<tracking>/<input_selection>/<frame_count>/<scene>/<question_id>.json
47
+ RESULTS_DIR = Path(os.environ.get("VSI_HARNESS_B_RESULTS_DIR", "/root/results/B"))
harness/B/launch.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 import resolve_protocol_budgets # noqa: E402
29
+ from harness.A.launch import scenes # noqa: E402
30
+ from harness.B import ( # noqa: E402
31
+ DEFAULT_DEPTH,
32
+ DEFAULT_INPUT_SELECTION,
33
+ DEFAULT_SPATIAL_CODE_FORMAT,
34
+ DEFAULT_TRACKING,
35
+ DEPTH_VARIANTS,
36
+ FRAMES_PER_VIDEO,
37
+ INPUT_SELECTIONS,
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,
53
+ results,
54
+ model,
55
+ spatial_code_format,
56
+ input_selection,
57
+ frame_count,
58
+ video,
59
+ depth,
60
+ tracking,
61
+ results_dir,
62
+ gpu,
63
+ cpu_threads,
64
+ extended,
65
+ reasoning_budget,
66
+ force_budget,
67
+ question_ids,
68
+ ):
69
+ if gpu is not None:
70
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
71
+ for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
72
+ os.environ[variable] = str(cpu_threads)
73
+ run = _load_run_module()
74
+ adapter = None
75
+ load_error = None
76
+ try:
77
+ adapter = vlm_models.get_adapter(model)
78
+ adapter.load_model("cuda:0" if gpu is not None else "cpu")
79
+ except Exception:
80
+ load_error = traceback.format_exc()
81
+ while True:
82
+ scene = tasks.get()
83
+ if scene is None:
84
+ return
85
+ if load_error is not None:
86
+ results.put((scene, False, load_error))
87
+ continue
88
+ try:
89
+ answered = run.run(
90
+ model,
91
+ spatial_code_format=spatial_code_format,
92
+ input_selection=input_selection,
93
+ frame_count=frame_count,
94
+ video=video,
95
+ depth=depth,
96
+ tracking=tracking,
97
+ scene=scene,
98
+ results_dir=results_dir,
99
+ adapter=adapter,
100
+ extended=extended,
101
+ reasoning_budget=reasoning_budget,
102
+ force_budget=force_budget,
103
+ question_ids=question_ids,
104
+ )
105
+ # thinking is applied on the adapter above, not passed to run() -- the
106
+ # worker owns the adapter, run() must not re-toggle it.
107
+ mean_score = (
108
+ sum(r["score"] for r in answered) / len(answered) if answered else None
109
+ )
110
+ results.put(
111
+ (scene, True, f"{len(answered)} question(s), mean_score={mean_score}")
112
+ )
113
+ except Exception:
114
+ results.put((scene, False, traceback.format_exc()))
115
+
116
+
117
+ def launch(
118
+ model,
119
+ spatial_code_format,
120
+ input_selection,
121
+ frame_count,
122
+ selected,
123
+ video=False,
124
+ depth=DEFAULT_DEPTH,
125
+ tracking=DEFAULT_TRACKING,
126
+ results_dir=None,
127
+ rebuild=False,
128
+ extended=True,
129
+ reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
130
+ force_budget=MAX_NEW_TOKENS,
131
+ question_ids=None,
132
+ ):
133
+ """Answer every question for ``selected`` scenes, sharded across every visible GPU.
134
+ ``question_ids``, when given, restricts every scene to that question subset."""
135
+ if video:
136
+ input_selection = "video"
137
+ frame_count = None
138
+ elif frame_count is None or frame_count < 1:
139
+ raise ValueError("frame_count must be positive in frames mode")
140
+ mode = "video" if video else f"{input_selection}/{frame_count}"
141
+ condition = f"{model}/{spatial_code_format}/{depth}/{tracking}/{mode}"
142
+ run = _load_run_module()
143
+ root = run.results_dir_for(
144
+ model,
145
+ None,
146
+ spatial_code_format,
147
+ depth,
148
+ tracking,
149
+ input_selection,
150
+ frame_count,
151
+ results_dir,
152
+ )
153
+ pending = []
154
+ completed = 0
155
+ for scene in selected:
156
+ rows = run.load_questions(scene=scene)
157
+ if question_ids is not None:
158
+ rows = [row for row in rows if row["id"] in question_ids]
159
+ if not rows:
160
+ raise ValueError(
161
+ f"no questions found for scene {scene!r}; check the manifest, scene selection, or question_ids"
162
+ )
163
+ answered = all((root / scene / f"{row['id']}.json").is_file() for row in rows)
164
+ if answered and not rebuild:
165
+ completed += 1
166
+ print(
167
+ f"[{condition} {completed}/{len(selected)}] {scene}: skipped",
168
+ flush=True,
169
+ )
170
+ else:
171
+ pending.append(scene)
172
+ if not pending:
173
+ print(f"[{condition}] DONE: {len(selected)} ok, 0 failed")
174
+ return
175
+
176
+ gpus = visible_gpus()
177
+ worker_count = min(len(pending), len(gpus) if gpus else 1)
178
+ assignments = gpus[:worker_count] if gpus else [None]
179
+ cpu_count = available_cpu_count()
180
+ cpu_threads = max(1, cpu_count // worker_count)
181
+ print(
182
+ f"[{condition}] starting {worker_count} persistent worker(s); "
183
+ f"GPUs={assignments}; CPU threads/worker={cpu_threads}",
184
+ flush=True,
185
+ )
186
+
187
+ context = mp.get_context("spawn")
188
+ tasks, results = context.Queue(), context.Queue()
189
+ for scene in pending:
190
+ tasks.put(scene)
191
+ for _ in range(worker_count):
192
+ tasks.put(None)
193
+ workers = [
194
+ context.Process(
195
+ target=_worker,
196
+ args=(
197
+ tasks,
198
+ results,
199
+ model,
200
+ spatial_code_format,
201
+ input_selection,
202
+ frame_count,
203
+ video,
204
+ depth,
205
+ tracking,
206
+ results_dir,
207
+ gpu,
208
+ cpu_threads,
209
+ extended,
210
+ reasoning_budget,
211
+ force_budget,
212
+ question_ids,
213
+ ),
214
+ )
215
+ for gpu in assignments
216
+ ]
217
+ for worker in workers:
218
+ worker.start()
219
+ failed = []
220
+ for finished in range(1, len(pending) + 1):
221
+ scene, ok, detail = results.get()
222
+ if not ok:
223
+ failed.append(scene)
224
+ print(
225
+ f"[{condition} {completed + finished}/{len(selected)}] {scene}: "
226
+ f"{'done' if ok else 'FAILED'}\n{detail}",
227
+ flush=True,
228
+ )
229
+ for worker in workers:
230
+ worker.join()
231
+ print(
232
+ f"[{condition}] DONE: {len(pending) - len(failed)} answered, {completed} skipped, "
233
+ f"{len(failed)} failed"
234
+ )
235
+ if failed:
236
+ raise SystemExit(1)
237
+
238
+
239
+ def main():
240
+ parser = argparse.ArgumentParser()
241
+ parser.add_argument("scene", nargs="?")
242
+ parser.add_argument(
243
+ "--scenes",
244
+ help="comma-separated scenes (cannot be combined with positional scene)",
245
+ )
246
+ parser.add_argument("--model", required=True, choices=vlm_models.available_models())
247
+ parser.add_argument(
248
+ "--input-selection",
249
+ default=None,
250
+ choices=INPUT_SELECTIONS,
251
+ dest="input_selection",
252
+ )
253
+ input_mode = parser.add_mutually_exclusive_group(required=True)
254
+ input_mode.add_argument("--frames", type=int)
255
+ input_mode.add_argument("--video", action="store_true")
256
+ parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS)
257
+ parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES)
258
+ parser.add_argument("--results-dir", default=None)
259
+ parser.add_argument("--rebuild", action="store_true")
260
+ parser.add_argument(
261
+ "--reasoning-budget",
262
+ type=int,
263
+ default=None,
264
+ help="thinking mode only (default: 2048)",
265
+ )
266
+ parser.add_argument(
267
+ "--force-budget",
268
+ type=int,
269
+ default=None,
270
+ help="thinking mode only (default: 16)",
271
+ )
272
+ args = parser.parse_args()
273
+ if args.scene and args.scenes:
274
+ parser.error("positional scene and --scenes cannot be used together")
275
+ if args.scenes is not None:
276
+ selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
277
+ if not selected:
278
+ parser.error("--scenes must contain at least one scene")
279
+ selected = list(dict.fromkeys(selected))
280
+ else:
281
+ selected = [args.scene] if args.scene else scenes()
282
+ if args.video:
283
+ if args.input_selection is not None:
284
+ parser.error("--input-selection cannot be used with --video")
285
+ else:
286
+ if args.input_selection is None:
287
+ parser.error("--input-selection is required with --frames")
288
+ if args.frames < 1:
289
+ parser.error("--frames must be positive")
290
+ resolve_protocol_budgets(parser, args)
291
+ launch(
292
+ args.model,
293
+ DEFAULT_SPATIAL_CODE_FORMAT,
294
+ args.input_selection,
295
+ args.frames,
296
+ selected,
297
+ video=args.video,
298
+ depth=args.depth,
299
+ tracking=args.tracking,
300
+ results_dir=args.results_dir,
301
+ rebuild=args.rebuild,
302
+ extended=True,
303
+ reasoning_budget=args.reasoning_budget,
304
+ force_budget=args.force_budget,
305
+ )
306
+
307
+
308
+ if __name__ == "__main__":
309
+ main()
harness/B/prompts.py ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """VSI-Bench prompt construction for spatial-code inputs.
2
+
3
+ There is one active spatial-code prompt: v2 legend + v2 prompt-facing code JSON,
4
+ followed by the VSI question/options shape and the harness step-by-step instruction.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+ import itertools
11
+ import json
12
+
13
+ from harness.A.prompts import (
14
+ MCA_POST_PROMPT,
15
+ MCA_QUESTION_TYPES,
16
+ NA_POST_PROMPT,
17
+ NA_QUESTION_TYPES,
18
+ STEP_BY_STEP_REASONING_PROMPT,
19
+ )
20
+
21
+ _CCF = "closest_classes_from"
22
+ _CCF_L2 = "closest classes distance meters from"
23
+ _CCF_L1 = "minimum distance between classes"
24
+
25
+ _HEAD = (
26
+ "Below is the spatial code of a scanned room. It is a JSON description of the room, "
27
+ "built automatically from a video walkthrough."
28
+ )
29
+ _UNITS_NOTE = (
30
+ "Every value below that is a physical measurement is written as a STRING that "
31
+ 'already names its own unit, such as "1.46 meters", "3.0 seconds", or "91 '
32
+ 'degrees" -- so a field\'s name does not repeat the unit.'
33
+ )
34
+
35
+
36
+ def _m(value):
37
+ return f"{value} meters"
38
+
39
+
40
+ def _s(value):
41
+ return f"{value} seconds"
42
+
43
+
44
+ def _deg(value):
45
+ return f"{value} degrees"
46
+
47
+
48
+ def _fr(value):
49
+ return f"{value} frames"
50
+
51
+
52
+ def _unit_strings(code):
53
+ def pos(point):
54
+ return {
55
+ "x coordinate": _m(point["floor_x_meters"]),
56
+ "y coordinate": _m(point["floor_y_meters"]),
57
+ "height above floor": _m(point["height_above_floor_meters"]),
58
+ }
59
+
60
+ for object_class in code.get("objects", {}).values():
61
+ for instance in object_class.get("instances", ()):
62
+ if "position" in instance:
63
+ instance["position"] = pos(instance["position"])
64
+ if "bounding_box" in instance:
65
+ box = instance.pop("bounding_box")
66
+ instance["bounding box"] = {
67
+ "x coordinate": [_m(v) for v in box["floor_x_meters"]],
68
+ "y coordinate": [_m(v) for v in box["floor_y_meters"]],
69
+ "height above floor": [_m(v) for v in box["height_above_floor_meters"]],
70
+ }
71
+ if "dimensions_meters" in instance:
72
+ instance["dimensions"] = [_m(v) for v in instance.pop("dimensions_meters")]
73
+ if "longest_dimension_meters" in instance:
74
+ instance["longest dimension"] = _m(instance.pop("longest_dimension_meters"))
75
+ if "seen_in_video_frames" in instance:
76
+ instance["seen in video"] = _fr(instance.pop("seen_in_video_frames"))
77
+ if "room" in code:
78
+ if "outline" in code["room"]:
79
+ code["room"]["outline"] = [
80
+ {
81
+ "x coordinate": _m(point["floor_x_meters"]),
82
+ "y coordinate": _m(point["floor_y_meters"]),
83
+ }
84
+ for point in code["room"]["outline"]
85
+ ]
86
+ if "floor_area_square_meters" in code["room"]:
87
+ code["room"]["floor area"] = f"{code['room'].pop('floor_area_square_meters')} square meters"
88
+ if "camera_trajectory" in code:
89
+ camera = code.pop("camera_trajectory")
90
+ for waypoint in camera.get("waypoints", ()):
91
+ if "time_seconds" in waypoint:
92
+ waypoint["time"] = _s(waypoint.pop("time_seconds"))
93
+ if "floor_x_meters" in waypoint:
94
+ waypoint["x coordinate"] = _m(waypoint.pop("floor_x_meters"))
95
+ if "floor_y_meters" in waypoint:
96
+ waypoint["y coordinate"] = _m(waypoint.pop("floor_y_meters"))
97
+ if "heading_degrees" in waypoint:
98
+ waypoint["heading"] = _deg(waypoint.pop("heading_degrees"))
99
+ if "sample_interval_seconds" in camera:
100
+ camera["sample interval seconds"] = camera.pop("sample_interval_seconds")
101
+ code["camera trajectory"] = camera
102
+ if _CCF_L2 in code:
103
+ for neighbors in code[_CCF_L2].values():
104
+ for entry in neighbors.values():
105
+ if "distance_meters" in entry:
106
+ entry["distance"] = _m(entry.pop("distance_meters"))
107
+ if "closeness_rank" in entry:
108
+ entry["closeness rank"] = entry.pop("closeness_rank")
109
+ if "appearance_order" in code:
110
+ code["appearance order"] = code.pop("appearance_order")
111
+ return code
112
+
113
+
114
+ def ablate(code, level, evidence=True):
115
+ """Return prompt-facing spatial code at level 0, 1, or 2."""
116
+ code = copy.deepcopy(code)
117
+ code.pop("spatial code schema", None)
118
+ if not evidence:
119
+ for object_class in code.get("objects", {}).values():
120
+ for instance in object_class.get("instances", ()):
121
+ instance.pop("seen_in_video_frames", None)
122
+ if level == 2:
123
+ if _CCF in code:
124
+ code[_CCF_L2] = code.pop(_CCF)
125
+ return _unit_strings(code)
126
+
127
+ code.pop("appearance order", None)
128
+ code.pop("appearance_order", None)
129
+ ccf = code.pop(_CCF, None)
130
+ if ccf is not None:
131
+ classes = sorted(ccf)
132
+ code[_CCF_L1] = {
133
+ f"{a} to {b}": f"{ccf[a][b]['distance_meters']} meters"
134
+ for a, b in itertools.combinations(classes, 2)
135
+ if b in ccf.get(a, {})
136
+ }
137
+ if level == 1:
138
+ code.pop("camera_trajectory", None)
139
+ if "room" in code:
140
+ code["room"].pop("outline", None)
141
+ for object_class in code.get("objects", {}).values():
142
+ for instance in object_class.get("instances", ()):
143
+ instance.pop("bounding_box", None)
144
+ instance.pop("dimensions_meters", None)
145
+ return _unit_strings(code)
146
+
147
+ if level != 0:
148
+ raise ValueError(f"unknown ablation level {level!r}; expected 0, 1, or 2")
149
+ if "room" in code:
150
+ code["room"].pop("floor_area_square_meters", None)
151
+ code.pop(_CCF_L1, None)
152
+ for object_class in code.get("objects", {}).values():
153
+ object_class.pop("count", None)
154
+ for instance in object_class.get("instances", ()):
155
+ instance.pop("longest_dimension_meters", None)
156
+ return _unit_strings(code)
157
+
158
+
159
+ def _objects_par(level, evidence):
160
+ paragraph = (
161
+ "The objects section lists, for every object class, the individual objects that were "
162
+ 'detected in the room. Each object has a position given as "x coordinate", "y '
163
+ 'coordinate" and "height above floor": x coordinate is the object\'s distance along '
164
+ "one fixed horizontal direction of the room, y coordinate is the object's distance "
165
+ "along a second fixed horizontal direction perpendicular to the first, and height "
166
+ "above floor is the object's vertical distance above the floor; these directions are "
167
+ "the same for everything in the room."
168
+ )
169
+ if level != 1:
170
+ paragraph += (
171
+ ' Each object also has a "bounding box" giving a minimum and a maximum value '
172
+ "along each of x coordinate, y coordinate and height above floor, marking the "
173
+ "full extent of the object. Each object also has dimensions, the object's three "
174
+ "side lengths, measured along the object's own axes and listed from longest to shortest."
175
+ )
176
+ if level >= 1:
177
+ paragraph += (
178
+ " Each object class also has a count, the number of objects of that class that "
179
+ 'are in the room. Each object also has a "longest dimension", the length of '
180
+ "that object's single longest side"
181
+ + (" (the largest of its dimensions)" if level != 1 else "")
182
+ + "."
183
+ )
184
+ if evidence:
185
+ paragraph += (
186
+ ' Each object also has "seen in video", the number of video frames in which '
187
+ "that object was detected."
188
+ )
189
+ return paragraph
190
+
191
+
192
+ def _room_par(level):
193
+ paragraph = "The room section describes the room as a whole."
194
+ if level != 1:
195
+ paragraph += (
196
+ " It has an outline giving the shape of the room's floor as a polygon: a list of "
197
+ "corner points that, connected in order, trace the boundary of the room, and each "
198
+ "corner point is given as x coordinate and y coordinate."
199
+ )
200
+ if level >= 1:
201
+ paragraph += ' The room also has a "floor area", the total floor area of the room.'
202
+ return paragraph
203
+
204
+
205
+ def _camera_par():
206
+ return (
207
+ 'The "camera trajectory" lists waypoints along the path the recording camera moved '
208
+ "through the room while filming: each waypoint gives a time, the camera's location "
209
+ "at that time as x coordinate and y coordinate, and the direction the camera was "
210
+ "facing at that time as a heading."
211
+ )
212
+
213
+
214
+ def _distance_par(level):
215
+ if level == 0:
216
+ return ""
217
+ if level == 1:
218
+ return (
219
+ 'The "minimum distance between classes" section gives the minimum distance '
220
+ 'between every pair of object classes: each key names two classes as "A to B", '
221
+ "and its value is the distance between the closest points of those two classes. "
222
+ 'Each pair appears once; a pair may be listed as either "A to B" or "B to A", '
223
+ "so check both when looking one up."
224
+ )
225
+ return (
226
+ 'The "closest classes distance meters from" section gives, for every object class, '
227
+ "an entry for each other class containing a distance, the distance between the "
228
+ 'closest points of the two classes, and a "closeness rank", which orders the other '
229
+ "classes by their nearness to the class the entry is listed under, from the nearest, "
230
+ "rank 1, to the farthest, the largest rank."
231
+ )
232
+
233
+
234
+ def _appearance_par(level):
235
+ if level < 2:
236
+ return ""
237
+ return (
238
+ 'The "appearance order" section lists every object class in the order it first '
239
+ "appeared in the video, earliest first -- just the class names, already sorted; "
240
+ "there is no timestamp to read, only the order itself."
241
+ )
242
+
243
+
244
+ def _dir_base(level):
245
+ text = (
246
+ "To compute the number of objects of a class: go to the objects section, find the "
247
+ "class by its name, and count the entries in its instances list.\n"
248
+ )
249
+ if level != 1:
250
+ text += (
251
+ "To compute the size of an object: read its dimensions, the object's three side "
252
+ "lengths, and take the largest; that is its longest side.\n"
253
+ "To compute the size of the room: work out the area of the polygon formed by the "
254
+ "room's outline corner points.\n"
255
+ 'To compute the distance between two objects: for each of the three axes take the '
256
+ 'gap between their "bounding box" ranges (zero if they overlap, otherwise the '
257
+ "distance between the nearer edges), then square the three gaps, add them, and "
258
+ "take the square root.\n"
259
+ )
260
+ text += (
261
+ 'To compute the order in which classes appeared: use "appearance order" when it is '
262
+ "present; otherwise use the video frames."
263
+ )
264
+ return text
265
+
266
+
267
+ def _dir_l1_add(level):
268
+ if level == 1:
269
+ distance_text = (
270
+ 'To read the distance between two classes directly: find their pair in "minimum '
271
+ 'distance between classes" -- check both "A to B" and "B to A" -- and read off '
272
+ "its value.\n"
273
+ "To read which of several named classes is closest to a class X directly: look up "
274
+ 'each candidate\'s pair with X in "minimum distance between classes" and pick the '
275
+ "smallest distance."
276
+ )
277
+ else:
278
+ distance_text = (
279
+ 'To read the distance between two classes directly: in "closest classes distance '
280
+ 'meters from", one class\'s entry for the other has a distance, the distance '
281
+ "between the closest points of the two classes.\n"
282
+ "To read which of several named classes is closest to a class X directly: compare "
283
+ 'their distance under "closest classes distance meters from"[X] and pick the smallest.'
284
+ )
285
+ return (
286
+ "To read the number of objects of a class directly: its count is the number of objects "
287
+ "of that class that are in the room.\n"
288
+ 'To read the size of an object directly: its "longest dimension" is the length of '
289
+ "its single longest side.\n"
290
+ 'To read the size of the room directly: its "floor area" is the total floor area of '
291
+ "the room.\n"
292
+ + distance_text
293
+ )
294
+
295
+
296
+ _DIR_L2_ADD = (
297
+ 'To read the ranking of the classes by their nearness to a class X directly: in "closest '
298
+ 'classes distance meters from"[X], each entry\'s "closeness rank" orders the other classes '
299
+ "by their nearness to X, from the nearest, rank 1, to the farthest, the largest rank; to "
300
+ "find the closest of several named classes pick the one with the smallest rank, comparing "
301
+ "only the classes named in the question.\n"
302
+ 'To read the order in which the classes appeared directly: "appearance order" lists every '
303
+ "class already sorted from the earliest to the latest, so read it from top to bottom."
304
+ )
305
+
306
+
307
+ def _directions(level):
308
+ text = "How to use the spatial code to answer the question.\n" + _dir_base(level)
309
+ if level >= 1:
310
+ text += "\n" + _dir_l1_add(level)
311
+ if level >= 2:
312
+ text += "\n" + _DIR_L2_ADD
313
+ return text
314
+
315
+
316
+ def legend(level=2, prompt_level=1, evidence=True):
317
+ paragraphs = [
318
+ _HEAD,
319
+ _UNITS_NOTE,
320
+ _objects_par(level, evidence),
321
+ _room_par(level),
322
+ _camera_par() if level != 1 else "",
323
+ _distance_par(level),
324
+ _appearance_par(level),
325
+ ]
326
+ if prompt_level >= 1:
327
+ paragraphs.append(_directions(level))
328
+ return "\n\n".join(paragraph for paragraph in paragraphs if paragraph)
329
+
330
+
331
+ LEGENDS = {0: legend(0), 1: legend(1), 2: legend(2)}
332
+ # The field-specific legend is appended by build_prompt(). Keeping this short shared
333
+ # prefix avoids describing fields that the question-specific projection removed.
334
+ PRE_PROMPT = _HEAD + "\n\n" + _UNITS_NOTE
335
+
336
+ FRAMES_EVIDENCE_NOTE = (
337
+ "Known limitations of the spatial code (it was built automatically, and some of its values "
338
+ "are less reliable than others -- use the video frames to cross-check them):\n"
339
+ "- An object class's count is a LOWER BOUND (the most instances ever seen at once in a "
340
+ "single video frame). If the frames clearly show more instances than the code lists, trust "
341
+ "the frames.\n"
342
+ "- An object's size/extent comes from a single frame's 3D points and can be cut short by "
343
+ "occlusion. If the frames clearly show the object is larger than the code says, trust the "
344
+ "frames.\n"
345
+ "- The appearance order was derived by a heuristic and can be wrong for classes that enter "
346
+ "the video gradually or at the edge of the view. The frames themselves are the ground truth "
347
+ "for what appears when.\n"
348
+ "- Object positions and inter-object distances are the code's most reliable values -- "
349
+ "prefer the code over eyeballing the frames for those."
350
+ )
351
+
352
+
353
+
354
+ def _project_for_question(code, question_type, question, options=None):
355
+ """Keep only answer-relevant sections while retaining every object class.
356
+
357
+ This is a field-level projection of the raw v2 cache, before v2 unit/key
358
+ rendering. It deliberately does not filter individual classes: for example,
359
+ absolute-distance questions receive the complete distance matrix.
360
+ """
361
+ source = copy.deepcopy(code)
362
+ source.pop("spatial code schema", None)
363
+ objects = source.get("objects", {})
364
+
365
+ if question_type == "object_counting":
366
+ return {"objects": {
367
+ name: {"count": value.get("count")}
368
+ for name, value in objects.items()
369
+ }}
370
+
371
+ if question_type == "object_size_estimation":
372
+ return {"objects": {
373
+ name: {"instances": [
374
+ {"longest_dimension_meters": instance["longest_dimension_meters"]}
375
+ for instance in value.get("instances", [])
376
+ if "longest_dimension_meters" in instance
377
+ ]}
378
+ for name, value in objects.items()
379
+ }}
380
+
381
+ if question_type == "room_size_estimation":
382
+ return {"room": {"floor_area_square_meters":
383
+ source.get("room", {}).get("floor_area_square_meters")}}
384
+
385
+ if question_type == "object_abs_distance":
386
+ # Keep the complete matrix. Only the ordering field is irrelevant here;
387
+ # each matrix entry keeps its distance and v2 rank metadata.
388
+ return {_CCF: copy.deepcopy(source.get(_CCF, {}))}
389
+
390
+ if question_type == "object_rel_distance":
391
+ # The question may name only some candidates, but the complete v2 matrix
392
+ # is retained so the model can resolve every option without guessing.
393
+ return {_CCF: copy.deepcopy(source.get(_CCF, {}))}
394
+
395
+ if question_type in {
396
+ "object_rel_direction_easy", "object_rel_direction_medium",
397
+ "object_rel_direction_hard", "route_planning",
398
+ }:
399
+ return {"objects": {
400
+ name: {"instances": [
401
+ {"position": copy.deepcopy(instance["position"])}
402
+ for instance in value.get("instances", [])
403
+ if "position" in instance
404
+ ]}
405
+ for name, value in objects.items()
406
+ }}
407
+
408
+ if question_type == "obj_appearance_order":
409
+ return {"appearance_order": copy.deepcopy(source.get("appearance_order", []))}
410
+
411
+ raise ValueError(f"unrecognized question_type: {question_type!r}")
412
+
413
+
414
+ LEGEND_V2 = """SPATIAL CODE of a scanned room (JSON, built from the video). Answer using ONLY its values.
415
+ - objects[X].count = number of instances of class X in the room (a lower-bound count: the most
416
+ ever seen at once in a single video frame).
417
+ - objects[X].instances = up to `count` individual objects of class X, each with:
418
+ - position = {floor_x_meters, floor_y_meters, height_above_floor_meters}: location in meters;
419
+ height 0.0 = resting on the floor.
420
+ - longest_dimension_meters = the object's single longest side, in meters (x100 = centimeters).
421
+ - bounding_box = full 3D extent, same named axes as position, each a [minimum, maximum] pair.
422
+ - first_seen_seconds = video timestamp (seconds from start) when this instance first appeared.
423
+ - seen_in_video_frames = number of video frames this instance was detected in. A very low
424
+ value (a few frames) means weak evidence: the instance may be a false detection.
425
+ - room.outline = the room's floor boundary as a polygon of {floor_x_meters, floor_y_meters}
426
+ vertices (same axes as positions).
427
+ - room.floor_area_square_meters = total floor area of the room, in square meters.
428
+ - closest_classes_from[X][Y] = {closeness_rank, distance_meters} for every other class Y as seen
429
+ from class X. distance_meters is between the closest points of X and Y (the lookup for "how far
430
+ is Y from X"). closeness_rank ranks all classes by nearness to X: rank 1 = the closest class.
431
+ To pick which of several given classes is closest to X, look up each one's closeness_rank under
432
+ closest_classes_from[X] and choose the class with the SMALLEST rank (farthest = largest rank).
433
+ - camera_trajectory.waypoints = the recording camera's path: {time_seconds, floor_x_meters,
434
+ floor_y_meters, heading_degrees}, sampled every sample_interval_seconds. Positions use the
435
+ same floor axes as object positions.
436
+ - appearance_order = every detected class with its first-appearance time, ALREADY SORTED
437
+ earliest-first."""
438
+
439
+ # Exact word-for-word sections from LEGEND_V2, selected by question type.
440
+ _V2_HEADER = "SPATIAL CODE of a scanned room (JSON, built from the video). Answer using ONLY its values."
441
+ _V2_COUNT = """- objects[X].count = number of instances of class X in the room (a lower-bound count: the most
442
+ ever seen at once in a single video frame)."""
443
+ _V2_INSTANCES = """- objects[X].instances = up to `count` individual objects of class X, each with:"""
444
+ _V2_POSITION = """ - position = {floor_x_meters, floor_y_meters, height_above_floor_meters}: location in meters;
445
+ height 0.0 = resting on the floor."""
446
+ _V2_SIZE = """ - longest_dimension_meters = the object's single longest side, in meters (x100 = centimeters)."""
447
+ _V2_ROOM_AREA = "- room.floor_area_square_meters = total floor area of the room, in square meters."
448
+ _V2_DISTANCE = """- closest_classes_from[X][Y] = {closeness_rank, distance_meters} for every other class Y as seen
449
+ from class X. distance_meters is between the closest points of X and Y (the lookup for "how far
450
+ is Y from X"). closeness_rank ranks all classes by nearness to X: rank 1 = the closest class.
451
+ To pick which of several given classes is closest to X, look up each one's closeness_rank under
452
+ closest_classes_from[X] and choose the class with the SMALLEST rank (farthest = largest rank)."""
453
+ _V2_APPEARANCE = """- appearance_order = every detected class with its first-appearance time, ALREADY SORTED
454
+ earliest-first."""
455
+
456
+
457
+ def _question_legend(question_type):
458
+ sections = [_V2_HEADER]
459
+ if question_type == "object_counting":
460
+ sections.append(_V2_COUNT)
461
+ elif question_type == "object_size_estimation":
462
+ sections.extend([_V2_INSTANCES, _V2_SIZE])
463
+ elif question_type == "room_size_estimation":
464
+ sections.append(_V2_ROOM_AREA)
465
+ elif question_type in {"object_abs_distance", "object_rel_distance"}:
466
+ sections.append(_V2_DISTANCE)
467
+ elif question_type in {
468
+ "object_rel_direction_easy", "object_rel_direction_medium",
469
+ "object_rel_direction_hard", "route_planning",
470
+ }:
471
+ sections.extend([_V2_INSTANCES, _V2_POSITION])
472
+ elif question_type == "obj_appearance_order":
473
+ sections.append(_V2_APPEARANCE)
474
+ else:
475
+ raise ValueError(f"unrecognized question_type: {question_type!r}")
476
+ return "\n".join(sections)
477
+
478
+ def _post_prompt(question_type):
479
+ if question_type in NA_QUESTION_TYPES:
480
+ return "\n".join([STEP_BY_STEP_REASONING_PROMPT, NA_POST_PROMPT])
481
+ if question_type in MCA_QUESTION_TYPES:
482
+ return "\n".join([STEP_BY_STEP_REASONING_PROMPT, MCA_POST_PROMPT])
483
+ raise ValueError(
484
+ f"unknown question_type {question_type!r}; "
485
+ f"expected one of {MCA_QUESTION_TYPES + NA_QUESTION_TYPES}"
486
+ )
487
+
488
+
489
+ def _assemble(pre_prompt, code, question_type, question, options=None):
490
+ code_text = json.dumps(code, indent=1)
491
+ if question_type in NA_QUESTION_TYPES:
492
+ return "\n".join([pre_prompt, "Spatial code:", code_text, question, _post_prompt(question_type)])
493
+ if question_type in MCA_QUESTION_TYPES:
494
+ if not options:
495
+ raise ValueError(f"question_type {question_type!r} requires options")
496
+ return "\n".join(
497
+ [
498
+ pre_prompt,
499
+ "Spatial code:",
500
+ code_text,
501
+ question,
502
+ "Options:\n" + "\n".join(options),
503
+ _post_prompt(question_type),
504
+ ]
505
+ )
506
+ return _post_prompt(question_type)
507
+
508
+
509
+ def build_ablation_prompt(code, question, question_type, options, level, prompt_level=1, evidence=True, frames_note=False):
510
+ rendered = ablate(code, level, evidence=evidence)
511
+ pre_prompt = legend(level, prompt_level=prompt_level, evidence=evidence)
512
+ if frames_note:
513
+ pre_prompt += "\n\n" + FRAMES_EVIDENCE_NOTE
514
+ return _assemble(pre_prompt, rendered, question_type, question, options)
515
+
516
+
517
+ def build_prompt(spatial_code, question_type, question, options=None, frames_note=False):
518
+ """Return the single v2 L2 spatial-code prompt."""
519
+ rendered = _project_for_question(spatial_code, question_type, question, options)
520
+ pre_prompt = _question_legend(question_type)
521
+ if frames_note:
522
+ pre_prompt += "\n\n" + FRAMES_EVIDENCE_NOTE
523
+ return _assemble(pre_prompt, rendered, question_type, question, options)
harness/B/run.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 import (
25
+ protocol_for_question,
26
+ question_group,
27
+ resolve_protocol_budgets,
28
+ ) # noqa: E402
29
+ from harness.A.run import _scalar_score, load_questions, vsi_official_eval # noqa: E402
30
+ from harness.B import ( # noqa: E402
31
+ DEFAULT_DEPTH,
32
+ DEFAULT_INPUT_SELECTION,
33
+ DEFAULT_SPATIAL_CODE_FORMAT,
34
+ DEFAULT_TRACKING,
35
+ DEPTH_VARIANTS,
36
+ FRAMES_PER_VIDEO,
37
+ INPUT_SELECTIONS,
38
+ RESULTS_DIR,
39
+ TRACKING_MODES,
40
+ )
41
+ from harness.B import prompts as code_prompts # noqa: E402
42
+ from harness.B import spatial_codes # noqa: E402
43
+
44
+
45
+ def results_dir_for(
46
+ model,
47
+ protocol,
48
+ spatial_code_format,
49
+ depth,
50
+ tracking,
51
+ input_selection,
52
+ frame_count,
53
+ results_dir=None,
54
+ ):
55
+ """Return the result root isolated by model + protocol + fixed explicit spatial code +
56
+ depth + tracking + input + frames. ``protocol`` is "base" (16-token) or
57
+ "extended-<reasoning budget>" (e.g. "extended-512") -- a real path segment, so
58
+ records from different protocols OR different reasoning budgets can never collide
59
+ on disk."""
60
+ if results_dir is not None:
61
+ return Path(results_dir)
62
+ root = RESULTS_DIR / model / spatial_code_format / depth / tracking
63
+ if input_selection == "video":
64
+ return root / "video"
65
+ return root / input_selection / str(frame_count)
66
+
67
+
68
+ def _build_record(
69
+ row, prompt, answer, metric_name, score, model, model_path, code_info
70
+ ):
71
+ """Assemble one question's full, untruncated result record (nothing summarized)."""
72
+ return {
73
+ "model": model,
74
+ "model_path": str(model_path),
75
+ "device": answer["device"],
76
+ "dtype": answer["dtype"],
77
+ "library_versions": answer["library_versions"],
78
+ "condition": (
79
+ f"{code_info['protocol']}:{code_info['spatial_code_format']}:"
80
+ f"{code_info['depth']}:{code_info['tracking']}:"
81
+ + (
82
+ "video"
83
+ if code_info["input_selection"] == "video"
84
+ else f"{code_info['input_selection']}:{code_info['frame_count']}"
85
+ )
86
+ ),
87
+ "protocol": code_info["protocol"],
88
+ "question_group": question_group(row["question_type"]),
89
+ "spatial_code_format": code_info["spatial_code_format"],
90
+ "input_selection": code_info["input_selection"],
91
+ "frame_count": code_info["frame_count"],
92
+ "depth": code_info["depth"],
93
+ "tracking": code_info["tracking"],
94
+ "spatial_code_path": code_info["spatial_code_path"],
95
+ "scene": row["scene_name"],
96
+ "dataset": row.get("dataset"),
97
+ "question_id": row["id"],
98
+ "question_type": row["question_type"],
99
+ "question": row["question"],
100
+ "options": row.get("options"),
101
+ "full_prompt": prompt,
102
+ "rendered_prompt": answer["prompt_text"],
103
+ "answer_expected": row["ground_truth"],
104
+ "answer_given": answer["answer_text"],
105
+ "answer_raw": answer["answer_raw"],
106
+ "input_token_count": answer["input_token_count"],
107
+ "vision_input_shapes": answer["vision_input_shapes"],
108
+ "output_token_ids": answer["output_token_ids"],
109
+ "output_token_count": answer["output_token_count"],
110
+ "hit_token_limit": answer["hit_token_limit"],
111
+ "eos_token_ids": answer["eos_token_ids"],
112
+ "generation_seconds": answer["generation_seconds"],
113
+ "generation_config": answer["generation_config"],
114
+ "reasoning_text": answer.get("reasoning_text"),
115
+ "reasoning_raw": answer.get("reasoning_raw"),
116
+ "reasoning_token_ids": answer.get("reasoning_token_ids"),
117
+ "reasoning_token_count": answer.get("reasoning_token_count"),
118
+ "reasoning_hit_limit": answer.get("reasoning_hit_limit"),
119
+ "forced": answer.get("forced", False),
120
+ "forced_input_token_count": answer.get("forced_input_token_count"),
121
+ "metric": metric_name,
122
+ "score": score,
123
+ }
124
+
125
+
126
+ def write_question_result(
127
+ row,
128
+ prompt,
129
+ answer,
130
+ metric_name,
131
+ score,
132
+ model,
133
+ model_path,
134
+ code_info,
135
+ results_dir=None,
136
+ ):
137
+ """Write one question's full, untruncated result record. Return (path, record)."""
138
+ record = _build_record(
139
+ row, prompt, answer, metric_name, score, model, model_path, code_info
140
+ )
141
+ root = results_dir_for(
142
+ model,
143
+ code_info["protocol"],
144
+ code_info["spatial_code_format"],
145
+ code_info["depth"],
146
+ code_info["tracking"],
147
+ code_info["input_selection"],
148
+ code_info["frame_count"],
149
+ results_dir,
150
+ )
151
+ scene_dir = root / record["scene"]
152
+ scene_dir.mkdir(parents=True, exist_ok=True)
153
+ path = scene_dir / f"{row['id']}.json"
154
+ with path.open("w", encoding="utf-8") as stream:
155
+ json.dump(record, stream, indent=1)
156
+ return path, record
157
+
158
+
159
+ def run(
160
+ model,
161
+ spatial_code_format=DEFAULT_SPATIAL_CODE_FORMAT,
162
+ input_selection=DEFAULT_INPUT_SELECTION,
163
+ frame_count=FRAMES_PER_VIDEO,
164
+ video=False,
165
+ depth=DEFAULT_DEPTH,
166
+ tracking=DEFAULT_TRACKING,
167
+ scene=None,
168
+ scenes=None,
169
+ limit=None,
170
+ device="cuda",
171
+ jsonl_path=None,
172
+ results_dir=None,
173
+ write_results=True,
174
+ adapter=None,
175
+ extended=True,
176
+ reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
177
+ force_budget=MAX_NEW_TOKENS,
178
+ question_ids=None,
179
+ ):
180
+ """Answer every matching question with one model, given its scene's spatial code as
181
+ text (no video frames). Each question's full record is written to its own JSON file
182
+ as soon as it is answered (unless ``write_results=False``).
183
+
184
+ Uses ``adapter.answer_extended`` (a large ``reasoning_budget`` first pass, with a
185
+ short forced second call only if the model doesn't conclude within it) as the
186
+ standing default protocol -- since working through a full spatial-code JSON before
187
+ answering benefits from more room than a short visual caption does.
188
+ ``extended=False`` runs harness.A's exact fixed 16-token base protocol instead
189
+ (plain ``adapter.answer``), so the protocol x representation grid can be measured
190
+ with the identical generation mechanism in every cell.
191
+
192
+ Pass a pre-loaded ``adapter`` (as harness.B.launch's persistent per-GPU workers do)
193
+ to reuse one already-loaded model across many calls; the caller then owns unloading
194
+ it. Without one, ``run`` loads and unloads its own adapter, same as harness.A.
195
+ """
196
+ if video:
197
+ input_selection = "video"
198
+ frame_count = None
199
+ elif frame_count is None or frame_count < 1:
200
+ raise ValueError("frame_count must be positive in frames mode")
201
+ rows = load_questions(jsonl_path, scene, scenes, limit)
202
+ if question_ids is not None:
203
+ rows = [row for row in rows if row["id"] in question_ids]
204
+ if not rows:
205
+ return []
206
+ owns_adapter = adapter is None
207
+ if owns_adapter:
208
+ adapter = vlm_models.get_adapter(model)
209
+ adapter.load_model(device)
210
+ code_cache = {}
211
+ results = []
212
+ try:
213
+ for row in rows:
214
+ protocol = protocol_for_question(row["question_type"])
215
+ scene_id = row["scene_name"]
216
+ if scene_id not in code_cache:
217
+ code, path = spatial_codes.load_spatial_code(
218
+ scene_id,
219
+ depth,
220
+ input_selection,
221
+ tracking,
222
+ frame_count,
223
+ spatial_code_format,
224
+ )
225
+ code_cache[scene_id] = {"code": code, "path": path}
226
+ cached = code_cache[scene_id]
227
+ prompt = code_prompts.build_prompt(
228
+ cached["code"],
229
+ row["question_type"],
230
+ row["question"],
231
+ row.get("options"),
232
+ )
233
+ answer = (
234
+ adapter.answer_extended(
235
+ [],
236
+ prompt,
237
+ reasoning_budget=reasoning_budget,
238
+ force_budget=force_budget,
239
+ )
240
+ if protocol == "thinking"
241
+ else adapter.answer([], prompt, max_new_tokens=MAX_NEW_TOKENS)
242
+ )
243
+ doc = {
244
+ "question_type": row["question_type"],
245
+ "ground_truth": row["ground_truth"],
246
+ }
247
+ score_doc = vsi_official_eval.vsibench_process_results(
248
+ doc, [answer["answer_text"]]
249
+ )["vsibench_score"]
250
+ metric_name, score = _scalar_score(row["question_type"], score_doc)
251
+ code_info = {
252
+ "protocol": protocol,
253
+ "spatial_code_format": spatial_code_format,
254
+ "input_selection": input_selection,
255
+ "frame_count": frame_count,
256
+ "depth": depth,
257
+ "tracking": tracking,
258
+ "spatial_code_path": cached["path"],
259
+ }
260
+ if write_results:
261
+ path, record = write_question_result(
262
+ row,
263
+ prompt,
264
+ answer,
265
+ metric_name,
266
+ score,
267
+ model,
268
+ adapter.model_path,
269
+ code_info,
270
+ results_dir,
271
+ )
272
+ else:
273
+ path = None
274
+ record = _build_record(
275
+ row,
276
+ prompt,
277
+ answer,
278
+ metric_name,
279
+ score,
280
+ model,
281
+ adapter.model_path,
282
+ code_info,
283
+ )
284
+ record["result_path"] = str(path) if path else None
285
+ results.append(record)
286
+ finally:
287
+ if owns_adapter:
288
+ adapter.unload()
289
+ return results
290
+
291
+
292
+ def main():
293
+ parser = argparse.ArgumentParser()
294
+ parser.add_argument("--model", required=True, choices=vlm_models.available_models())
295
+ parser.add_argument("--scene", default=None, help="restrict to one VSI-Bench scene")
296
+ parser.add_argument(
297
+ "--input-selection",
298
+ default=None,
299
+ choices=INPUT_SELECTIONS,
300
+ dest="input_selection",
301
+ )
302
+ input_mode = parser.add_mutually_exclusive_group(required=True)
303
+ input_mode.add_argument("--frames", type=int)
304
+ input_mode.add_argument("--video", action="store_true")
305
+ parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS)
306
+ parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES)
307
+ parser.add_argument(
308
+ "--limit", type=int, default=None, help="cap the number of questions"
309
+ )
310
+ parser.add_argument("--device", default="cuda")
311
+ parser.add_argument(
312
+ "--results-dir",
313
+ default=None,
314
+ help="override the default results/B/<model>/explicit/"
315
+ "<depth>/<tracking>/{<input>/<frames>|video} root",
316
+ )
317
+ parser.add_argument(
318
+ "--no-write",
319
+ action="store_true",
320
+ help="skip writing per-question JSON files; print/score only",
321
+ )
322
+ parser.add_argument(
323
+ "--reasoning-budget",
324
+ type=int,
325
+ default=None,
326
+ help="thinking questions only (default: 2048)",
327
+ )
328
+ parser.add_argument(
329
+ "--force-budget",
330
+ type=int,
331
+ default=None,
332
+ help="thinking questions only (default: 16)",
333
+ )
334
+ args = parser.parse_args()
335
+ if args.video:
336
+ if args.input_selection is not None:
337
+ parser.error("--input-selection cannot be used with --video")
338
+ else:
339
+ if args.input_selection is None:
340
+ parser.error("--input-selection is required with --frames")
341
+ if args.frames < 1:
342
+ parser.error("--frames must be positive")
343
+ resolve_protocol_budgets(parser, args)
344
+ results = run(
345
+ args.model,
346
+ spatial_code_format=DEFAULT_SPATIAL_CODE_FORMAT,
347
+ input_selection=args.input_selection,
348
+ frame_count=args.frames,
349
+ video=args.video,
350
+ depth=args.depth,
351
+ tracking=args.tracking,
352
+ scene=args.scene,
353
+ limit=args.limit,
354
+ device=args.device,
355
+ results_dir=args.results_dir,
356
+ write_results=not args.no_write,
357
+ extended=True,
358
+ reasoning_budget=args.reasoning_budget,
359
+ force_budget=args.force_budget,
360
+ )
361
+
362
+ for result in results:
363
+ print(
364
+ f"[{result['scene']}#{result['question_id']}] {result['question_type']}: "
365
+ f"pred={result['answer_given']!r} gt={result['answer_expected']!r} "
366
+ f"score={result['score']} ({result['generation_seconds']:.2f}s) -> "
367
+ f"{result['result_path']}"
368
+ )
369
+ if results:
370
+ mean_score = sum(r["score"] for r in results) / len(results)
371
+ total_seconds = sum(r["generation_seconds"] for r in results)
372
+ print(
373
+ f"\n{len(results)} questions, mean vsibench_score={mean_score:.4f}, "
374
+ f"total generation time={total_seconds:.1f}s"
375
+ )
376
+
377
+
378
+ if __name__ == "__main__":
379
+ main()
harness/B/spatial_codes.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load one scene's on-disk explicit spatial code 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(
19
+ scene, depth, input_selection, tracking, frame_count, spatial_code_format
20
+ ):
21
+ """Return (spatial code dict, path it was loaded from)."""
22
+ if spatial_code_format not in SPATIAL_CODE_FORMATS:
23
+ raise ValueError(
24
+ f"unknown spatial-code format {spatial_code_format!r}; "
25
+ f"expected one of {SPATIAL_CODE_FORMATS}"
26
+ )
27
+ path = spatial_code_path(
28
+ scene, depth, input_selection, tracking, frame_count, spatial_code_format
29
+ )
30
+ if not Path(path).is_file():
31
+ raise FileNotFoundError(f"no spatial code found for scene {scene!r} at {path}")
32
+ with open(path, encoding="utf-8") as stream:
33
+ return json.load(stream), path
harness/B/sweep.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sweep any set of models 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 import resolve_protocol_budgets # noqa: E402
26
+ from harness.A import EXTENDED_MAX_NEW_TOKENS # noqa: E402
27
+ from harness.A.sweep import _parse_csv_choice, _parse_frame_counts # noqa: E402
28
+ from harness.B import ( # noqa: E402
29
+ DEFAULT_DEPTH,
30
+ DEFAULT_SPATIAL_CODE_FORMAT,
31
+ DEFAULT_TRACKING,
32
+ DEPTH_VARIANTS,
33
+ INPUT_SELECTIONS,
34
+ TRACKING_MODES,
35
+ )
36
+ from harness.B import launch as harness_launch # noqa: E402
37
+
38
+
39
+ def build_plan(
40
+ models, spatial_code_formats, input_selections, frame_counts, depths, trackings
41
+ ):
42
+ """Return every (model, spatial_code_format, depth, tracking, input_selection,
43
+ frame_count) 6-tuple in the sweep, in a stable, cheapest-first-ish order (frame
44
+ count sorted first)."""
45
+ return [
46
+ (model, spatial_code_format, depth, tracking, input_selection, frame_count)
47
+ for frame_count in sorted(frame_counts)
48
+ for model in models
49
+ for spatial_code_format in spatial_code_formats
50
+ for depth in depths
51
+ for tracking in trackings
52
+ for input_selection in input_selections
53
+ ]
54
+
55
+
56
+ def sweep(
57
+ models,
58
+ spatial_code_formats,
59
+ input_selections,
60
+ frame_counts,
61
+ selected_scenes,
62
+ video=False,
63
+ depths=(DEFAULT_DEPTH,),
64
+ trackings=(DEFAULT_TRACKING,),
65
+ results_dir=None,
66
+ rebuild=False,
67
+ extended=True,
68
+ reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
69
+ ):
70
+ """Run every sweep combination across all visible GPUs."""
71
+ plan = build_plan(
72
+ models, spatial_code_formats, input_selections, frame_counts, depths, trackings
73
+ )
74
+ for index, (
75
+ model,
76
+ spatial_code_format,
77
+ depth,
78
+ tracking,
79
+ input_selection,
80
+ frame_count,
81
+ ) in enumerate(plan, start=1):
82
+ print(
83
+ f"=== sweep {index}/{len(plan)}: {model}/"
84
+ f"{spatial_code_format}/{depth}/{tracking}/"
85
+ + ("video" if video else f"{input_selection}/{frame_count}")
86
+ + " ===",
87
+ flush=True,
88
+ )
89
+ harness_launch.launch(
90
+ model,
91
+ spatial_code_format,
92
+ input_selection,
93
+ frame_count,
94
+ selected_scenes,
95
+ video=video,
96
+ depth=depth,
97
+ tracking=tracking,
98
+ results_dir=results_dir,
99
+ rebuild=rebuild,
100
+ extended=extended,
101
+ reasoning_budget=reasoning_budget,
102
+ )
103
+
104
+
105
+ def main():
106
+ parser = argparse.ArgumentParser()
107
+ parser.add_argument("scene", nargs="?")
108
+ parser.add_argument(
109
+ "--scenes",
110
+ help="comma-separated scenes (cannot be combined with positional scene)",
111
+ )
112
+ parser.add_argument(
113
+ "--models",
114
+ required=True,
115
+ help=f"comma-separated models (or 'all'); one of {vlm_models.available_models()}",
116
+ )
117
+ parser.add_argument(
118
+ "--input-selections",
119
+ required=False,
120
+ dest="input_selections",
121
+ help=f"comma-separated selections (or 'all'); one of {INPUT_SELECTIONS}",
122
+ )
123
+ input_mode = parser.add_mutually_exclusive_group(required=True)
124
+ input_mode.add_argument(
125
+ "--frames", help="comma-separated frame counts, e.g. 16,32,64"
126
+ )
127
+ input_mode.add_argument("--video", action="store_true")
128
+ parser.add_argument(
129
+ "--depths",
130
+ default=DEFAULT_DEPTH,
131
+ help=f"comma-separated depths (or 'all'); one of {DEPTH_VARIANTS}",
132
+ )
133
+ parser.add_argument(
134
+ "--trackings",
135
+ default=DEFAULT_TRACKING,
136
+ help=f"comma-separated tracking modes (or 'all'); one of {TRACKING_MODES}",
137
+ )
138
+ parser.add_argument("--results-dir", default=None)
139
+ parser.add_argument("--rebuild", action="store_true")
140
+ parser.add_argument(
141
+ "--reasoning-budget",
142
+ type=int,
143
+ default=None,
144
+ dest="reasoning_budget",
145
+ help="thinking-protocol first-pass budget (the calibrated value from "
146
+ "analysis/preregistration.md, e.g. 512)",
147
+ )
148
+ args = parser.parse_args()
149
+ resolve_protocol_budgets(parser, args)
150
+ if args.scene and args.scenes:
151
+ parser.error("positional scene and --scenes cannot be used together")
152
+
153
+ try:
154
+ models = _parse_csv_choice(
155
+ args.models, vlm_models.available_models(), "--models"
156
+ )
157
+ spatial_code_formats = (DEFAULT_SPATIAL_CODE_FORMAT,)
158
+ if args.video:
159
+ if args.input_selections is not None:
160
+ raise ValueError("--input-selections cannot be used with --video")
161
+ input_selections = ["video"]
162
+ frame_counts = [None]
163
+ else:
164
+ if args.input_selections is None:
165
+ raise ValueError("--input-selections is required with --frames")
166
+ input_selections = _parse_csv_choice(
167
+ args.input_selections, INPUT_SELECTIONS, "--input-selections"
168
+ )
169
+ frame_counts = _parse_frame_counts(args.frames)
170
+ depths = _parse_csv_choice(args.depths, DEPTH_VARIANTS, "--depths")
171
+ trackings = _parse_csv_choice(args.trackings, TRACKING_MODES, "--trackings")
172
+ except ValueError as exc:
173
+ parser.error(str(exc))
174
+
175
+ if args.scenes is not None:
176
+ selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
177
+ if not selected:
178
+ parser.error("--scenes must contain at least one scene")
179
+ selected = list(dict.fromkeys(selected))
180
+ else:
181
+ from harness.A.launch import scenes
182
+
183
+ selected = [args.scene] if args.scene else scenes()
184
+
185
+ sweep(
186
+ models,
187
+ spatial_code_formats,
188
+ input_selections,
189
+ frame_counts,
190
+ selected,
191
+ video=args.video,
192
+ depths=depths,
193
+ trackings=trackings,
194
+ results_dir=args.results_dir,
195
+ rebuild=args.rebuild,
196
+ extended=True,
197
+ reasoning_budget=args.reasoning_budget,
198
+ )
199
+
200
+
201
+ if __name__ == "__main__":
202
+ main()
harness/C/__init__.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Harness C supplies both visual input and explicit spatial code to the model.
2
+
3
+ The visual input (sampled frames or video) and spatial-code source (frame-derived or
4
+ video-derived) are configured independently. Changing one never changes the other.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from pathlib import Path
11
+
12
+ from harness.A import (
13
+ DO_SAMPLE,
14
+ FRAME_SELECTIONS,
15
+ JSONL,
16
+ MAX_NEW_TOKENS,
17
+ MODEL_PATHS,
18
+ TEMPERATURE,
19
+ WORKSPACE_ROOT,
20
+ )
21
+ from harness.B import (
22
+ DEFAULT_DEPTH,
23
+ DEFAULT_INPUT_SELECTION,
24
+ DEFAULT_SPATIAL_CODE_FORMAT,
25
+ DEFAULT_TRACKING,
26
+ DEPTH_VARIANTS,
27
+ INPUT_SELECTIONS,
28
+ TRACKING_MODES,
29
+ )
30
+
31
+ assert INPUT_SELECTIONS == FRAME_SELECTIONS # one shared vocabulary drives both sources
32
+
33
+ FRAMES_PER_VIDEO = int(os.environ.get("VSI_HARNESS_C_FRAMES_PER_VIDEO", "32"))
34
+
35
+ # One JSON per question, matching harness.A/B's layout:
36
+ # results/C/<model>/explicit/<depth>/<tracking>/code/.../visual/.../<scene>/<question_id>.json
37
+ RESULTS_DIR = Path(os.environ.get("VSI_HARNESS_C_RESULTS_DIR", "/root/results/C"))
harness/C/launch.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 import resolve_protocol_budgets # noqa: E402
29
+ from harness.A.launch import scenes # noqa: E402
30
+ from harness.B import ( # noqa: E402
31
+ DEFAULT_DEPTH,
32
+ DEFAULT_INPUT_SELECTION,
33
+ DEFAULT_SPATIAL_CODE_FORMAT,
34
+ DEFAULT_TRACKING,
35
+ DEPTH_VARIANTS,
36
+ INPUT_SELECTIONS,
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,
53
+ results,
54
+ model,
55
+ spatial_code_format,
56
+ input_selection,
57
+ frame_count,
58
+ video,
59
+ spatial_code_source,
60
+ spatial_code_input_selection,
61
+ spatial_code_frame_count,
62
+ depth,
63
+ tracking,
64
+ results_dir,
65
+ gpu,
66
+ cpu_threads,
67
+ extended,
68
+ reasoning_budget,
69
+ force_budget,
70
+ ):
71
+ if gpu is not None:
72
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
73
+ for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
74
+ os.environ[variable] = str(cpu_threads)
75
+ import cv2
76
+
77
+ cv2.setNumThreads(cpu_threads)
78
+ run = _load_run_module()
79
+ adapter = None
80
+ load_error = None
81
+ try:
82
+ adapter = vlm_models.get_adapter(model)
83
+ adapter.load_model("cuda:0" if gpu is not None else "cpu")
84
+ except Exception:
85
+ load_error = traceback.format_exc()
86
+ while True:
87
+ scene = tasks.get()
88
+ if scene is None:
89
+ return
90
+ if load_error is not None:
91
+ results.put((scene, False, load_error))
92
+ continue
93
+ try:
94
+ answered = run.run(
95
+ model,
96
+ spatial_code_format=spatial_code_format,
97
+ input_selection=input_selection,
98
+ frame_count=frame_count,
99
+ video=video,
100
+ spatial_code_source=spatial_code_source,
101
+ spatial_code_input_selection=spatial_code_input_selection,
102
+ spatial_code_frame_count=spatial_code_frame_count,
103
+ depth=depth,
104
+ tracking=tracking,
105
+ scene=scene,
106
+ results_dir=results_dir,
107
+ adapter=adapter,
108
+ extended=extended,
109
+ reasoning_budget=reasoning_budget,
110
+ force_budget=force_budget,
111
+ )
112
+ mean_score = (
113
+ sum(r["score"] for r in answered) / len(answered) if answered else None
114
+ )
115
+ results.put(
116
+ (scene, True, f"{len(answered)} question(s), mean_score={mean_score}")
117
+ )
118
+ except Exception:
119
+ results.put((scene, False, traceback.format_exc()))
120
+
121
+
122
+ def launch(
123
+ model,
124
+ spatial_code_format,
125
+ input_selection,
126
+ frame_count,
127
+ selected,
128
+ video=False,
129
+ spatial_code_source="frames",
130
+ spatial_code_input_selection=DEFAULT_INPUT_SELECTION,
131
+ spatial_code_frame_count=FRAMES_PER_VIDEO,
132
+ depth=DEFAULT_DEPTH,
133
+ tracking=DEFAULT_TRACKING,
134
+ results_dir=None,
135
+ rebuild=False,
136
+ extended=True,
137
+ reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
138
+ force_budget=MAX_NEW_TOKENS,
139
+ ):
140
+ """Answer every question for ``selected`` scenes, sharded across every visible GPU."""
141
+ if video:
142
+ input_selection = "video"
143
+ frame_count = None
144
+ elif frame_count is None or frame_count < 1:
145
+ raise ValueError("frame_count must be positive in frames mode")
146
+ mode = "video" if video else f"{input_selection}/{frame_count}"
147
+ if spatial_code_source == "video":
148
+ code_input_selection, code_frame_count, code_mode = "video", None, "video"
149
+ elif spatial_code_source == "frames":
150
+ if spatial_code_frame_count is None or spatial_code_frame_count < 1:
151
+ raise ValueError("spatial_code_frame_count must be positive")
152
+ code_input_selection = spatial_code_input_selection
153
+ code_frame_count = spatial_code_frame_count
154
+ code_mode = f"{code_input_selection}/{code_frame_count}"
155
+ else:
156
+ raise ValueError("spatial_code_source must be frames or video")
157
+ condition = f"{model}/{spatial_code_format}/{depth}/{tracking}/code-{code_mode}/visual-{mode}"
158
+ run = _load_run_module()
159
+ root = run.results_dir_for(
160
+ model,
161
+ None,
162
+ spatial_code_format,
163
+ depth,
164
+ tracking,
165
+ input_selection,
166
+ frame_count,
167
+ spatial_code_source,
168
+ code_input_selection,
169
+ code_frame_count,
170
+ results_dir,
171
+ )
172
+ pending = []
173
+ completed = 0
174
+ for scene in selected:
175
+ rows = run.load_questions(scene=scene)
176
+ if not rows:
177
+ raise ValueError(
178
+ f"no questions found for scene {scene!r}; check the manifest/scene selection"
179
+ )
180
+ answered = all((root / scene / f"{row['id']}.json").is_file() for row in rows)
181
+ if answered and not rebuild:
182
+ completed += 1
183
+ print(
184
+ f"[{condition} {completed}/{len(selected)}] {scene}: skipped",
185
+ flush=True,
186
+ )
187
+ else:
188
+ pending.append(scene)
189
+ if not pending:
190
+ print(f"[{condition}] DONE: {len(selected)} ok, 0 failed")
191
+ return
192
+
193
+ gpus = visible_gpus()
194
+ worker_count = min(len(pending), len(gpus) if gpus else 1)
195
+ assignments = gpus[:worker_count] if gpus else [None]
196
+ cpu_count = available_cpu_count()
197
+ cpu_threads = max(1, cpu_count // worker_count)
198
+ print(
199
+ f"[{condition}] starting {worker_count} persistent worker(s); "
200
+ f"GPUs={assignments}; CPU threads/worker={cpu_threads}",
201
+ flush=True,
202
+ )
203
+
204
+ context = mp.get_context("spawn")
205
+ tasks, results = context.Queue(), context.Queue()
206
+ for scene in pending:
207
+ tasks.put(scene)
208
+ for _ in range(worker_count):
209
+ tasks.put(None)
210
+ workers = [
211
+ context.Process(
212
+ target=_worker,
213
+ args=(
214
+ tasks,
215
+ results,
216
+ model,
217
+ spatial_code_format,
218
+ input_selection,
219
+ frame_count,
220
+ video,
221
+ spatial_code_source,
222
+ code_input_selection,
223
+ code_frame_count,
224
+ depth,
225
+ tracking,
226
+ results_dir,
227
+ gpu,
228
+ cpu_threads,
229
+ extended,
230
+ reasoning_budget,
231
+ force_budget,
232
+ ),
233
+ )
234
+ for gpu in assignments
235
+ ]
236
+ for worker in workers:
237
+ worker.start()
238
+ failed = []
239
+ for finished in range(1, len(pending) + 1):
240
+ scene, ok, detail = results.get()
241
+ if not ok:
242
+ failed.append(scene)
243
+ print(
244
+ f"[{condition} {completed + finished}/{len(selected)}] {scene}: "
245
+ f"{'done' if ok else 'FAILED'}\n{detail}",
246
+ flush=True,
247
+ )
248
+ for worker in workers:
249
+ worker.join()
250
+ print(
251
+ f"[{condition}] DONE: {len(pending) - len(failed)} answered, {completed} skipped, "
252
+ f"{len(failed)} failed"
253
+ )
254
+ if failed:
255
+ raise SystemExit(1)
256
+
257
+
258
+ def main():
259
+ parser = argparse.ArgumentParser()
260
+ parser.add_argument("scene", nargs="?")
261
+ parser.add_argument(
262
+ "--scenes",
263
+ help="comma-separated scenes (cannot be combined with positional scene)",
264
+ )
265
+ parser.add_argument("--model", required=True, choices=vlm_models.available_models())
266
+ parser.add_argument(
267
+ "--input-selection",
268
+ default=None,
269
+ choices=INPUT_SELECTIONS,
270
+ dest="input_selection",
271
+ )
272
+ input_mode = parser.add_mutually_exclusive_group(required=True)
273
+ input_mode.add_argument("--frames", type=int)
274
+ input_mode.add_argument("--video", action="store_true")
275
+ parser.add_argument("--spatial-code-source", required=True, choices=("frames", "video"))
276
+ parser.add_argument("--spatial-code-input-selection", choices=INPUT_SELECTIONS)
277
+ parser.add_argument("--spatial-code-frames", type=int)
278
+ parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS)
279
+ parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES)
280
+ parser.add_argument("--results-dir", default=None)
281
+ parser.add_argument("--rebuild", action="store_true")
282
+ parser.add_argument(
283
+ "--reasoning-budget",
284
+ type=int,
285
+ default=None,
286
+ help="thinking mode only (default: 2048)",
287
+ )
288
+ parser.add_argument(
289
+ "--force-budget",
290
+ type=int,
291
+ default=None,
292
+ help="thinking mode only (default: 16)",
293
+ )
294
+ args = parser.parse_args()
295
+ if args.scene and args.scenes:
296
+ parser.error("positional scene and --scenes cannot be used together")
297
+ if args.scenes is not None:
298
+ selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
299
+ if not selected:
300
+ parser.error("--scenes must contain at least one scene")
301
+ selected = list(dict.fromkeys(selected))
302
+ else:
303
+ selected = [args.scene] if args.scene else scenes()
304
+ if args.video:
305
+ if args.input_selection is not None:
306
+ parser.error("--input-selection cannot be used with --video")
307
+ else:
308
+ if args.input_selection is None:
309
+ parser.error("--input-selection is required with --frames")
310
+ if args.frames < 1:
311
+ parser.error("--frames must be positive")
312
+ if args.spatial_code_source == "video":
313
+ if args.spatial_code_input_selection is not None or args.spatial_code_frames is not None:
314
+ parser.error("spatial-code frame flags cannot be used with --spatial-code-source video")
315
+ else:
316
+ if args.spatial_code_input_selection is None or args.spatial_code_frames is None:
317
+ parser.error("--spatial-code-input-selection and --spatial-code-frames are required with --spatial-code-source frames")
318
+ if args.spatial_code_frames < 1:
319
+ parser.error("--spatial-code-frames must be positive")
320
+ resolve_protocol_budgets(parser, args)
321
+ launch(
322
+ args.model,
323
+ DEFAULT_SPATIAL_CODE_FORMAT,
324
+ args.input_selection,
325
+ args.frames,
326
+ selected,
327
+ video=args.video,
328
+ spatial_code_source=args.spatial_code_source,
329
+ spatial_code_input_selection=args.spatial_code_input_selection,
330
+ spatial_code_frame_count=args.spatial_code_frames,
331
+ depth=args.depth,
332
+ tracking=args.tracking,
333
+ results_dir=args.results_dir,
334
+ rebuild=args.rebuild,
335
+ extended=True,
336
+ reasoning_budget=args.reasoning_budget,
337
+ force_budget=args.force_budget,
338
+ )
339
+
340
+
341
+ if __name__ == "__main__":
342
+ main()
harness/C/prompts.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Combined video-frames + v2 spatial-code prompt construction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from harness.B import prompts as code_prompts
6
+
7
+ FRAMES_NOTE = "These are frames of a video."
8
+ VIDEO_NOTE = "This is a video."
9
+
10
+
11
+ def build_prompt(spatial_code, question_type, question, options=None, video=False):
12
+ """Return the trailing text block for frames + spatial code.
13
+
14
+ The actual frame images are prepended separately by harness.A.models. The text uses
15
+ the same v2 spatial-code prompt as harness.B, plus the code+frames evidence note.
16
+ """
17
+ prompt = code_prompts.build_prompt(
18
+ spatial_code,
19
+ question_type,
20
+ question,
21
+ options,
22
+ frames_note=True,
23
+ )
24
+ return (VIDEO_NOTE if video else FRAMES_NOTE) + "\n" + prompt
harness/C/run.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run one VLM over VSI-Bench questions with BOTH video frames and the scene's on-disk
2
+ explicit spatial code, sourced from the exact same (depth, tracking,
3
+ input_selection, frame_count) config.
4
+
5
+ Writes one JSON file per question in the identical shape harness.A/B use -- carrying
6
+ BOTH frame provenance (video path, frame indices/timestamps) and spatial-code
7
+ provenance (format, path), since C uses both kinds of input. Scoring reuses the same
8
+ real, unmodified official scorer harness.A, harness.B, and symbolic/run.py all 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
+ import inference as inference_config # noqa: E402
23
+ from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402
24
+ from harness.A import frames as frame_sampling # noqa: E402
25
+ from harness.A import models as vlm_models # noqa: E402
26
+ from harness.A import (
27
+ protocol_for_question,
28
+ question_group,
29
+ resolve_protocol_budgets,
30
+ ) # noqa: E402
31
+ from harness.A.run import _scalar_score, load_questions, vsi_official_eval # noqa: E402
32
+ from harness.B import ( # noqa: E402
33
+ DEFAULT_DEPTH,
34
+ DEFAULT_INPUT_SELECTION,
35
+ DEFAULT_SPATIAL_CODE_FORMAT,
36
+ DEFAULT_TRACKING,
37
+ DEPTH_VARIANTS,
38
+ INPUT_SELECTIONS,
39
+ TRACKING_MODES,
40
+ )
41
+ from harness.B import spatial_codes # noqa: E402
42
+ from harness.C import FRAMES_PER_VIDEO, RESULTS_DIR # noqa: E402
43
+ from harness.C import prompts as combined_prompts # noqa: E402
44
+
45
+
46
+ def results_dir_for(
47
+ model,
48
+ protocol,
49
+ spatial_code_format,
50
+ depth,
51
+ tracking,
52
+ input_selection,
53
+ frame_count,
54
+ spatial_code_source="frames",
55
+ spatial_code_input_selection=DEFAULT_INPUT_SELECTION,
56
+ spatial_code_frame_count=FRAMES_PER_VIDEO,
57
+ results_dir=None,
58
+ ):
59
+ """Return the result root isolated by model + protocol + fixed explicit spatial code +
60
+ depth + tracking + input + frames. ``protocol`` is "base" (16-token) or
61
+ "<reasoning budget>" (e.g. "512") -- a real path segment, so records from
62
+ different protocols OR different reasoning budgets can never collide on disk."""
63
+ if results_dir is not None:
64
+ return Path(results_dir)
65
+ root = RESULTS_DIR / model / spatial_code_format / depth / tracking
66
+ visual = Path("visual") / ("video" if input_selection == "video" else f"frames/{input_selection}/{frame_count}")
67
+ code = Path("code") / ("video" if spatial_code_source == "video" else f"frames/{spatial_code_input_selection}/{spatial_code_frame_count}")
68
+ return root / code / visual
69
+
70
+
71
+ def _build_record(
72
+ row, prompt, answer, metric_name, score, model, model_path, source_info
73
+ ):
74
+ """Assemble one question's full, untruncated result record (nothing summarized)."""
75
+ return {
76
+ "model": model,
77
+ "model_path": str(model_path),
78
+ "device": answer["device"],
79
+ "dtype": answer["dtype"],
80
+ "library_versions": answer["library_versions"],
81
+ "condition": (
82
+ f"{source_info['protocol']}:{source_info['spatial_code_format']}:"
83
+ f"{source_info['depth']}:{source_info['tracking']}:"
84
+ f"code-{source_info['spatial_code_source']}"
85
+ + ("" if source_info["spatial_code_source"] == "video" else
86
+ f"-{source_info['spatial_code_input_selection']}"
87
+ f"-{source_info['spatial_code_frame_count']}")
88
+ + f":visual-{source_info['input_selection']}"
89
+ + ("" if source_info["input_selection"] == "video" else
90
+ f"-{source_info['frame_count']}")
91
+ ),
92
+ "protocol": source_info["protocol"],
93
+ "question_group": question_group(row["question_type"]),
94
+ "spatial_code_format": source_info["spatial_code_format"],
95
+ "input_selection": source_info["input_selection"],
96
+ "frame_count": source_info["frame_count"],
97
+ "spatial_code_source": source_info["spatial_code_source"],
98
+ "spatial_code_input_selection": source_info["spatial_code_input_selection"],
99
+ "spatial_code_frame_count": source_info["spatial_code_frame_count"],
100
+ "depth": source_info["depth"],
101
+ "tracking": source_info["tracking"],
102
+ "spatial_code_path": source_info["spatial_code_path"],
103
+ "video_path": source_info["video_path"],
104
+ "frame_indices": source_info["frame_indices"],
105
+ "frame_timestamps_seconds": source_info["frame_timestamps"],
106
+ "scene": row["scene_name"],
107
+ "dataset": row.get("dataset"),
108
+ "question_id": row["id"],
109
+ "question_type": row["question_type"],
110
+ "question": row["question"],
111
+ "options": row.get("options"),
112
+ "full_prompt": prompt,
113
+ "rendered_prompt": answer["prompt_text"],
114
+ "answer_expected": row["ground_truth"],
115
+ "answer_given": answer["answer_text"],
116
+ "answer_raw": answer["answer_raw"],
117
+ "input_token_count": answer["input_token_count"],
118
+ "vision_input_shapes": answer["vision_input_shapes"],
119
+ "output_token_ids": answer["output_token_ids"],
120
+ "output_token_count": answer["output_token_count"],
121
+ "hit_token_limit": answer["hit_token_limit"],
122
+ "eos_token_ids": answer["eos_token_ids"],
123
+ "generation_seconds": answer["generation_seconds"],
124
+ "generation_config": answer["generation_config"],
125
+ "reasoning_text": answer.get("reasoning_text"),
126
+ "reasoning_raw": answer.get("reasoning_raw"),
127
+ "reasoning_token_ids": answer.get("reasoning_token_ids"),
128
+ "reasoning_token_count": answer.get("reasoning_token_count"),
129
+ "reasoning_hit_limit": answer.get("reasoning_hit_limit"),
130
+ "forced": answer.get("forced", False),
131
+ "forced_input_token_count": answer.get("forced_input_token_count"),
132
+ "metric": metric_name,
133
+ "score": score,
134
+ }
135
+
136
+
137
+ def write_question_result(
138
+ row,
139
+ prompt,
140
+ answer,
141
+ metric_name,
142
+ score,
143
+ model,
144
+ model_path,
145
+ source_info,
146
+ results_dir=None,
147
+ ):
148
+ """Write one question's full, untruncated result record. Return (path, record)."""
149
+ record = _build_record(
150
+ row, prompt, answer, metric_name, score, model, model_path, source_info
151
+ )
152
+ root = results_dir_for(
153
+ model,
154
+ source_info["protocol"],
155
+ source_info["spatial_code_format"],
156
+ source_info["depth"],
157
+ source_info["tracking"],
158
+ source_info["input_selection"],
159
+ source_info["frame_count"],
160
+ source_info["spatial_code_source"],
161
+ source_info["spatial_code_input_selection"],
162
+ source_info["spatial_code_frame_count"],
163
+ results_dir,
164
+ )
165
+ scene_dir = root / record["scene"]
166
+ scene_dir.mkdir(parents=True, exist_ok=True)
167
+ path = scene_dir / f"{row['id']}.json"
168
+ with path.open("w", encoding="utf-8") as stream:
169
+ json.dump(record, stream, indent=1)
170
+ return path, record
171
+
172
+
173
+ def run(
174
+ model,
175
+ spatial_code_format=DEFAULT_SPATIAL_CODE_FORMAT,
176
+ input_selection=DEFAULT_INPUT_SELECTION,
177
+ frame_count=FRAMES_PER_VIDEO,
178
+ video=False,
179
+ spatial_code_source="frames",
180
+ spatial_code_input_selection=DEFAULT_INPUT_SELECTION,
181
+ spatial_code_frame_count=FRAMES_PER_VIDEO,
182
+ depth=DEFAULT_DEPTH,
183
+ tracking=DEFAULT_TRACKING,
184
+ scene=None,
185
+ scenes=None,
186
+ limit=None,
187
+ device="cuda",
188
+ jsonl_path=None,
189
+ results_dir=None,
190
+ write_results=True,
191
+ adapter=None,
192
+ extended=True,
193
+ reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
194
+ force_budget=MAX_NEW_TOKENS,
195
+ ):
196
+ """Answer every matching question with one model, given both its scene's video
197
+ frames AND its spatial code as text -- both sourced from the same (depth, tracking,
198
+ input_selection, frame_count) config, so they never mismatch.
199
+
200
+ Uses ``adapter.answer_extended`` (a large ``reasoning_budget`` first pass, with a
201
+ short forced second call only if the model doesn't conclude within it) as the
202
+ standing default protocol, same as harness.B, since C combines the same complex
203
+ spatial-code JSON with the video frames. ``extended=False`` runs harness.A's exact
204
+ fixed 16-token base protocol instead (plain ``adapter.answer``), so the protocol x
205
+ representation grid can be measured with the identical generation mechanism in
206
+ every cell.
207
+
208
+ Pass a pre-loaded ``adapter`` (as harness.C.launch's persistent per-GPU workers do)
209
+ to reuse one already-loaded model across many calls; the caller then owns unloading
210
+ it. Without one, ``run`` loads and unloads its own adapter, same as harness.A/B.
211
+ """
212
+ if video:
213
+ input_selection = "video"
214
+ frame_count = None
215
+ elif frame_count is None or frame_count < 1:
216
+ raise ValueError("frame_count must be positive in frames mode")
217
+ if spatial_code_source == "video":
218
+ code_input_selection, code_frame_count = "video", None
219
+ elif spatial_code_source == "frames":
220
+ if spatial_code_frame_count is None or spatial_code_frame_count < 1:
221
+ raise ValueError("spatial_code_frame_count must be positive")
222
+ code_input_selection = spatial_code_input_selection
223
+ code_frame_count = spatial_code_frame_count
224
+ else:
225
+ raise ValueError("spatial_code_source must be frames or video")
226
+ if spatial_code_format != "explicit":
227
+ raise ValueError("Harness C supports explicit spatial codes only")
228
+ protocol = "mixed"
229
+ results_dir = results_dir_for(
230
+ model,
231
+ protocol,
232
+ spatial_code_format,
233
+ depth,
234
+ tracking,
235
+ input_selection,
236
+ frame_count,
237
+ spatial_code_source,
238
+ code_input_selection,
239
+ code_frame_count,
240
+ results_dir,
241
+ )
242
+ rows = load_questions(jsonl_path, scene, scenes, limit)
243
+ if not rows:
244
+ return []
245
+ owns_adapter = adapter is None
246
+ if owns_adapter:
247
+ adapter = vlm_models.get_adapter(model)
248
+ adapter.load_model(device)
249
+ source_cache = {}
250
+ results = []
251
+ try:
252
+ for row in rows:
253
+ protocol = protocol_for_question(row["question_type"])
254
+ scene_id = row["scene_name"]
255
+ if scene_id not in source_cache:
256
+ video_path = inference_config.video_path(scene_id, row.get("dataset"))
257
+ if video:
258
+ frame_images = video_path
259
+ frame_timestamps = None
260
+ frame_indices = None
261
+ else:
262
+ frame_images, frame_timestamps, frame_indices = (
263
+ frame_sampling.sample_frames(
264
+ video_path, frame_count, input_selection
265
+ )
266
+ )
267
+ code, code_path = spatial_codes.load_spatial_code(
268
+ scene_id,
269
+ depth,
270
+ code_input_selection,
271
+ tracking,
272
+ code_frame_count,
273
+ spatial_code_format,
274
+ )
275
+ source_cache[scene_id] = {
276
+ "video_path": video_path,
277
+ "frame_images": frame_images,
278
+ "frame_timestamps": frame_timestamps,
279
+ "frame_indices": frame_indices,
280
+ "code": code,
281
+ "spatial_code_path": code_path,
282
+ }
283
+ cached = source_cache[scene_id]
284
+ prompt = combined_prompts.build_prompt(
285
+ cached["code"],
286
+ row["question_type"],
287
+ row["question"],
288
+ row.get("options"),
289
+ video=video,
290
+ )
291
+ answer = (
292
+ adapter.answer_extended(
293
+ cached["frame_images"],
294
+ prompt,
295
+ reasoning_budget=reasoning_budget,
296
+ force_budget=force_budget,
297
+ )
298
+ if protocol == "thinking"
299
+ else adapter.answer(
300
+ cached["frame_images"], prompt, max_new_tokens=MAX_NEW_TOKENS
301
+ )
302
+ )
303
+ doc = {
304
+ "question_type": row["question_type"],
305
+ "ground_truth": row["ground_truth"],
306
+ }
307
+ score_doc = vsi_official_eval.vsibench_process_results(
308
+ doc, [answer["answer_text"]]
309
+ )["vsibench_score"]
310
+ metric_name, score = _scalar_score(row["question_type"], score_doc)
311
+ source_info = {
312
+ "protocol": protocol,
313
+ "spatial_code_format": spatial_code_format,
314
+ "input_selection": input_selection,
315
+ "frame_count": frame_count,
316
+ "spatial_code_source": spatial_code_source,
317
+ "spatial_code_input_selection": code_input_selection,
318
+ "spatial_code_frame_count": code_frame_count,
319
+ "depth": depth,
320
+ "tracking": tracking,
321
+ "spatial_code_path": cached["spatial_code_path"],
322
+ "video_path": cached["video_path"],
323
+ "frame_indices": cached["frame_indices"],
324
+ "frame_timestamps": cached["frame_timestamps"],
325
+ }
326
+ if write_results:
327
+ path, record = write_question_result(
328
+ row,
329
+ prompt,
330
+ answer,
331
+ metric_name,
332
+ score,
333
+ model,
334
+ adapter.model_path,
335
+ source_info,
336
+ results_dir,
337
+ )
338
+ else:
339
+ path = None
340
+ record = _build_record(
341
+ row,
342
+ prompt,
343
+ answer,
344
+ metric_name,
345
+ score,
346
+ model,
347
+ adapter.model_path,
348
+ source_info,
349
+ )
350
+ record["result_path"] = str(path) if path else None
351
+ results.append(record)
352
+ finally:
353
+ if owns_adapter:
354
+ adapter.unload()
355
+ return results
356
+
357
+
358
+ def main():
359
+ parser = argparse.ArgumentParser()
360
+ parser.add_argument("--model", required=True, choices=vlm_models.available_models())
361
+ parser.add_argument("--scene", default=None, help="restrict to one VSI-Bench scene")
362
+ parser.add_argument(
363
+ "--input-selection",
364
+ default=None,
365
+ choices=INPUT_SELECTIONS,
366
+ dest="input_selection",
367
+ )
368
+ input_mode = parser.add_mutually_exclusive_group(required=True)
369
+ input_mode.add_argument("--frames", type=int)
370
+ input_mode.add_argument("--video", action="store_true")
371
+ parser.add_argument("--spatial-code-source", required=True, choices=("frames", "video"))
372
+ parser.add_argument("--spatial-code-input-selection", choices=INPUT_SELECTIONS)
373
+ parser.add_argument("--spatial-code-frames", type=int)
374
+ parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS)
375
+ parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES)
376
+ parser.add_argument(
377
+ "--limit", type=int, default=None, help="cap the number of questions"
378
+ )
379
+ parser.add_argument("--device", default="cuda")
380
+ parser.add_argument(
381
+ "--results-dir",
382
+ default=None,
383
+ help="override the default results/C/<model>/explicit/"
384
+ "<depth>/<tracking>/{<input>/<frames>|video} root",
385
+ )
386
+ parser.add_argument(
387
+ "--no-write",
388
+ action="store_true",
389
+ help="skip writing per-question JSON files; print/score only",
390
+ )
391
+ parser.add_argument(
392
+ "--reasoning-budget",
393
+ type=int,
394
+ default=None,
395
+ help="thinking questions only (default: 2048)",
396
+ )
397
+ parser.add_argument(
398
+ "--force-budget",
399
+ type=int,
400
+ default=None,
401
+ help="thinking questions only (default: 16)",
402
+ )
403
+ args = parser.parse_args()
404
+ if args.video:
405
+ if args.input_selection is not None:
406
+ parser.error("--input-selection cannot be used with --video")
407
+ else:
408
+ if args.input_selection is None:
409
+ parser.error("--input-selection is required with --frames")
410
+ if args.frames < 1:
411
+ parser.error("--frames must be positive")
412
+ if args.spatial_code_source == "video":
413
+ if args.spatial_code_input_selection is not None or args.spatial_code_frames is not None:
414
+ parser.error("spatial-code frame flags cannot be used with --spatial-code-source video")
415
+ else:
416
+ if args.spatial_code_input_selection is None or args.spatial_code_frames is None:
417
+ parser.error("--spatial-code-input-selection and --spatial-code-frames are required with --spatial-code-source frames")
418
+ if args.spatial_code_frames < 1:
419
+ parser.error("--spatial-code-frames must be positive")
420
+ resolve_protocol_budgets(parser, args)
421
+ results = run(
422
+ args.model,
423
+ spatial_code_format=DEFAULT_SPATIAL_CODE_FORMAT,
424
+ input_selection=args.input_selection,
425
+ frame_count=args.frames,
426
+ video=args.video,
427
+ spatial_code_source=args.spatial_code_source,
428
+ spatial_code_input_selection=args.spatial_code_input_selection,
429
+ spatial_code_frame_count=args.spatial_code_frames,
430
+ depth=args.depth,
431
+ tracking=args.tracking,
432
+ scene=args.scene,
433
+ limit=args.limit,
434
+ device=args.device,
435
+ results_dir=args.results_dir,
436
+ write_results=not args.no_write,
437
+ extended=True,
438
+ reasoning_budget=args.reasoning_budget,
439
+ force_budget=args.force_budget,
440
+ )
441
+
442
+ for result in results:
443
+ print(
444
+ f"[{result['scene']}#{result['question_id']}] {result['question_type']}: "
445
+ f"pred={result['answer_given']!r} gt={result['answer_expected']!r} "
446
+ f"score={result['score']} ({result['generation_seconds']:.2f}s) -> "
447
+ f"{result['result_path']}"
448
+ )
449
+ if results:
450
+ mean_score = sum(r["score"] for r in results) / len(results)
451
+ total_seconds = sum(r["generation_seconds"] for r in results)
452
+ print(
453
+ f"\n{len(results)} questions, mean vsibench_score={mean_score:.4f}, "
454
+ f"total generation time={total_seconds:.1f}s"
455
+ )
456
+
457
+
458
+ if __name__ == "__main__":
459
+ main()
harness/C/sweep.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sweep any set of models 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.C.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 import resolve_protocol_budgets # noqa: E402
26
+ from harness.A import EXTENDED_MAX_NEW_TOKENS # noqa: E402
27
+ from harness.A.sweep import _parse_csv_choice, _parse_frame_counts # noqa: E402
28
+ from harness.B import ( # noqa: E402
29
+ DEFAULT_DEPTH,
30
+ DEFAULT_INPUT_SELECTION,
31
+ DEFAULT_SPATIAL_CODE_FORMAT,
32
+ DEFAULT_TRACKING,
33
+ DEPTH_VARIANTS,
34
+ INPUT_SELECTIONS,
35
+ TRACKING_MODES,
36
+ )
37
+ from harness.C import launch as harness_launch # noqa: E402
38
+
39
+
40
+ def build_plan(
41
+ models, spatial_code_formats, input_selections, frame_counts, depths, trackings,
42
+ spatial_code_sources, spatial_code_input_selections, spatial_code_frame_counts,
43
+ ):
44
+ """Return every independent visual-input x spatial-code-input combination."""
45
+ code_configs = []
46
+ for source in spatial_code_sources:
47
+ if source == "video":
48
+ code_configs.append(("video", "video", None))
49
+ else:
50
+ code_configs.extend(
51
+ ("frames", selection, count)
52
+ for count in sorted(spatial_code_frame_counts)
53
+ for selection in spatial_code_input_selections
54
+ )
55
+ return [
56
+ (model, fmt, depth, tracking, selection, count,
57
+ code_source, code_selection, code_count)
58
+ for count in frame_counts
59
+ for model in models
60
+ for fmt in spatial_code_formats
61
+ for depth in depths
62
+ for tracking in trackings
63
+ for selection in input_selections
64
+ for code_source, code_selection, code_count in code_configs
65
+ ]
66
+
67
+
68
+ def sweep(
69
+ models, spatial_code_formats, input_selections, frame_counts, selected_scenes,
70
+ video=False, depths=(DEFAULT_DEPTH,), trackings=(DEFAULT_TRACKING,),
71
+ spatial_code_sources=("frames",),
72
+ spatial_code_input_selections=(DEFAULT_INPUT_SELECTION,),
73
+ spatial_code_frame_counts=(32,), results_dir=None, rebuild=False,
74
+ extended=True, reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
75
+ ):
76
+ """Run every independent visual-input x spatial-code-input combination."""
77
+ plan = build_plan(
78
+ models, spatial_code_formats, input_selections, frame_counts, depths, trackings,
79
+ spatial_code_sources, spatial_code_input_selections, spatial_code_frame_counts,
80
+ )
81
+ for index, config in enumerate(plan, start=1):
82
+ (model, fmt, depth, tracking, selection, count,
83
+ code_source, code_selection, code_count) = config
84
+ visual_mode = "video" if video else f"{selection}/{count}"
85
+ code_mode = "video" if code_source == "video" else f"{code_selection}/{code_count}"
86
+ print(f"=== sweep {index}/{len(plan)}: {model}/{fmt}/{depth}/{tracking}/"
87
+ f"code-{code_mode}/visual-{visual_mode} ===", flush=True)
88
+ harness_launch.launch(
89
+ model, fmt, selection, count, selected_scenes, video=video,
90
+ spatial_code_source=code_source,
91
+ spatial_code_input_selection=code_selection,
92
+ spatial_code_frame_count=code_count,
93
+ depth=depth, tracking=tracking, results_dir=results_dir,
94
+ rebuild=rebuild, extended=extended, reasoning_budget=reasoning_budget,
95
+ )
96
+
97
+ def main():
98
+ parser = argparse.ArgumentParser()
99
+ parser.add_argument("scene", nargs="?")
100
+ parser.add_argument("--scenes", help="comma-separated scenes")
101
+ parser.add_argument("--models", required=True)
102
+ parser.add_argument("--input-selections", dest="input_selections")
103
+ visual = parser.add_mutually_exclusive_group(required=True)
104
+ visual.add_argument("--frames", help="comma-separated visual frame counts")
105
+ visual.add_argument("--video", action="store_true")
106
+ parser.add_argument("--spatial-code-sources", required=True)
107
+ parser.add_argument("--spatial-code-input-selections")
108
+ parser.add_argument("--spatial-code-frames")
109
+ parser.add_argument("--depths", default=DEFAULT_DEPTH)
110
+ parser.add_argument("--trackings", default=DEFAULT_TRACKING)
111
+ parser.add_argument("--results-dir")
112
+ parser.add_argument("--rebuild", action="store_true")
113
+ parser.add_argument("--reasoning-budget", type=int, default=None,
114
+ help="thinking questions only")
115
+ args = parser.parse_args()
116
+ resolve_protocol_budgets(parser, args)
117
+ if args.scene and args.scenes:
118
+ parser.error("positional scene and --scenes cannot be used together")
119
+ try:
120
+ models = _parse_csv_choice(args.models, vlm_models.available_models(), "--models")
121
+ if args.video:
122
+ if args.input_selections is not None:
123
+ raise ValueError("--input-selections cannot be used with --video")
124
+ selections, counts = ["video"], [None]
125
+ else:
126
+ if args.input_selections is None:
127
+ raise ValueError("--input-selections is required with --frames")
128
+ selections = _parse_csv_choice(args.input_selections, INPUT_SELECTIONS,
129
+ "--input-selections")
130
+ counts = _parse_frame_counts(args.frames)
131
+ code_sources = _parse_csv_choice(args.spatial_code_sources,
132
+ ("frames", "video"),
133
+ "--spatial-code-sources")
134
+ if "frames" in code_sources:
135
+ if (args.spatial_code_input_selections is None or
136
+ args.spatial_code_frames is None):
137
+ raise ValueError("spatial-code selections and frame counts are required "
138
+ "when frame-derived codes are included")
139
+ code_selections = _parse_csv_choice(
140
+ args.spatial_code_input_selections, INPUT_SELECTIONS,
141
+ "--spatial-code-input-selections")
142
+ code_counts = _parse_frame_counts(args.spatial_code_frames)
143
+ else:
144
+ if (args.spatial_code_input_selections is not None or
145
+ args.spatial_code_frames is not None):
146
+ raise ValueError("spatial-code frame flags cannot be used with video-only codes")
147
+ code_selections, code_counts = [], []
148
+ depths = _parse_csv_choice(args.depths, DEPTH_VARIANTS, "--depths")
149
+ trackings = _parse_csv_choice(args.trackings, TRACKING_MODES, "--trackings")
150
+ except ValueError as exc:
151
+ parser.error(str(exc))
152
+ if args.scenes is not None:
153
+ selected = list(dict.fromkeys(x.strip() for x in args.scenes.split(",") if x.strip()))
154
+ if not selected:
155
+ parser.error("--scenes must contain at least one scene")
156
+ else:
157
+ from harness.A.launch import scenes
158
+ selected = [args.scene] if args.scene else scenes()
159
+ sweep(
160
+ models, (DEFAULT_SPATIAL_CODE_FORMAT,), selections, counts, selected,
161
+ video=args.video, depths=depths, trackings=trackings,
162
+ spatial_code_sources=code_sources,
163
+ spatial_code_input_selections=code_selections,
164
+ spatial_code_frame_counts=code_counts,
165
+ results_dir=args.results_dir, rebuild=args.rebuild,
166
+ reasoning_budget=args.reasoning_budget,
167
+ )
168
+
169
+
170
+ if __name__ == "__main__":
171
+ main()
harness/F/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """Harness F: deterministic symbolic reasoning over perceived spatial codes."""
2
+
3
+ from pathlib import Path
4
+ import os
5
+
6
+ RESULTS_DIR = Path(os.environ.get("VSI_HARNESS_F_RESULTS_DIR", "/root/results/F"))
7
+ SOURCES = ("perceived",)
8
+ DEFAULT_SOURCE = "perceived"
harness/F/launch.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """Launch one Harness F symbolic-solver condition over selected scenes."""
2
+
3
+ from harness.F.run import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
harness/F/run.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the existing symbolic solver as first-class Harness F."""
2
+
3
+ from __future__ import annotations
4
+ import argparse
5
+ import glob
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent
11
+ if str(WORKSPACE_ROOT) not in sys.path:
12
+ sys.path.insert(0, str(WORKSPACE_ROOT))
13
+
14
+ from harness.F import DEFAULT_SOURCE, RESULTS_DIR, SOURCES
15
+ from symbolic import run as symbolic_run
16
+
17
+
18
+ def results_dir_for(
19
+ source,
20
+ spatial_code_format,
21
+ depth="metric",
22
+ tracking="tracking",
23
+ input_selection="uniform",
24
+ frame_count=32,
25
+ results_dir=None,
26
+ ):
27
+ if results_dir is not None:
28
+ return Path(results_dir)
29
+ root = RESULTS_DIR / "perceived" / depth / tracking
30
+ if input_selection == "video":
31
+ return root / "video" / spatial_code_format
32
+ return root / input_selection / str(frame_count) / spatial_code_format
33
+
34
+
35
+ def select_source(
36
+ source=DEFAULT_SOURCE,
37
+ spatial_code_format="explicit",
38
+ depth="metric",
39
+ tracking="tracking",
40
+ input_selection="uniform",
41
+ frame_count=32,
42
+ ):
43
+ if source not in SOURCES:
44
+ raise ValueError(f"unknown source {source!r}; expected one of {SOURCES}")
45
+ if spatial_code_format != "explicit":
46
+ raise ValueError("Harness F supports explicit spatial codes only")
47
+ return symbolic_run.select_spatial_codes(
48
+ depth, input_selection, tracking, frame_count, spatial_code_format
49
+ )
50
+
51
+
52
+ def available_scenes():
53
+ return sorted(
54
+ Path(path).stem
55
+ for path in glob.glob(str(Path(symbolic_run.SPATIAL_CODES_DIR) / "*.json"))
56
+ )
57
+
58
+
59
+ def run(
60
+ source=DEFAULT_SOURCE,
61
+ spatial_code_format="explicit",
62
+ depth="metric",
63
+ tracking="tracking",
64
+ input_selection="uniform",
65
+ frame_count=32,
66
+ video=False,
67
+ scene=None,
68
+ scenes=None,
69
+ results_dir=None,
70
+ write_results=True,
71
+ quiet=True,
72
+ ):
73
+ if scene is not None and scenes is not None:
74
+ raise ValueError("scene and scenes cannot both be given")
75
+ if video:
76
+ input_selection = "video"
77
+ frame_count = None
78
+ elif frame_count is None or frame_count < 1:
79
+ raise ValueError("frame_count must be positive in frames mode")
80
+ select_source(
81
+ source, spatial_code_format, depth, tracking, input_selection, frame_count
82
+ )
83
+ selected = (
84
+ [scene] if scene else list(scenes) if scenes is not None else available_scenes()
85
+ )
86
+ root = results_dir_for(
87
+ source,
88
+ spatial_code_format,
89
+ depth,
90
+ tracking,
91
+ input_selection,
92
+ frame_count,
93
+ results_dir,
94
+ )
95
+ records = []
96
+ for scene_id in selected:
97
+ per_question, aggregate = symbolic_run.score_scene(scene_id)
98
+ code = symbolic_run.fetch_spatial_code(scene_id)
99
+ if not quiet:
100
+ symbolic_run._print_scene_report(scene_id, per_question, aggregate, code)
101
+ if write_results:
102
+ symbolic_run.write_scene_results(
103
+ scene_id, per_question, aggregate, code, root
104
+ )
105
+ for pq in per_question:
106
+ records.append(
107
+ {
108
+ "model": "symbolic",
109
+ "source": source,
110
+ "scene": scene_id,
111
+ "dataset": pq.get("dataset"),
112
+ "question_id": pq["question_id"],
113
+ "question_type": pq["question_type"],
114
+ "question": pq["question"],
115
+ "answer_expected": pq["ground_truth"],
116
+ "answer_given": (
117
+ "" if pq["engine_answer"] is None else str(pq["engine_answer"])
118
+ ),
119
+ "score": pq["score"],
120
+ "result_path": (
121
+ str(root / scene_id / f"{pq['question_id']}.json")
122
+ if write_results
123
+ else None
124
+ ),
125
+ }
126
+ )
127
+ return records
128
+
129
+
130
+ def main():
131
+ p = argparse.ArgumentParser()
132
+ p.add_argument("scene", nargs="?")
133
+ p.add_argument(
134
+ "--scenes", help="comma-separated scenes; default: every available scene"
135
+ )
136
+ p.add_argument("--source", choices=SOURCES, default=DEFAULT_SOURCE)
137
+ p.add_argument("--depth", choices=symbolic_run.DEPTH_VARIANTS, default="metric")
138
+ p.add_argument(
139
+ "--tracking", choices=symbolic_run.TRACKING_MODES, default="tracking"
140
+ )
141
+ p.add_argument(
142
+ "--input-selection",
143
+ choices=symbolic_run.INPUT_SELECTIONS,
144
+ default=None,
145
+ dest="input_selection",
146
+ )
147
+ input_mode = p.add_mutually_exclusive_group(required=True)
148
+ input_mode.add_argument("--frames", type=int)
149
+ input_mode.add_argument("--video", action="store_true")
150
+ p.add_argument("--results-dir", default=None)
151
+ p.add_argument("--no-write", action="store_true")
152
+ p.add_argument("--verbose", action="store_true")
153
+ a = p.parse_args()
154
+ if a.scene and a.scenes:
155
+ p.error("scene and --scenes cannot be combined")
156
+ if a.video:
157
+ if a.input_selection is not None:
158
+ p.error("--input-selection cannot be used with --video")
159
+ else:
160
+ if a.input_selection is None:
161
+ p.error("--input-selection is required with --frames")
162
+ if a.frames < 1:
163
+ p.error("--frames must be positive")
164
+ selected = (
165
+ None
166
+ if not a.scenes
167
+ else list(dict.fromkeys(x.strip() for x in a.scenes.split(",") if x.strip()))
168
+ )
169
+ records = run(
170
+ a.source,
171
+ "explicit",
172
+ a.depth,
173
+ a.tracking,
174
+ a.input_selection,
175
+ a.frames,
176
+ a.video,
177
+ a.scene,
178
+ selected,
179
+ a.results_dir,
180
+ not a.no_write,
181
+ not a.verbose,
182
+ )
183
+ mean = sum(r["score"] for r in records) / len(records) if records else None
184
+ print(f"{len(records)} questions, mean_score={mean}")
185
+
186
+
187
+ if __name__ == "__main__":
188
+ main()
harness/F/sweep.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sweep Harness F spatial-code configurations."""
2
+
3
+ from __future__ import annotations
4
+ import argparse
5
+ from itertools import product
6
+ from harness.F import run as harness_run
7
+ from symbolic import run as symbolic_run
8
+
9
+
10
+ def _csv(value, valid):
11
+ values = (
12
+ list(valid)
13
+ if value.lower() == "all"
14
+ else [x.strip() for x in value.split(",") if x.strip()]
15
+ )
16
+ unknown = [x for x in values if x not in valid]
17
+ if unknown:
18
+ raise ValueError(f"unknown values {unknown}; expected {valid} or all")
19
+ return list(dict.fromkeys(values))
20
+
21
+
22
+ def main():
23
+ p = argparse.ArgumentParser()
24
+ p.add_argument("--sources", default="all")
25
+ p.add_argument("--depths", default="metric")
26
+ p.add_argument("--trackings", default="tracking")
27
+ p.add_argument("--input-selections", default=None)
28
+ input_mode = p.add_mutually_exclusive_group(required=True)
29
+ input_mode.add_argument("--frames")
30
+ input_mode.add_argument("--video", action="store_true")
31
+ p.add_argument("--scenes", default=None)
32
+ p.add_argument("--results-dir", default=None)
33
+ a = p.parse_args()
34
+ try:
35
+ sources = _csv(a.sources, harness_run.SOURCES)
36
+ formats = ("explicit",)
37
+ depths = _csv(a.depths, symbolic_run.DEPTH_VARIANTS)
38
+ trackings = _csv(a.trackings, symbolic_run.TRACKING_MODES)
39
+ if a.video:
40
+ if a.input_selections is not None:
41
+ raise ValueError("--input-selections cannot be used with --video")
42
+ selections = ["video"]
43
+ frames = [None]
44
+ else:
45
+ if a.input_selections is None:
46
+ raise ValueError("--input-selections is required with --frames")
47
+ selections = _csv(a.input_selections, symbolic_run.INPUT_SELECTIONS)
48
+ frames = list(
49
+ dict.fromkeys(int(x.strip()) for x in a.frames.split(",") if x.strip())
50
+ )
51
+ if not frames or any(x < 1 for x in frames):
52
+ raise ValueError("frames must be positive")
53
+ except ValueError as exc:
54
+ p.error(str(exc))
55
+ scenes = (
56
+ None
57
+ if not a.scenes
58
+ else list(dict.fromkeys(x.strip() for x in a.scenes.split(",") if x.strip()))
59
+ )
60
+ for source, fmt in product(sources, formats):
61
+ configs = product(depths, trackings, selections, frames)
62
+ for config in configs:
63
+ depth, tracking, selection, count = config
64
+ records = harness_run.run(
65
+ source,
66
+ fmt,
67
+ depth,
68
+ tracking,
69
+ selection,
70
+ count,
71
+ video=a.video,
72
+ scenes=scenes,
73
+ results_dir=a.results_dir,
74
+ )
75
+ print(source, fmt, depth, tracking, selection, count, len(records))
76
+
77
+
78
+ if __name__ == "__main__":
79
+ main()
harness/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ """Top-level namespace for direct VLM-inference harnesses (as opposed to the
2
+ encoder/symbolic spatial-code pipeline)."""