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

Remove old harness before replacement

Browse files
harness/A/__init__.py DELETED
@@ -1,111 +0,0 @@
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 DELETED
@@ -1,54 +0,0 @@
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 DELETED
@@ -1,282 +0,0 @@
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 DELETED
@@ -1,416 +0,0 @@
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 DELETED
@@ -1,58 +0,0 @@
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 DELETED
@@ -1,419 +0,0 @@
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 DELETED
@@ -1,187 +0,0 @@
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 DELETED
@@ -1,47 +0,0 @@
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 DELETED
@@ -1,309 +0,0 @@
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 DELETED
@@ -1,523 +0,0 @@
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 DELETED
@@ -1,379 +0,0 @@
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 DELETED
@@ -1,33 +0,0 @@
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 DELETED
@@ -1,202 +0,0 @@
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 DELETED
@@ -1,47 +0,0 @@
1
- """Harness C: route BOTH a scene's video frames AND its on-disk spatial code (explicit
2
- explicit) to all three models, for every VSI-Bench question.
3
-
4
- Frames and spatial code are sourced from the exact same (depth, tracking,
5
- input_selection, frame_count) config -- the same parameters drive both
6
- harness.A.frames.sample_frames() and harness.B.spatial_codes.load_spatial_code(), so the
7
- spatial code shown to the model is guaranteed to have been built from sampling the same
8
- video the same way the frames themselves are sampled here; they can never mismatch.
9
-
10
- Reuses harness.A's model registry/adapters and fixed generation protocol exactly, and
11
- harness.B's spatial-code loading and format/input-selection vocabulary. Results are
12
- written in the identical per-question JSON shape harness.A and harness.B use, with both
13
- harnesses' provenance fields present (frame provenance from A, spatial-code provenance
14
- from B) since C uses both kinds of input.
15
- """
16
-
17
- from __future__ import annotations
18
-
19
- import os
20
- from pathlib import Path
21
-
22
- from harness.A import (
23
- DO_SAMPLE,
24
- FRAME_SELECTIONS,
25
- JSONL,
26
- MAX_NEW_TOKENS,
27
- MODEL_PATHS,
28
- TEMPERATURE,
29
- WORKSPACE_ROOT,
30
- )
31
- from harness.B import (
32
- DEFAULT_DEPTH,
33
- DEFAULT_INPUT_SELECTION,
34
- DEFAULT_SPATIAL_CODE_FORMAT,
35
- DEFAULT_TRACKING,
36
- DEPTH_VARIANTS,
37
- INPUT_SELECTIONS,
38
- TRACKING_MODES,
39
- )
40
-
41
- assert INPUT_SELECTIONS == FRAME_SELECTIONS # one shared vocabulary drives both sources
42
-
43
- FRAMES_PER_VIDEO = int(os.environ.get("VSI_HARNESS_C_FRAMES_PER_VIDEO", "32"))
44
-
45
- # One JSON per question, matching harness.A/B's layout:
46
- # results/C/<model>/<spatial_code_format>/<depth>/<tracking>/<input_selection>/<frame_count>/<scene>/<question_id>.json
47
- RESULTS_DIR = Path(os.environ.get("VSI_HARNESS_C_RESULTS_DIR", "/root/results/C"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
harness/C/launch.py DELETED
@@ -1,303 +0,0 @@
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
- depth,
60
- tracking,
61
- results_dir,
62
- gpu,
63
- cpu_threads,
64
- extended,
65
- reasoning_budget,
66
- force_budget,
67
- ):
68
- if gpu is not None:
69
- os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
70
- for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
71
- os.environ[variable] = str(cpu_threads)
72
- import cv2
73
-
74
- cv2.setNumThreads(cpu_threads)
75
- run = _load_run_module()
76
- adapter = None
77
- load_error = None
78
- try:
79
- adapter = vlm_models.get_adapter(model)
80
- adapter.load_model("cuda:0" if gpu is not None else "cpu")
81
- except Exception:
82
- load_error = traceback.format_exc()
83
- while True:
84
- scene = tasks.get()
85
- if scene is None:
86
- return
87
- if load_error is not None:
88
- results.put((scene, False, load_error))
89
- continue
90
- try:
91
- answered = run.run(
92
- model,
93
- spatial_code_format=spatial_code_format,
94
- input_selection=input_selection,
95
- frame_count=frame_count,
96
- video=video,
97
- depth=depth,
98
- tracking=tracking,
99
- scene=scene,
100
- results_dir=results_dir,
101
- adapter=adapter,
102
- extended=extended,
103
- reasoning_budget=reasoning_budget,
104
- force_budget=force_budget,
105
- )
106
- mean_score = (
107
- sum(r["score"] for r in answered) / len(answered) if answered else None
108
- )
109
- results.put(
110
- (scene, True, f"{len(answered)} question(s), mean_score={mean_score}")
111
- )
112
- except Exception:
113
- results.put((scene, False, traceback.format_exc()))
114
-
115
-
116
- def launch(
117
- model,
118
- spatial_code_format,
119
- input_selection,
120
- frame_count,
121
- selected,
122
- video=False,
123
- depth=DEFAULT_DEPTH,
124
- tracking=DEFAULT_TRACKING,
125
- results_dir=None,
126
- rebuild=False,
127
- extended=True,
128
- reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
129
- force_budget=MAX_NEW_TOKENS,
130
- ):
131
- """Answer every question for ``selected`` scenes, sharded across every visible GPU."""
132
- if video:
133
- input_selection = "video"
134
- frame_count = None
135
- elif frame_count is None or frame_count < 1:
136
- raise ValueError("frame_count must be positive in frames mode")
137
- mode = "video" if video else f"{input_selection}/{frame_count}"
138
- condition = f"{model}/{spatial_code_format}/{depth}/{tracking}/{mode}"
139
- run = _load_run_module()
140
- root = run.results_dir_for(
141
- model,
142
- None,
143
- spatial_code_format,
144
- depth,
145
- tracking,
146
- input_selection,
147
- frame_count,
148
- results_dir,
149
- )
150
- pending = []
151
- completed = 0
152
- for scene in selected:
153
- rows = run.load_questions(scene=scene)
154
- if not rows:
155
- raise ValueError(
156
- f"no questions found for scene {scene!r}; check the manifest/scene selection"
157
- )
158
- answered = all((root / scene / f"{row['id']}.json").is_file() for row in rows)
159
- if answered and not rebuild:
160
- completed += 1
161
- print(
162
- f"[{condition} {completed}/{len(selected)}] {scene}: skipped",
163
- flush=True,
164
- )
165
- else:
166
- pending.append(scene)
167
- if not pending:
168
- print(f"[{condition}] DONE: {len(selected)} ok, 0 failed")
169
- return
170
-
171
- gpus = visible_gpus()
172
- worker_count = min(len(pending), len(gpus) if gpus else 1)
173
- assignments = gpus[:worker_count] if gpus else [None]
174
- cpu_count = available_cpu_count()
175
- cpu_threads = max(1, cpu_count // worker_count)
176
- print(
177
- f"[{condition}] starting {worker_count} persistent worker(s); "
178
- f"GPUs={assignments}; CPU threads/worker={cpu_threads}",
179
- flush=True,
180
- )
181
-
182
- context = mp.get_context("spawn")
183
- tasks, results = context.Queue(), context.Queue()
184
- for scene in pending:
185
- tasks.put(scene)
186
- for _ in range(worker_count):
187
- tasks.put(None)
188
- workers = [
189
- context.Process(
190
- target=_worker,
191
- args=(
192
- tasks,
193
- results,
194
- model,
195
- spatial_code_format,
196
- input_selection,
197
- frame_count,
198
- video,
199
- depth,
200
- tracking,
201
- results_dir,
202
- gpu,
203
- cpu_threads,
204
- extended,
205
- reasoning_budget,
206
- force_budget,
207
- ),
208
- )
209
- for gpu in assignments
210
- ]
211
- for worker in workers:
212
- worker.start()
213
- failed = []
214
- for finished in range(1, len(pending) + 1):
215
- scene, ok, detail = results.get()
216
- if not ok:
217
- failed.append(scene)
218
- print(
219
- f"[{condition} {completed + finished}/{len(selected)}] {scene}: "
220
- f"{'done' if ok else 'FAILED'}\n{detail}",
221
- flush=True,
222
- )
223
- for worker in workers:
224
- worker.join()
225
- print(
226
- f"[{condition}] DONE: {len(pending) - len(failed)} answered, {completed} skipped, "
227
- f"{len(failed)} failed"
228
- )
229
- if failed:
230
- raise SystemExit(1)
231
-
232
-
233
- def main():
234
- parser = argparse.ArgumentParser()
235
- parser.add_argument("scene", nargs="?")
236
- parser.add_argument(
237
- "--scenes",
238
- help="comma-separated scenes (cannot be combined with positional scene)",
239
- )
240
- parser.add_argument("--model", required=True, choices=vlm_models.available_models())
241
- parser.add_argument(
242
- "--input-selection",
243
- default=None,
244
- choices=INPUT_SELECTIONS,
245
- dest="input_selection",
246
- )
247
- input_mode = parser.add_mutually_exclusive_group(required=True)
248
- input_mode.add_argument("--frames", type=int)
249
- input_mode.add_argument("--video", action="store_true")
250
- parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS)
251
- parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES)
252
- parser.add_argument("--results-dir", default=None)
253
- parser.add_argument("--rebuild", action="store_true")
254
- parser.add_argument(
255
- "--reasoning-budget",
256
- type=int,
257
- default=None,
258
- help="thinking mode only (default: 2048)",
259
- )
260
- parser.add_argument(
261
- "--force-budget",
262
- type=int,
263
- default=None,
264
- help="thinking mode only (default: 16)",
265
- )
266
- args = parser.parse_args()
267
- if args.scene and args.scenes:
268
- parser.error("positional scene and --scenes cannot be used together")
269
- if args.scenes is not None:
270
- selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
271
- if not selected:
272
- parser.error("--scenes must contain at least one scene")
273
- selected = list(dict.fromkeys(selected))
274
- else:
275
- selected = [args.scene] if args.scene else scenes()
276
- if args.video:
277
- if args.input_selection is not None:
278
- parser.error("--input-selection cannot be used with --video")
279
- else:
280
- if args.input_selection is None:
281
- parser.error("--input-selection is required with --frames")
282
- if args.frames < 1:
283
- parser.error("--frames must be positive")
284
- resolve_protocol_budgets(parser, args)
285
- launch(
286
- args.model,
287
- DEFAULT_SPATIAL_CODE_FORMAT,
288
- args.input_selection,
289
- args.frames,
290
- selected,
291
- video=args.video,
292
- depth=args.depth,
293
- tracking=args.tracking,
294
- results_dir=args.results_dir,
295
- rebuild=args.rebuild,
296
- extended=True,
297
- reasoning_budget=args.reasoning_budget,
298
- force_budget=args.force_budget,
299
- )
300
-
301
-
302
- if __name__ == "__main__":
303
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
harness/C/overlay.py DELETED
@@ -1,391 +0,0 @@
1
- """Set-of-Marks overlay for the strong correspondence arm (harness C) -- sourced
2
- PURELY from SAM3's own raw per-frame output. No 3D math anywhere in this module.
3
-
4
- Gives frames and spatial code a SHARED instance namespace with 1:1 correspondence
5
- guaranteed BY CONSTRUCTION: every explicit-code instance gets an id ("bed 1",
6
- "chair 2", ...), and that id is stamped in EXACTLY the frames SAM3's own tracker
7
- reported that instance's masklet(s) present in, at EXACTLY the bounding box SAM3's
8
- own tracker reported for it there. There is no camera projection, no floor-basis
9
- inversion, no depth buffer, no occlusion heuristic anywhere in this pipeline -- an
10
- instance is drawn iff SAM3's raw cache says it's in this frame, at the box SAM3's
11
- raw cache says it's at. Any placement error, missing detection, or wrong-frame
12
- presence is therefore attributable to SAM3 (or the SAM3->code consolidation
13
- encoder.geometric already performs, verified separately), never to this module's
14
- own math, since this module doesn't do any.
15
-
16
- Provenance (which raw SAM3 masklet id(s) a final code instance came from) is
17
- recovered via encoder.geometric.instance_source_track_ids(), which exposes the
18
- "oids" field build_compact_spatial_code()'s own consolidation pipeline threads
19
- through internally but never emits in the on-disk schema (adding it there would
20
- change every harness's prompt -- this module is the only consumer).
21
- """
22
-
23
- from __future__ import annotations
24
-
25
- import json
26
- import sys
27
- from pathlib import Path
28
-
29
- from PIL import Image, ImageDraw, ImageFont
30
-
31
- # Markers are drawn on a layer rendered at _SUPERSAMPLE x the frame's own resolution,
32
- # then downsampled with LANCZOS before compositing -- this is what makes the box
33
- # edges and glyph strokes look crisp/anti-aliased rather than jagged, WITHOUT the
34
- # marker's rendered footprint on the final frame growing (that footprint is set by
35
- # _FONT_SIZE below, sized for the frame's OWN resolution).
36
- _SUPERSAMPLE = 3
37
- _FONT_SIZE = 15
38
- _MARKER_RADIUS = 5
39
- _MAX_NUDGES = 12
40
-
41
- # A scalable font, not PIL's tiny fixed-size default bitmap font -- labels need to be
42
- # legible to a human reviewer (and to the model) at typical VSI-Bench frame resolution.
43
- # DejaVuSans-Bold ships inside every Pillow install (PIL/fonts/), so this never depends
44
- # on the host having a system font installed.
45
- try:
46
- _LABEL_FONT = ImageFont.truetype(
47
- str(Path(ImageFont.__file__).parent / "fonts" / "DejaVuSans-Bold.ttf"),
48
- _FONT_SIZE * _SUPERSAMPLE,
49
- )
50
- except OSError:
51
- _LABEL_FONT = ImageFont.load_default(size=_FONT_SIZE * _SUPERSAMPLE)
52
-
53
- WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent
54
- if str(WORKSPACE_ROOT) not in sys.path:
55
- sys.path.insert(0, str(WORKSPACE_ROOT))
56
-
57
- from encoder import config as encoder_config # noqa: E402
58
- from encoder import geometric as gm # noqa: E402
59
- from encoder import run as perceive # noqa: E402
60
-
61
-
62
- def _parse_meters(value):
63
- return float(str(value).split()[0])
64
-
65
-
66
- def _boxes_overlap(a, b):
67
- return a[0] < b[2] and a[2] > b[0] and a[1] < b[3] and a[3] > b[1]
68
-
69
-
70
- def _place_label_box(anchor_x, anchor_y, width, height, placed, frame_h, step):
71
- """Return ((left, top, right, bottom), was_nudged) for one label, greedily moved
72
- vertically away from every box already in ``placed`` (deterministic: labels are
73
- tried in the caller's fixed order, so a given code always nudges the same way).
74
- ``was_nudged`` is False only for attempt 0 (the label's natural, un-collided
75
- position) -- the caller uses it to draw a leader line ONLY when the label actually
76
- moved away from its marker, instead of drawing one, unconditionally, that's too
77
- short to see for every other label. Alternates below/above the anchor in
78
- increasing steps so a crowded cluster fans out symmetrically instead of drifting
79
- off in one direction; stops at ``_MAX_NUDGES`` attempts and returns the last-tried
80
- box rather than looping forever -- a residual overlap in a dense cluster is a
81
- real, visible property of that cluster, not something to hide by trying
82
- indefinitely."""
83
- for attempt in range(_MAX_NUDGES):
84
- direction = 1 if attempt % 2 == 0 else -1
85
- offset = direction * step * ((attempt + 1) // 2)
86
- top = anchor_y + offset
87
- box = (anchor_x, top, anchor_x + width, top + height)
88
- if (
89
- 0 <= box[1]
90
- and box[3] <= frame_h
91
- and not any(_boxes_overlap(box, p) for p in placed)
92
- ):
93
- return box, attempt > 0
94
- return box, True
95
-
96
-
97
- def instance_ids(explicit_code):
98
- """Return a copy of an explicit code whose instances each carry an
99
- '"instance id": "<class> <n>"' field (1-based, in the code's own list order --
100
- the same numbering label_positions() and stamp_frames() use). Input not mutated."""
101
- code = dict(explicit_code)
102
- objects = {}
103
- for class_name, rendered in code.get("objects", {}).items():
104
- instances = [
105
- {**instance, "instance id": f"{class_name} {index}"}
106
- for index, instance in enumerate(rendered.get("instances", []), 1)
107
- ]
108
- objects[class_name] = {**rendered, "instances": instances}
109
- code["objects"] = objects
110
- return code
111
-
112
-
113
- def label_positions(explicit_code):
114
- """Return [(label, floor_x, floor_y, height_above_floor, longest_dimension)] for
115
- every instance, labeled identically to instance_ids(). NOT used by stamp_frames
116
- (which sources positions from SAM3's own raw boxes, not the code's stored 3D
117
- position) -- kept as a standalone utility for auditing the code's own claimed
118
- geometry against a scene (e.g. checking a suspect instance's stored height)."""
119
- out = []
120
- for class_name, rendered in explicit_code.get("objects", {}).items():
121
- for index, instance in enumerate(rendered.get("instances", []), 1):
122
- position = instance["position"]
123
- out.append(
124
- (
125
- f"{class_name} {index}",
126
- _parse_meters(position["x coordinate"]),
127
- _parse_meters(position["y coordinate"]),
128
- _parse_meters(position["height above floor"]),
129
- _parse_meters(instance["longest dimension"]),
130
- )
131
- )
132
- return out
133
-
134
-
135
- def _load_raw_sam3_boxes(scene_id, input_selection, tracking, frame_count):
136
- """Return {class_name: {frame_index: {masklet_id: (x, y, w, h) normalized [0,1]}}}
137
- read directly from the native SAM3 tracking cache -- the same file
138
- encoder.run.cache_or_load() itself reads, parsed here with NO further processing
139
- (no masking, no merging, no geometry): exactly what SAM3's own tracker reported,
140
- per frame, per masklet."""
141
- import torch
142
-
143
- path = encoder_config.sam3_cache_file(
144
- scene_id, input_selection, tracking, frame_count
145
- )
146
- if not Path(path).is_file():
147
- raise FileNotFoundError(
148
- f"no raw SAM3 cache found for scene {scene_id!r} at {path} -- the strong "
149
- "correspondence arm needs the scene's SAM3 perception cache on disk"
150
- )
151
- raw = torch.load(path, map_location="cpu", weights_only=False)
152
- out = {}
153
- for class_name, class_data in raw.items():
154
- stream = class_data.get("stream", []) if isinstance(class_data, dict) else []
155
- frames = {}
156
- for entry in stream:
157
- outputs = entry.get("outputs", {})
158
- obj_ids = outputs.get("out_obj_ids", [])
159
- boxes = outputs.get("out_boxes_xywh", [])
160
- frames[int(entry["frame_index"])] = {
161
- int(oid): tuple(float(v) for v in box)
162
- for oid, box in zip(obj_ids, boxes)
163
- }
164
- out[str(class_name)] = frames
165
- return out
166
-
167
-
168
- def overlay_frame_cache_dir(scene_id, depth, input_selection, tracking, frame_count):
169
- """Return the on-disk cache directory for one scene's stamped overlay frames --
170
- same axes as the spatial code path (depth still matters here even though box
171
- POSITIONS never touch it: instance_source_track_ids's provenance mapping, which
172
- decides which raw SAM3 id becomes "chair 1" vs "chair 3", is computed via
173
- room_gravity on the depth-specific geometry cache). Format is always explicit
174
- (the only format the correspondence arms support), so it isn't part of the path."""
175
- return (
176
- encoder_config.CACHE_ROOT
177
- / "overlay-frames"
178
- / depth
179
- / tracking
180
- / input_selection
181
- / str(frame_count)
182
- / scene_id
183
- )
184
-
185
-
186
- def overlay_spatial_code_path(scene_id, depth, input_selection, tracking, frame_count):
187
- """Return the durable overlay-code JSON path for one scene/config.
188
-
189
- Overlay codes are stored under the configured spatial-code root's top-level
190
- ``overlay`` directory so an overlay run has a browsable code artifact matching
191
- the stamped frames, instead of only an in-memory prompt transform.
192
- """
193
- encoder_config._validate_dimensions(depth, input_selection, tracking, frame_count)
194
- return (
195
- encoder_config.CODES_ROOT
196
- / "overlay"
197
- / encoder_config.MODEL
198
- / depth
199
- / tracking
200
- / input_selection
201
- / str(frame_count)
202
- / "explicit"
203
- / f"{scene_id}.json"
204
- )
205
-
206
-
207
- def load_or_create_overlay_code(
208
- explicit_code, scene_id, depth, input_selection, tracking, frame_count
209
- ):
210
- """Load an existing overlay code, or create and save it from ``explicit_code``.
211
-
212
- The saved code is exactly ``instance_ids(explicit_code)``. Existing files are
213
- trusted as the durable artifact for that scene/config and are not rewritten.
214
- Returns ``(code, path)``.
215
- """
216
- path = overlay_spatial_code_path(
217
- scene_id, depth, input_selection, tracking, frame_count
218
- )
219
- if path.is_file():
220
- return json.loads(path.read_text(encoding="utf-8")), str(path)
221
- code = instance_ids(explicit_code)
222
- path.parent.mkdir(parents=True, exist_ok=True)
223
- path.write_text(json.dumps(code, indent=1) + "\n", encoding="utf-8")
224
- return code, str(path)
225
-
226
-
227
- def _load_cached_frames(cache_dir, frame_count):
228
- """Return (stamped_frame_copies, per_frame_visible_labels) if a complete cache
229
- exists at ``cache_dir`` (every frame PNG plus the labels sidecar present), else
230
- None. A partial cache (e.g. an interrupted pre-generation run) is treated as
231
- absent -- regenerated in full, never silently served incomplete."""
232
- labels_path = cache_dir / "labels.json"
233
- if not labels_path.is_file():
234
- return None
235
- frame_paths = [cache_dir / f"{i}.png" for i in range(frame_count)]
236
- if not all(path.is_file() for path in frame_paths):
237
- return None
238
- images = [Image.open(path).convert("RGB") for path in frame_paths]
239
- visible = json.loads(labels_path.read_text())
240
- return images, visible
241
-
242
-
243
- def _save_cached_frames(cache_dir, stamped, visible):
244
- cache_dir.mkdir(parents=True, exist_ok=True)
245
- for i, image in enumerate(stamped):
246
- image.save(cache_dir / f"{i}.png")
247
- (cache_dir / "labels.json").write_text(json.dumps(visible))
248
-
249
-
250
- def stamp_frames(
251
- frame_images,
252
- explicit_code,
253
- scene_id,
254
- depth,
255
- input_selection,
256
- tracking,
257
- frame_count,
258
- use_cache=True,
259
- ):
260
- """Return (stamped_frame_copies, per_frame_visible_labels). For every code
261
- instance, looks up which raw SAM3 masklet id(s) it consolidated from
262
- (encoder.geometric.instance_source_track_ids) and, per frame, whether SAM3's own
263
- tracker reported any of those ids present -- if so, stamps SAM3's own reported box
264
- for it, verbatim. An instance is absent from a frame's output iff SAM3's raw
265
- tracker never reported it there; there is no other reason. Input images are
266
- never mutated.
267
-
268
- ``use_cache=True`` (default) reads/writes a persistent on-disk cache under
269
- overlay_frame_cache_dir() -- the same stamping is otherwise recomputed from
270
- scratch on every call (once per scene per model per run), and the result is
271
- scene-only (never model- or question-dependent), so caching it once and reusing
272
- it across every model/run that touches this scene/config is a pure speed win.
273
- Pass False to force a fresh computation (e.g. after a code or overlay-logic
274
- change, before the cache is known to be stale and worth clearing)."""
275
- cache_dir = overlay_frame_cache_dir(
276
- scene_id, depth, input_selection, tracking, frame_count
277
- )
278
- if use_cache:
279
- cached = _load_cached_frames(cache_dir, frame_count)
280
- if cached is not None:
281
- return cached
282
- geometry, _how = perceive.cache_or_load(
283
- scene_id, depth, input_selection, tracking, frame_count, False
284
- )
285
- provenance = gm.instance_source_track_ids(geometry)
286
- raw_boxes = _load_raw_sam3_boxes(scene_id, input_selection, tracking, frame_count)
287
-
288
- labels = []
289
- for class_name, rendered in explicit_code.get("objects", {}).items():
290
- oid_lists = provenance.get(class_name, [])
291
- for index, _instance in enumerate(rendered.get("instances", []), 1):
292
- oids = oid_lists[index - 1] if index - 1 < len(oid_lists) else []
293
- labels.append((f"{class_name} {index}", class_name, oids))
294
-
295
- stamped, visible = [], []
296
- for frame_index, image in enumerate(frame_images):
297
- image = image.convert("RGB")
298
- # Markers are drawn on a transparent layer at _SUPERSAMPLE x resolution, THEN
299
- # downsampled with LANCZOS and alpha-composited onto the (unscaled, un-blurred)
300
- # frame -- crisp anti-aliased edges on the marker itself, no change to the
301
- # underlying photo's own resolution or the marker's on-frame footprint.
302
- hi_res_size = (image.size[0] * _SUPERSAMPLE, image.size[1] * _SUPERSAMPLE)
303
- overlay_layer = Image.new("RGBA", hi_res_size, (0, 0, 0, 0))
304
- draw = ImageDraw.Draw(overlay_layer)
305
- marker_r = _MARKER_RADIUS * _SUPERSAMPLE
306
- placed_boxes = []
307
- frame_labels = []
308
- for label, class_name, oids in labels:
309
- frame_detections = raw_boxes.get(class_name, {}).get(frame_index, {})
310
- box = next(
311
- (frame_detections[oid] for oid in oids if oid in frame_detections), None
312
- )
313
- if box is None:
314
- continue # SAM3's own tracker did not report this instance in this frame
315
- nx, ny, nw, nh = box # normalized [0,1] -- SAM3's own box, verbatim
316
- bx0, by0 = nx * hi_res_size[0], ny * hi_res_size[1]
317
- bw, bh = nw * hi_res_size[0], nh * hi_res_size[1]
318
- draw.rectangle(
319
- [bx0, by0, bx0 + bw, by0 + bh],
320
- outline="red",
321
- width=max(2, _SUPERSAMPLE),
322
- )
323
- px, py = bx0 + bw / 2, by0 + bh / 2
324
- draw.ellipse(
325
- [px - marker_r, py - marker_r, px + marker_r, py + marker_r],
326
- outline="red",
327
- width=max(2, _SUPERSAMPLE),
328
- )
329
- # Flip the label to the opposite side of the marker whenever its default
330
- # placement would run off the frame -- a label clipped at the image edge is
331
- # unreadable to both a human reviewer and the model.
332
- text_width = draw.textlength(label, font=_LABEL_FONT)
333
- text_height = _FONT_SIZE * _SUPERSAMPLE * 1.3
334
- gap = 8 * _SUPERSAMPLE
335
- text_x = (
336
- px - gap - text_width
337
- if px + gap + text_width > hi_res_size[0]
338
- else px + gap
339
- )
340
- anchor_y = (
341
- py + 4 * _SUPERSAMPLE
342
- if py - 10 * _SUPERSAMPLE < 0
343
- else py - 10 * _SUPERSAMPLE
344
- )
345
- # Nudge this label's box away from every label already placed in this
346
- # frame -- a crowded cluster fans its labels out instead of stacking them
347
- # into an unreadable smear (see _place_label_box's docstring).
348
- label_box, was_nudged = _place_label_box(
349
- text_x,
350
- anchor_y,
351
- text_width,
352
- text_height,
353
- placed_boxes,
354
- hi_res_size[1],
355
- step=text_height + 2 * _SUPERSAMPLE,
356
- )
357
- placed_boxes.append(label_box)
358
- if was_nudged:
359
- # A leader line from the marker to its (moved) label -- needed because
360
- # dense clusters (several instances detected close together) can leave
361
- # an unconnected dot cluster reading as unowned "random circles" once
362
- # collision avoidance fans their labels apart. Only drawn when nudging
363
- # actually happened -- a label already next to its own dot doesn't
364
- # need one, and it would be invisible under the marker anyway.
365
- anchor_x = label_box[2] if text_x < px else label_box[0]
366
- anchor_y_mid = (label_box[1] + label_box[3]) / 2
367
- draw.line(
368
- [(px, py), (anchor_x, anchor_y_mid)],
369
- fill=(255, 70, 55, 210),
370
- width=max(2, _SUPERSAMPLE),
371
- )
372
- # A thin dark stroke (not a solid fill box) keeps the label legible
373
- # against any background without blotting out the photo underneath it.
374
- draw.text(
375
- (label_box[0], label_box[1]),
376
- label,
377
- font=_LABEL_FONT,
378
- fill="#ff4030",
379
- stroke_width=max(2, _SUPERSAMPLE),
380
- stroke_fill=(0, 0, 0, 235),
381
- )
382
- frame_labels.append(label)
383
- overlay_layer = overlay_layer.resize(image.size, Image.LANCZOS)
384
- composited = Image.alpha_composite(
385
- image.convert("RGBA"), overlay_layer
386
- ).convert("RGB")
387
- stamped.append(composited)
388
- visible.append(frame_labels)
389
- if use_cache:
390
- _save_cached_frames(cache_dir, stamped, visible)
391
- return stamped, visible
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
harness/C/overlay_launch.py DELETED
@@ -1,202 +0,0 @@
1
- """Pre-generate the strong correspondence arm's stamped-frame cache for many scenes
2
- at once (harness.C.overlay.overlay_frame_cache_dir/stamp_frames).
3
-
4
- Stamping is scene-only (never model- or question-dependent), so pre-populating the
5
- cache once here means every later --overlay-ids run, for every model, reuses these
6
- same files instead of recomputing the identical stamping from scratch each time --
7
- and the cached PNGs are themselves a durable, browsable record of what every scene's
8
- overlay actually looks like, independent of any particular model run.
9
-
10
- Usage:
11
- python -m harness.C.overlay_launch --depth metric --tracking tracking \\
12
- --input uniform --frames 32
13
- Pre-generates every scene with BOTH an explicit spatial code AND a SAM3
14
- perception cache for this config -- skips scenes already cached and scenes
15
- missing either dependency (reported, not silently dropped).
16
-
17
- python -m harness.C.overlay_launch --depth metric --tracking tracking \\
18
- --input uniform --frames 32 --scenes 42444976,45b0dac5e3
19
- Restrict to specific scenes.
20
-
21
- python -m harness.C.overlay_launch ... --rebuild
22
- Recompute even scenes whose cache already exists (e.g. after an overlay.py
23
- rendering change).
24
- """
25
-
26
- from __future__ import annotations
27
-
28
- import argparse
29
- import multiprocessing as mp
30
- import os
31
- import sys
32
- import traceback
33
- from pathlib import Path
34
-
35
- HERE = Path(__file__).resolve().parent
36
- WORKSPACE_ROOT = HERE.parent.parent
37
- if str(WORKSPACE_ROOT) not in sys.path:
38
- sys.path.insert(0, str(WORKSPACE_ROOT))
39
-
40
- from harness.A.launch import scenes as all_scenes # noqa: E402
41
- from harness.A import frames as frame_sampling # noqa: E402
42
- from harness.B import spatial_codes # noqa: E402
43
- from harness.C import overlay # noqa: E402
44
- import inference as inference_config # noqa: E402
45
-
46
-
47
- def _available_cpu_count():
48
- configured = os.environ.get("VSI_CPU_WORKERS")
49
- if configured is not None:
50
- count = int(configured)
51
- if count < 1:
52
- raise ValueError("VSI_CPU_WORKERS must be positive")
53
- return count
54
- try:
55
- return max(1, len(os.sched_getaffinity(0)))
56
- except AttributeError:
57
- return max(1, os.cpu_count() or 1)
58
-
59
-
60
- def _has_dependencies(scene, depth, input_selection, tracking, frame_count):
61
- """True iff this scene has both an explicit spatial code AND a raw SAM3 cache
62
- for this config -- both are required to stamp its frames."""
63
- try:
64
- spatial_codes.load_spatial_code(
65
- scene, depth, input_selection, tracking, frame_count, "explicit"
66
- )
67
- except FileNotFoundError:
68
- return False
69
- from encoder import config as encoder_config
70
-
71
- return Path(
72
- encoder_config.sam3_cache_file(scene, input_selection, tracking, frame_count)
73
- ).is_file()
74
-
75
-
76
- def _generate_one(args):
77
- scene, depth, input_selection, tracking, frame_count = args
78
- try:
79
- code, _path = spatial_codes.load_spatial_code(
80
- scene, depth, input_selection, tracking, frame_count, "explicit"
81
- )
82
- video_path = inference_config.video_path(scene, None)
83
- frame_images, _ts, _idx = frame_sampling.sample_frames(
84
- video_path, frame_count, input_selection
85
- )
86
- overlay.stamp_frames(
87
- frame_images,
88
- code,
89
- scene,
90
- depth,
91
- input_selection,
92
- tracking,
93
- frame_count,
94
- use_cache=True,
95
- )
96
- overlay.load_or_create_overlay_code(
97
- code, scene, depth, input_selection, tracking, frame_count
98
- )
99
- return scene, True, None
100
- except Exception:
101
- return scene, False, traceback.format_exc()
102
-
103
-
104
- def launch(
105
- depth, input_selection, tracking, frame_count, selected, rebuild=False, workers=0
106
- ):
107
- """Pre-generate the overlay-frame cache for every scene in ``selected`` that has
108
- both required dependencies. Returns (succeeded, failed, skipped_missing_deps)
109
- scene-name lists."""
110
- eligible, missing = [], []
111
- for scene in selected:
112
- if _has_dependencies(scene, depth, input_selection, tracking, frame_count):
113
- eligible.append(scene)
114
- else:
115
- missing.append(scene)
116
- if missing:
117
- print(
118
- f"[overlay-launch] {len(missing)} scene(s) missing a code or SAM3 cache, skipped:"
119
- )
120
- print(f" {missing}")
121
-
122
- if not rebuild:
123
- pending = []
124
- for scene in eligible:
125
- cache_dir = overlay.overlay_frame_cache_dir(
126
- scene, depth, input_selection, tracking, frame_count
127
- )
128
- code_path = overlay.overlay_spatial_code_path(
129
- scene, depth, input_selection, tracking, frame_count
130
- )
131
- if (
132
- overlay._load_cached_frames(cache_dir, frame_count) is not None
133
- and code_path.is_file()
134
- ):
135
- continue
136
- pending.append(scene)
137
- skipped = len(eligible) - len(pending)
138
- if skipped:
139
- print(f"[overlay-launch] {skipped} scene(s) already cached, skipped")
140
- else:
141
- pending = eligible
142
-
143
- if not pending:
144
- print(
145
- f"[overlay-launch] DONE: 0 generated, {len(eligible) - len(pending)} skipped"
146
- )
147
- return [], [], missing
148
-
149
- worker_count = workers if workers > 0 else _available_cpu_count()
150
- worker_count = min(worker_count, len(pending))
151
- print(
152
- f"[overlay-launch] generating {len(pending)} scene(s) with {worker_count} worker(s)"
153
- )
154
- tasks = [
155
- (scene, depth, input_selection, tracking, frame_count) for scene in pending
156
- ]
157
- with mp.get_context("spawn").Pool(worker_count) as pool:
158
- results = pool.map(_generate_one, tasks)
159
-
160
- succeeded = [scene for scene, ok, _ in results if ok]
161
- failed = [(scene, detail) for scene, ok, detail in results if not ok]
162
- for scene, detail in failed:
163
- print(f"[overlay-launch] FAILED {scene}:\n{detail}")
164
- print(
165
- f"[overlay-launch] DONE: {len(succeeded)} generated, {len(failed)} failed, "
166
- f"{len(eligible) - len(pending)} already cached"
167
- )
168
- return succeeded, failed, missing
169
-
170
-
171
- def main():
172
- parser = argparse.ArgumentParser()
173
- parser.add_argument("--depth", required=True)
174
- parser.add_argument("--tracking", required=True)
175
- parser.add_argument("--input", required=True, dest="input_selection")
176
- parser.add_argument("--frames", type=int, required=True)
177
- parser.add_argument(
178
- "--scenes", default=None, help="comma-separated scenes (default: all)"
179
- )
180
- parser.add_argument("--rebuild", action="store_true")
181
- parser.add_argument("--workers", type=int, default=0, help="0 = all available CPUs")
182
- args = parser.parse_args()
183
- selected = (
184
- [s.strip() for s in args.scenes.split(",") if s.strip()]
185
- if args.scenes
186
- else all_scenes()
187
- )
188
- _succeeded, failed, _missing = launch(
189
- args.depth,
190
- args.input_selection,
191
- args.tracking,
192
- args.frames,
193
- selected,
194
- rebuild=args.rebuild,
195
- workers=args.workers,
196
- )
197
- if failed:
198
- raise SystemExit(1)
199
-
200
-
201
- if __name__ == "__main__":
202
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
harness/C/prompts.py DELETED
@@ -1,24 +0,0 @@
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 DELETED
@@ -1,416 +0,0 @@
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
- results_dir=None,
55
- ):
56
- """Return the result root isolated by model + protocol + fixed explicit spatial code +
57
- depth + tracking + input + frames. ``protocol`` is "base" (16-token) or
58
- "<reasoning budget>" (e.g. "512") -- a real path segment, so records from
59
- different protocols OR different reasoning budgets can never collide 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, source_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"{source_info['protocol']}:{source_info['spatial_code_format']}:"
80
- f"{source_info['depth']}:{source_info['tracking']}:"
81
- + (
82
- "video"
83
- if source_info["input_selection"] == "video"
84
- else f"{source_info['input_selection']}:{source_info['frame_count']}"
85
- )
86
- ),
87
- "protocol": source_info["protocol"],
88
- "question_group": question_group(row["question_type"]),
89
- "spatial_code_format": source_info["spatial_code_format"],
90
- "input_selection": source_info["input_selection"],
91
- "frame_count": source_info["frame_count"],
92
- "depth": source_info["depth"],
93
- "tracking": source_info["tracking"],
94
- "spatial_code_path": source_info["spatial_code_path"],
95
- "video_path": source_info["video_path"],
96
- "frame_indices": source_info["frame_indices"],
97
- "frame_timestamps_seconds": source_info["frame_timestamps"],
98
- "scene": row["scene_name"],
99
- "dataset": row.get("dataset"),
100
- "question_id": row["id"],
101
- "question_type": row["question_type"],
102
- "question": row["question"],
103
- "options": row.get("options"),
104
- "full_prompt": prompt,
105
- "rendered_prompt": answer["prompt_text"],
106
- "answer_expected": row["ground_truth"],
107
- "answer_given": answer["answer_text"],
108
- "answer_raw": answer["answer_raw"],
109
- "input_token_count": answer["input_token_count"],
110
- "vision_input_shapes": answer["vision_input_shapes"],
111
- "output_token_ids": answer["output_token_ids"],
112
- "output_token_count": answer["output_token_count"],
113
- "hit_token_limit": answer["hit_token_limit"],
114
- "eos_token_ids": answer["eos_token_ids"],
115
- "generation_seconds": answer["generation_seconds"],
116
- "generation_config": answer["generation_config"],
117
- "reasoning_text": answer.get("reasoning_text"),
118
- "reasoning_raw": answer.get("reasoning_raw"),
119
- "reasoning_token_ids": answer.get("reasoning_token_ids"),
120
- "reasoning_token_count": answer.get("reasoning_token_count"),
121
- "reasoning_hit_limit": answer.get("reasoning_hit_limit"),
122
- "forced": answer.get("forced", False),
123
- "forced_input_token_count": answer.get("forced_input_token_count"),
124
- "metric": metric_name,
125
- "score": score,
126
- }
127
-
128
-
129
- def write_question_result(
130
- row,
131
- prompt,
132
- answer,
133
- metric_name,
134
- score,
135
- model,
136
- model_path,
137
- source_info,
138
- results_dir=None,
139
- ):
140
- """Write one question's full, untruncated result record. Return (path, record)."""
141
- record = _build_record(
142
- row, prompt, answer, metric_name, score, model, model_path, source_info
143
- )
144
- root = results_dir_for(
145
- model,
146
- source_info["protocol"],
147
- source_info["spatial_code_format"],
148
- source_info["depth"],
149
- source_info["tracking"],
150
- source_info["input_selection"],
151
- source_info["frame_count"],
152
- results_dir,
153
- )
154
- scene_dir = root / record["scene"]
155
- scene_dir.mkdir(parents=True, exist_ok=True)
156
- path = scene_dir / f"{row['id']}.json"
157
- with path.open("w", encoding="utf-8") as stream:
158
- json.dump(record, stream, indent=1)
159
- return path, record
160
-
161
-
162
- def run(
163
- model,
164
- spatial_code_format=DEFAULT_SPATIAL_CODE_FORMAT,
165
- input_selection=DEFAULT_INPUT_SELECTION,
166
- frame_count=FRAMES_PER_VIDEO,
167
- video=False,
168
- depth=DEFAULT_DEPTH,
169
- tracking=DEFAULT_TRACKING,
170
- scene=None,
171
- scenes=None,
172
- limit=None,
173
- device="cuda",
174
- jsonl_path=None,
175
- results_dir=None,
176
- write_results=True,
177
- adapter=None,
178
- extended=True,
179
- reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
180
- force_budget=MAX_NEW_TOKENS,
181
- ):
182
- """Answer every matching question with one model, given both its scene's video
183
- frames AND its spatial code as text -- both sourced from the same (depth, tracking,
184
- input_selection, frame_count) config, so they never mismatch.
185
-
186
- Uses ``adapter.answer_extended`` (a large ``reasoning_budget`` first pass, with a
187
- short forced second call only if the model doesn't conclude within it) as the
188
- standing default protocol, same as harness.B, since C combines the same complex
189
- spatial-code JSON with the video frames. ``extended=False`` runs harness.A's exact
190
- fixed 16-token base protocol instead (plain ``adapter.answer``), so the protocol x
191
- representation grid can be measured with the identical generation mechanism in
192
- every cell.
193
-
194
- Pass a pre-loaded ``adapter`` (as harness.C.launch's persistent per-GPU workers do)
195
- to reuse one already-loaded model across many calls; the caller then owns unloading
196
- it. Without one, ``run`` loads and unloads its own adapter, same as harness.A/B.
197
- """
198
- if video:
199
- input_selection = "video"
200
- frame_count = None
201
- elif frame_count is None or frame_count < 1:
202
- raise ValueError("frame_count must be positive in frames mode")
203
- if spatial_code_format != "explicit":
204
- raise ValueError("Harness C supports explicit spatial codes only")
205
- protocol = "mixed"
206
- results_dir = results_dir_for(
207
- model,
208
- protocol,
209
- spatial_code_format,
210
- depth,
211
- tracking,
212
- input_selection,
213
- frame_count,
214
- results_dir,
215
- )
216
- rows = load_questions(jsonl_path, scene, scenes, limit)
217
- if not rows:
218
- return []
219
- owns_adapter = adapter is None
220
- if owns_adapter:
221
- adapter = vlm_models.get_adapter(model)
222
- adapter.load_model(device)
223
- source_cache = {}
224
- results = []
225
- try:
226
- for row in rows:
227
- protocol = protocol_for_question(row["question_type"])
228
- scene_id = row["scene_name"]
229
- if scene_id not in source_cache:
230
- video_path = inference_config.video_path(scene_id, row.get("dataset"))
231
- if video:
232
- frame_images = video_path
233
- frame_timestamps = None
234
- frame_indices = None
235
- else:
236
- frame_images, frame_timestamps, frame_indices = (
237
- frame_sampling.sample_frames(
238
- video_path, frame_count, input_selection
239
- )
240
- )
241
- code, code_path = spatial_codes.load_spatial_code(
242
- scene_id,
243
- depth,
244
- input_selection,
245
- tracking,
246
- frame_count,
247
- spatial_code_format,
248
- )
249
- source_cache[scene_id] = {
250
- "video_path": video_path,
251
- "frame_images": frame_images,
252
- "frame_timestamps": frame_timestamps,
253
- "frame_indices": frame_indices,
254
- "code": code,
255
- "spatial_code_path": code_path,
256
- }
257
- cached = source_cache[scene_id]
258
- prompt = combined_prompts.build_prompt(
259
- cached["code"],
260
- row["question_type"],
261
- row["question"],
262
- row.get("options"),
263
- video=video,
264
- )
265
- answer = (
266
- adapter.answer_extended(
267
- cached["frame_images"],
268
- prompt,
269
- reasoning_budget=reasoning_budget,
270
- force_budget=force_budget,
271
- )
272
- if protocol == "thinking"
273
- else adapter.answer(
274
- cached["frame_images"], prompt, max_new_tokens=MAX_NEW_TOKENS
275
- )
276
- )
277
- doc = {
278
- "question_type": row["question_type"],
279
- "ground_truth": row["ground_truth"],
280
- }
281
- score_doc = vsi_official_eval.vsibench_process_results(
282
- doc, [answer["answer_text"]]
283
- )["vsibench_score"]
284
- metric_name, score = _scalar_score(row["question_type"], score_doc)
285
- source_info = {
286
- "protocol": protocol,
287
- "spatial_code_format": spatial_code_format,
288
- "input_selection": input_selection,
289
- "frame_count": frame_count,
290
- "depth": depth,
291
- "tracking": tracking,
292
- "spatial_code_path": cached["spatial_code_path"],
293
- "video_path": cached["video_path"],
294
- "frame_indices": cached["frame_indices"],
295
- "frame_timestamps": cached["frame_timestamps"],
296
- }
297
- if write_results:
298
- path, record = write_question_result(
299
- row,
300
- prompt,
301
- answer,
302
- metric_name,
303
- score,
304
- model,
305
- adapter.model_path,
306
- source_info,
307
- results_dir,
308
- )
309
- else:
310
- path = None
311
- record = _build_record(
312
- row,
313
- prompt,
314
- answer,
315
- metric_name,
316
- score,
317
- model,
318
- adapter.model_path,
319
- source_info,
320
- )
321
- record["result_path"] = str(path) if path else None
322
- results.append(record)
323
- finally:
324
- if owns_adapter:
325
- adapter.unload()
326
- return results
327
-
328
-
329
- def main():
330
- parser = argparse.ArgumentParser()
331
- parser.add_argument("--model", required=True, choices=vlm_models.available_models())
332
- parser.add_argument("--scene", default=None, help="restrict to one VSI-Bench scene")
333
- parser.add_argument(
334
- "--input-selection",
335
- default=None,
336
- choices=INPUT_SELECTIONS,
337
- dest="input_selection",
338
- )
339
- input_mode = parser.add_mutually_exclusive_group(required=True)
340
- input_mode.add_argument("--frames", type=int)
341
- input_mode.add_argument("--video", action="store_true")
342
- parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS)
343
- parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES)
344
- parser.add_argument(
345
- "--limit", type=int, default=None, help="cap the number of questions"
346
- )
347
- parser.add_argument("--device", default="cuda")
348
- parser.add_argument(
349
- "--results-dir",
350
- default=None,
351
- help="override the default results/C/<model>/explicit/"
352
- "<depth>/<tracking>/{<input>/<frames>|video} root",
353
- )
354
- parser.add_argument(
355
- "--no-write",
356
- action="store_true",
357
- help="skip writing per-question JSON files; print/score only",
358
- )
359
- parser.add_argument(
360
- "--reasoning-budget",
361
- type=int,
362
- default=None,
363
- help="thinking questions only (default: 2048)",
364
- )
365
- parser.add_argument(
366
- "--force-budget",
367
- type=int,
368
- default=None,
369
- help="thinking questions only (default: 16)",
370
- )
371
- args = parser.parse_args()
372
- if args.video:
373
- if args.input_selection is not None:
374
- parser.error("--input-selection cannot be used with --video")
375
- else:
376
- if args.input_selection is None:
377
- parser.error("--input-selection is required with --frames")
378
- if args.frames < 1:
379
- parser.error("--frames must be positive")
380
- resolve_protocol_budgets(parser, args)
381
- results = run(
382
- args.model,
383
- spatial_code_format=DEFAULT_SPATIAL_CODE_FORMAT,
384
- input_selection=args.input_selection,
385
- frame_count=args.frames,
386
- video=args.video,
387
- depth=args.depth,
388
- tracking=args.tracking,
389
- scene=args.scene,
390
- limit=args.limit,
391
- device=args.device,
392
- results_dir=args.results_dir,
393
- write_results=not args.no_write,
394
- extended=True,
395
- reasoning_budget=args.reasoning_budget,
396
- force_budget=args.force_budget,
397
- )
398
-
399
- for result in results:
400
- print(
401
- f"[{result['scene']}#{result['question_id']}] {result['question_type']}: "
402
- f"pred={result['answer_given']!r} gt={result['answer_expected']!r} "
403
- f"score={result['score']} ({result['generation_seconds']:.2f}s) -> "
404
- f"{result['result_path']}"
405
- )
406
- if results:
407
- mean_score = sum(r["score"] for r in results) / len(results)
408
- total_seconds = sum(r["generation_seconds"] for r in results)
409
- print(
410
- f"\n{len(results)} questions, mean vsibench_score={mean_score:.4f}, "
411
- f"total generation time={total_seconds:.1f}s"
412
- )
413
-
414
-
415
- if __name__ == "__main__":
416
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
harness/C/sweep.py DELETED
@@ -1,202 +0,0 @@
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_SPATIAL_CODE_FORMAT,
31
- DEFAULT_TRACKING,
32
- DEPTH_VARIANTS,
33
- INPUT_SELECTIONS,
34
- TRACKING_MODES,
35
- )
36
- from harness.C 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
- "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/D/__init__.py DELETED
@@ -1,42 +0,0 @@
1
- """Harness D: harness.B's spatial-code-as-text routing, but the spatial code is the
2
- GROUND-TRUTH one (encoder.ground_truth -- built from the dataset's own 3D annotations,
3
- zero perception error) instead of the SAM3+DA3-perceived one B reads off disk.
4
-
5
- Ground truth has no depth/tracking/input-selection/frame-count axis at all (it is built
6
- once per scene directly from annotations, not from any particular video-frame sampling
7
- run) -- so D only sweeps model x spatial_code_format, both formats, mirroring exactly
8
- the (model, format) grid harness.B actually swept at its one frozen (selection, frames)
9
- config. Deliberately NOT narrowed to just B's winning format: ground-truth codes cost
10
- nothing extra to build across formats (no encoder GPU pass at all), so running both
11
- formats is free relative to running one, and it is the only way to see whether a
12
- format's real-vs-perfect-perception ranking flips.
13
-
14
- Results are written in the identical per-question JSON shape harness.A/B/C use, so D's
15
- records are directly comparable and drop straight into analysis.aggregate/analysis.compare
16
- alongside every other harness. harness.D.symbolic_eval additionally answers every
17
- question with the real symbolic solver run directly against the ground-truth code (no
18
- VLM at all) -- the perfect-information ceiling -- written through symbolic.run's own
19
- writer into results/symbolic/ground truth/<format>/, the same results family every
20
- other symbolic-solver result already lives in, not a separate results/D/... location.
21
- """
22
-
23
- from __future__ import annotations
24
-
25
- import os
26
- from pathlib import Path
27
-
28
- from harness.A import (
29
- DO_SAMPLE,
30
- JSONL,
31
- MAX_NEW_TOKENS,
32
- MODEL_PATHS,
33
- TEMPERATURE,
34
- WORKSPACE_ROOT,
35
- )
36
- from harness.B import SPATIAL_CODE_FORMATS
37
-
38
- DEFAULT_SPATIAL_CODE_FORMAT = "explicit"
39
-
40
- # One JSON per question, matching harness.B's layout minus the axes ground truth doesn't
41
- # have: results/D/<model>/code/<protocol>/<spatial_code_format>/<scene>/<question_id>.json
42
- RESULTS_DIR = Path(os.environ.get("VSI_HARNESS_D_RESULTS_DIR", "/root/results/D"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
harness/D/launch.py DELETED
@@ -1,340 +0,0 @@
1
- """Keep every visible GPU busy with persistent harness-D inference workers.
2
-
3
- Same shape as ``harness.B.launch``, minus the depth/tracking/input-selection/frame-count
4
- axes ground truth doesn't have: one persistent worker process per visible GPU, pulling
5
- scenes off a shared queue, each loading its model exactly once and reusing it for every
6
- scene it's assigned (via ``run.run(..., adapter=...)``). One invocation covers one
7
- (model, spatial_code_format) pair across every requested scene; sweep multiple pairs by
8
- invoking this once per pair (see harness.D.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 encoder.ground_truth import scenes as ground_truth_scenes # noqa: E402
27
- from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402
28
- from harness.A import models as vlm_models # noqa: E402
29
- from harness.B import (
30
- DEFAULT_INPUT_SELECTION,
31
- FRAMES_PER_VIDEO,
32
- INPUT_SELECTIONS,
33
- ) # noqa: E402
34
- from harness.D import DEFAULT_SPATIAL_CODE_FORMAT, SPATIAL_CODE_FORMATS # noqa: E402
35
- from inference.launch import available_cpu_count, visible_gpus # noqa: E402
36
-
37
-
38
- def _load_run_module():
39
- spec = importlib.util.spec_from_file_location("_harness_D_run", HERE / "run.py")
40
- module = importlib.util.module_from_spec(spec)
41
- sys.modules[spec.name] = module
42
- spec.loader.exec_module(module)
43
- return module
44
-
45
-
46
- def _worker(
47
- tasks,
48
- results,
49
- model,
50
- spatial_code_format,
51
- results_dir,
52
- gpu,
53
- cpu_threads,
54
- extended,
55
- reasoning_budget,
56
- force_budget,
57
- frames,
58
- frame_selection,
59
- frame_count,
60
- raw_budget,
61
- thinking,
62
- ):
63
- if gpu is not None:
64
- os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
65
- for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
66
- os.environ[variable] = str(cpu_threads)
67
- run = _load_run_module()
68
- adapter = None
69
- load_error = None
70
- try:
71
- adapter = vlm_models.get_adapter(model)
72
- if thinking and not adapter.set_thinking(True):
73
- raise ValueError(f"{model} has no native thinking mode to enable")
74
- adapter.load_model("cuda:0" if gpu is not None else "cpu")
75
- except Exception:
76
- load_error = traceback.format_exc()
77
- while True:
78
- scene = tasks.get()
79
- if scene is None:
80
- return
81
- if load_error is not None:
82
- results.put((scene, False, load_error))
83
- continue
84
- try:
85
- answered = run.run(
86
- model,
87
- spatial_code_format=spatial_code_format,
88
- scene=scene,
89
- results_dir=results_dir,
90
- adapter=adapter,
91
- extended=extended,
92
- reasoning_budget=reasoning_budget,
93
- force_budget=force_budget,
94
- frames=frames,
95
- frame_selection=frame_selection,
96
- frame_count=frame_count,
97
- raw_budget=raw_budget,
98
- thinking=thinking,
99
- )
100
- mean_score = (
101
- sum(r["score"] for r in answered) / len(answered) if answered else None
102
- )
103
- results.put(
104
- (scene, True, f"{len(answered)} question(s), mean_score={mean_score}")
105
- )
106
- except Exception:
107
- results.put((scene, False, traceback.format_exc()))
108
-
109
-
110
- def launch(
111
- model,
112
- spatial_code_format,
113
- selected,
114
- results_dir=None,
115
- rebuild=False,
116
- extended=True,
117
- reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
118
- force_budget=MAX_NEW_TOKENS,
119
- frames=False,
120
- frame_selection=DEFAULT_INPUT_SELECTION,
121
- frame_count=FRAMES_PER_VIDEO,
122
- raw_budget=None,
123
- thinking=False,
124
- ):
125
- """Answer every question for ``selected`` scenes, sharded across every visible GPU.
126
-
127
- ``raw_budget`` (mutually exclusive with ``extended``) runs the raw-budget arm:
128
- base-protocol mechanics at this token cap, under its own truncated/<budget> path
129
- segment -- see harness.D.run.run."""
130
- if extended and raw_budget is not None:
131
- raise ValueError("extended and raw_budget are mutually exclusive")
132
- protocol = (
133
- f"{reasoning_budget}"
134
- if extended
135
- else f"truncated/{raw_budget}" if raw_budget is not None else "base"
136
- )
137
- condition = f"{model}/{protocol}/{spatial_code_format}"
138
- if frames:
139
- condition += f"/frames/{frame_selection}/{frame_count}"
140
- run = _load_run_module()
141
- root = run.results_dir_for(
142
- model,
143
- protocol,
144
- spatial_code_format,
145
- results_dir,
146
- frames=frames,
147
- frame_selection=frame_selection,
148
- frame_count=frame_count,
149
- )
150
- pending = []
151
- completed = 0
152
- for scene in selected:
153
- rows = run.load_questions(scene=scene)
154
- if not rows:
155
- raise ValueError(
156
- f"no questions found for scene {scene!r}; check the manifest/scene selection"
157
- )
158
- answered = all((root / scene / f"{row['id']}.json").is_file() for row in rows)
159
- if answered and not rebuild:
160
- completed += 1
161
- print(
162
- f"[{condition} {completed}/{len(selected)}] {scene}: skipped",
163
- flush=True,
164
- )
165
- else:
166
- pending.append(scene)
167
- if not pending:
168
- print(f"[{condition}] DONE: {len(selected)} ok, 0 failed")
169
- return
170
-
171
- gpus = visible_gpus()
172
- worker_count = min(len(pending), len(gpus) if gpus else 1)
173
- assignments = gpus[:worker_count] if gpus else [None]
174
- cpu_count = available_cpu_count()
175
- cpu_threads = max(1, cpu_count // worker_count)
176
- print(
177
- f"[{condition}] starting {worker_count} persistent worker(s); "
178
- f"GPUs={assignments}; CPU threads/worker={cpu_threads}",
179
- flush=True,
180
- )
181
-
182
- context = mp.get_context("spawn")
183
- tasks, results = context.Queue(), context.Queue()
184
- for scene in pending:
185
- tasks.put(scene)
186
- for _ in range(worker_count):
187
- tasks.put(None)
188
- workers = [
189
- context.Process(
190
- target=_worker,
191
- args=(
192
- tasks,
193
- results,
194
- model,
195
- spatial_code_format,
196
- results_dir,
197
- gpu,
198
- cpu_threads,
199
- extended,
200
- reasoning_budget,
201
- force_budget,
202
- frames,
203
- frame_selection,
204
- frame_count,
205
- raw_budget,
206
- thinking,
207
- ),
208
- )
209
- for gpu in assignments
210
- ]
211
- for worker in workers:
212
- worker.start()
213
- failed = []
214
- for finished in range(1, len(pending) + 1):
215
- scene, ok, detail = results.get()
216
- if not ok:
217
- failed.append(scene)
218
- print(
219
- f"[{condition} {completed + finished}/{len(selected)}] {scene}: "
220
- f"{'done' if ok else 'FAILED'}\n{detail}",
221
- flush=True,
222
- )
223
- for worker in workers:
224
- worker.join()
225
- print(
226
- f"[{condition}] DONE: {len(pending) - len(failed)} answered, {completed} skipped, "
227
- f"{len(failed)} failed"
228
- )
229
- if failed:
230
- raise SystemExit(1)
231
-
232
-
233
- def scenes():
234
- """Every scene that both has a real VSI-Bench question AND ground-truth annotation
235
- coverage -- i.e. every scene harness.A/B/C could ever be run on (all of them have GT,
236
- since encoder.ground_truth covers the full 288-scene meta_info set, a superset of any
237
- perception-built spatial code's coverage)."""
238
- from harness.A.launch import scenes as vsi_scenes
239
-
240
- ground_truth = set(ground_truth_scenes())
241
- return [scene for scene in vsi_scenes() if scene in ground_truth]
242
-
243
-
244
- def main():
245
- parser = argparse.ArgumentParser()
246
- parser.add_argument("scene", nargs="?")
247
- parser.add_argument(
248
- "--scenes",
249
- help="comma-separated scenes (cannot be combined with positional scene)",
250
- )
251
- parser.add_argument("--model", required=True, choices=vlm_models.available_models())
252
- parser.add_argument(
253
- "--spatial-code-format",
254
- default=DEFAULT_SPATIAL_CODE_FORMAT,
255
- choices=SPATIAL_CODE_FORMATS,
256
- dest="spatial_code_format",
257
- )
258
- parser.add_argument("--results-dir", default=None)
259
- parser.add_argument("--rebuild", action="store_true")
260
- parser.add_argument(
261
- "--base-protocol",
262
- action="store_true",
263
- help="run harness.A's exact fixed 16-token protocol instead of the extended default",
264
- )
265
- parser.add_argument(
266
- "--with-frames",
267
- action="store_true",
268
- dest="frames",
269
- help="frames+ground-truth-code arm: also sample and show the scene's raw video "
270
- "frames alongside the ground-truth code (default sampling: uniform, 32 frames -- "
271
- "the frozen Step-1 config)",
272
- )
273
- parser.add_argument(
274
- "--frame-selection",
275
- default=DEFAULT_INPUT_SELECTION,
276
- choices=INPUT_SELECTIONS,
277
- dest="frame_selection",
278
- help="only used with --with-frames",
279
- )
280
- parser.add_argument(
281
- "--frames-per-video",
282
- type=int,
283
- default=FRAMES_PER_VIDEO,
284
- dest="frame_count",
285
- help="only used with --with-frames",
286
- )
287
- parser.add_argument(
288
- "--thinking",
289
- action="store_true",
290
- help="enable the model's native thinking mode where supported; errors on models without the switch",
291
- )
292
- parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
293
- parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
294
- parser.add_argument(
295
- "--truncated-budget",
296
- type=int,
297
- default=None,
298
- help="raw-budget arm: base-protocol mechanics (single generation, no forced "
299
- "rescue) at this token cap instead of the hardcoded 16 (mutually exclusive "
300
- "with --base-protocol)",
301
- )
302
- args = parser.parse_args()
303
- if args.scene and args.scenes:
304
- parser.error("positional scene and --scenes cannot be used together")
305
- if args.scenes is not None:
306
- selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
307
- if not selected:
308
- parser.error("--scenes must contain at least one scene")
309
- selected = list(dict.fromkeys(selected))
310
- else:
311
- selected = [args.scene] if args.scene else scenes()
312
- if args.reasoning_budget < 1:
313
- parser.error("--reasoning-budget must be positive")
314
- if args.force_budget < 1:
315
- parser.error("--force-budget must be positive")
316
- if args.frame_count < 1:
317
- parser.error("--frames-per-video must be positive")
318
- if args.truncated_budget is not None and args.truncated_budget < 1:
319
- parser.error("--truncated-budget must be positive")
320
- if args.base_protocol and args.truncated_budget is not None:
321
- parser.error("--base-protocol and --truncated-budget are mutually exclusive")
322
- launch(
323
- args.model,
324
- args.spatial_code_format,
325
- selected,
326
- results_dir=args.results_dir,
327
- rebuild=args.rebuild,
328
- extended=not args.base_protocol and args.truncated_budget is None,
329
- frames=args.frames,
330
- frame_selection=args.frame_selection,
331
- frame_count=args.frame_count,
332
- thinking=args.thinking,
333
- reasoning_budget=args.reasoning_budget,
334
- force_budget=args.force_budget,
335
- raw_budget=args.truncated_budget,
336
- )
337
-
338
-
339
- if __name__ == "__main__":
340
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
harness/D/prompts.py DELETED
@@ -1,9 +0,0 @@
1
- """Ground-truth spatial-code prompt construction.
2
-
3
- Ground-truth and perceived code use the same v2 prompt text; only the loaded code file
4
- differs.
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- from harness.B.prompts import build_prompt
 
 
 
 
 
 
 
 
 
 
harness/D/run.py DELETED
@@ -1,457 +0,0 @@
1
- """Run one VLM over VSI-Bench questions through harness D's ground-truth-spatial-code-
2
- as-text routing.
3
-
4
- Writes one JSON file per question in the identical shape harness.A/B/C use -- the
5
- frame-provenance fields are replaced with spatial-code provenance fields
6
- (spatial_code_format, spatial_code_path), since D has no video frames and no depth/
7
- tracking/input-selection/frame-count axis at all (ground truth is built once per scene
8
- straight from dataset annotations). Scoring reuses the same real, unmodified official
9
- scorer every harness uses.
10
- """
11
-
12
- from __future__ import annotations
13
-
14
- import argparse
15
- import json
16
- import sys
17
- from pathlib import Path
18
-
19
- WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent
20
- if str(WORKSPACE_ROOT) not in sys.path:
21
- sys.path.insert(0, str(WORKSPACE_ROOT))
22
-
23
- import inference as inference_config # noqa: E402
24
- from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402
25
- from harness.A import frames as frame_sampling # noqa: E402
26
- from harness.A import models as vlm_models # noqa: E402
27
- from harness.A.run import _scalar_score, load_questions, vsi_official_eval # noqa: E402
28
- from harness.B import (
29
- DEFAULT_INPUT_SELECTION,
30
- FRAMES_PER_VIDEO,
31
- INPUT_SELECTIONS,
32
- ) # noqa: E402
33
- from harness.C import prompts as combined_prompts # noqa: E402
34
- from harness.D import (
35
- DEFAULT_SPATIAL_CODE_FORMAT,
36
- RESULTS_DIR,
37
- SPATIAL_CODE_FORMATS,
38
- ) # noqa: E402
39
- from harness.D import prompts as code_prompts # noqa: E402
40
- from harness.D import spatial_codes # noqa: E402
41
-
42
-
43
- def results_dir_for(
44
- model,
45
- protocol,
46
- spatial_code_format,
47
- results_dir=None,
48
- frames=False,
49
- frame_selection=DEFAULT_INPUT_SELECTION,
50
- frame_count=FRAMES_PER_VIDEO,
51
- ):
52
- """Return the result root isolated by model + protocol + spatial-code-format.
53
- ``protocol`` is "base" (16-token) or "<reasoning budget>" (e.g. "512") -- a real path segment, so records from different protocols OR
54
- different reasoning budgets can never collide on disk.
55
-
56
- ``frames=True`` (the frames+ground-truth-code arm) selects the sibling
57
- "code + frames" branch and appends "<selection>/<count>" -- video frames have no bearing on which ground-truth
58
- code gets loaded (ground truth has no depth/tracking/input-selection axis at all;
59
- see harness/D/__init__.py), but they DO change what the model sees, so this arm's
60
- records must never share a path with the text-only condition's."""
61
- if results_dir is not None:
62
- return Path(results_dir)
63
- root = (
64
- RESULTS_DIR
65
- / model
66
- / ("code + frames" if frames else "code")
67
- / protocol
68
- / spatial_code_format
69
- )
70
- if frames:
71
- root = root / frame_selection / str(frame_count)
72
- return root
73
-
74
-
75
- def _build_record(
76
- row, prompt, answer, metric_name, score, model, model_path, code_info
77
- ):
78
- """Assemble one question's full, untruncated result record (nothing summarized).
79
-
80
- ``code_info`` carries frame provenance (``video_path``, ``frame_indices``,
81
- ``frame_timestamps``) only for the frames+ground-truth-code arm; all three are None
82
- on the standard text-only condition, matching how harness.A/B/D's other optional
83
- fields (``reasoning_text`` etc.) are present-but-null rather than absent."""
84
- condition = f"{code_info['protocol']}:{code_info['spatial_code_format']}"
85
- if code_info.get("frames"):
86
- condition += (
87
- f":frames:{code_info['frame_selection']}:{code_info['frame_count']}"
88
- )
89
- return {
90
- "model": model,
91
- "model_path": str(model_path),
92
- "device": answer["device"],
93
- "dtype": answer["dtype"],
94
- "library_versions": answer["library_versions"],
95
- "condition": condition,
96
- "protocol": code_info["protocol"],
97
- "spatial_code_format": code_info["spatial_code_format"],
98
- "spatial_code_path": code_info["spatial_code_path"],
99
- "frames": code_info.get("frames", False),
100
- "frame_selection": code_info.get("frame_selection"),
101
- "frame_count": code_info.get("frame_count"),
102
- "video_path": code_info.get("video_path"),
103
- "frame_indices": code_info.get("frame_indices"),
104
- "frame_timestamps_seconds": code_info.get("frame_timestamps"),
105
- "scene": row["scene_name"],
106
- "dataset": row.get("dataset"),
107
- "question_id": row["id"],
108
- "question_type": row["question_type"],
109
- "question": row["question"],
110
- "options": row.get("options"),
111
- "full_prompt": prompt,
112
- "rendered_prompt": answer["prompt_text"],
113
- "answer_expected": row["ground_truth"],
114
- "answer_given": answer["answer_text"],
115
- "answer_raw": answer["answer_raw"],
116
- "input_token_count": answer["input_token_count"],
117
- "vision_input_shapes": answer["vision_input_shapes"],
118
- "output_token_ids": answer["output_token_ids"],
119
- "output_token_count": answer["output_token_count"],
120
- "hit_token_limit": answer["hit_token_limit"],
121
- "eos_token_ids": answer["eos_token_ids"],
122
- "generation_seconds": answer["generation_seconds"],
123
- "generation_config": answer["generation_config"],
124
- "reasoning_text": answer.get("reasoning_text"),
125
- "reasoning_raw": answer.get("reasoning_raw"),
126
- "reasoning_token_ids": answer.get("reasoning_token_ids"),
127
- "reasoning_token_count": answer.get("reasoning_token_count"),
128
- "reasoning_hit_limit": answer.get("reasoning_hit_limit"),
129
- "forced": answer.get("forced", False),
130
- "forced_input_token_count": answer.get("forced_input_token_count"),
131
- "metric": metric_name,
132
- "score": score,
133
- }
134
-
135
-
136
- def write_question_result(
137
- row,
138
- prompt,
139
- answer,
140
- metric_name,
141
- score,
142
- model,
143
- model_path,
144
- code_info,
145
- results_dir=None,
146
- ):
147
- """Write one question's full, untruncated result record. Return (path, record)."""
148
- record = _build_record(
149
- row, prompt, answer, metric_name, score, model, model_path, code_info
150
- )
151
- root = results_dir_for(
152
- model,
153
- code_info["protocol"],
154
- code_info["spatial_code_format"],
155
- results_dir,
156
- frames=code_info.get("frames", False),
157
- frame_selection=code_info.get("frame_selection", DEFAULT_INPUT_SELECTION),
158
- frame_count=code_info.get("frame_count", FRAMES_PER_VIDEO),
159
- )
160
- scene_dir = root / record["scene"]
161
- scene_dir.mkdir(parents=True, exist_ok=True)
162
- path = scene_dir / f"{row['id']}.json"
163
- with path.open("w", encoding="utf-8") as stream:
164
- json.dump(record, stream, indent=1)
165
- return path, record
166
-
167
-
168
- def run(
169
- model,
170
- spatial_code_format=DEFAULT_SPATIAL_CODE_FORMAT,
171
- scene=None,
172
- scenes=None,
173
- limit=None,
174
- device="cuda",
175
- jsonl_path=None,
176
- results_dir=None,
177
- write_results=True,
178
- adapter=None,
179
- thinking=False,
180
- extended=True,
181
- reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
182
- force_budget=MAX_NEW_TOKENS,
183
- code_transform=None,
184
- frames=False,
185
- frame_selection=DEFAULT_INPUT_SELECTION,
186
- frame_count=FRAMES_PER_VIDEO,
187
- raw_budget=None,
188
- ):
189
- """Answer every matching question with one model, given its scene's GROUND-TRUTH
190
- spatial code as text. Each question's full record is written to its own JSON file
191
- as soon as it is answered (unless ``write_results=False``).
192
-
193
- ``frames=True`` runs the frames+ground-truth-code arm: the scene's raw video is
194
- ALSO sampled (``frame_selection``/``frame_count``, harness.A.frames.sample_frames --
195
- the same sampling every harness uses; ground truth has no depth/tracking axis for
196
- frames to be sourced "from", so there is nothing for this to mismatch against) and
197
- shown alongside the ground-truth code, with harness.C's frames+code context line
198
- (byte-identical composition rule: harness.A's frame sentence + harness.B's code
199
- sentence, the same CODE_DESCRIPTION D's own text-only line already uses). This is
200
- the ground-truth counterpart of harness C -- C answers with frames + a PERCEIVED
201
- code; this is frames + the PERFECT code -- which harness C itself cannot produce,
202
- since its spatial-code loader is perception-only. The default ``frame_selection``/
203
- ``frame_count`` match the frozen Step-1 config (uniform, 32) so a default frames=True
204
- call needs no extra flags to land on the same sampling every other harness uses.
205
-
206
- Uses ``adapter.answer_extended`` as the standing default protocol, same as
207
- harness.B -- working through a full spatial-code JSON before answering benefits
208
- from more room than a short visual caption does. ``extended=False`` runs
209
- harness.A's exact fixed 16-token base protocol instead (plain ``adapter.answer``).
210
-
211
- ``raw_budget`` (mutually exclusive with ``extended``) runs the raw-budget arm --
212
- same mechanism as ``extended=False`` (single generation, no forced rescue) but at
213
- this token cap instead of the hardcoded 16, under its own "truncated/<budget>"
214
- protocol path segment (mirrors harness.B/C's identical arm) so it can never collide
215
- with either the extended or the base-protocol condition on disk.
216
-
217
- ``code_transform``, when given, is called as ``code_transform(code, scene_id,
218
- spatial_code_format)`` on each freshly loaded code and its return value is what
219
- the prompt is built from -- the hook the corruption module (README Theme 8) uses
220
- to run corrupted codes through this EXACT prompt/adapter path instead of a
221
- duplicated one. ``None`` (the default) leaves behavior byte-identical to before.
222
-
223
- Pass a pre-loaded ``adapter`` (as harness.D.launch's persistent per-GPU workers do)
224
- to reuse one already-loaded model across many calls; the caller then owns unloading
225
- it. Without one, ``run`` loads and unloads its own adapter, same as harness.A/B.
226
- """
227
- if extended and raw_budget is not None:
228
- raise ValueError("extended and raw_budget are mutually exclusive")
229
- rows = load_questions(jsonl_path, scene, scenes, limit)
230
- if not rows:
231
- return []
232
- owns_adapter = adapter is None
233
- if owns_adapter:
234
- adapter = vlm_models.get_adapter(model)
235
- if thinking and not adapter.set_thinking(True):
236
- raise ValueError(f"{model} has no native thinking mode to enable")
237
- adapter.load_model(device)
238
- code_cache = {}
239
- results = []
240
- try:
241
- for row in rows:
242
- scene_id = row["scene_name"]
243
- if scene_id not in code_cache:
244
- code, path = spatial_codes.load_spatial_code(
245
- scene_id, spatial_code_format
246
- )
247
- if code_transform is not None:
248
- code = code_transform(code, scene_id, spatial_code_format)
249
- entry = {"code": code, "path": path}
250
- if frames:
251
- video_path = inference_config.video_path(
252
- scene_id, row.get("dataset")
253
- )
254
- frame_images, frame_timestamps, frame_indices = (
255
- frame_sampling.sample_frames(
256
- video_path, frame_count, frame_selection
257
- )
258
- )
259
- entry.update(
260
- video_path=video_path,
261
- frame_images=frame_images,
262
- frame_timestamps=frame_timestamps,
263
- frame_indices=frame_indices,
264
- )
265
- code_cache[scene_id] = entry
266
- cached = code_cache[scene_id]
267
- prompt_builder = combined_prompts.build_prompt if frames else code_prompts.build_prompt
268
- prompt = prompt_builder(
269
- cached["code"],
270
- row["question_type"],
271
- row["question"],
272
- row.get("options"),
273
- )
274
- answer = (
275
- adapter.answer_extended(
276
- cached["frame_images"] if frames else [],
277
- prompt,
278
- reasoning_budget=reasoning_budget,
279
- force_budget=force_budget,
280
- )
281
- if extended
282
- else adapter.answer(
283
- cached["frame_images"] if frames else [],
284
- prompt,
285
- max_new_tokens=raw_budget,
286
- )
287
- )
288
- doc = {
289
- "question_type": row["question_type"],
290
- "ground_truth": row["ground_truth"],
291
- }
292
- score_doc = vsi_official_eval.vsibench_process_results(
293
- doc, [answer["answer_text"]]
294
- )["vsibench_score"]
295
- metric_name, score = _scalar_score(row["question_type"], score_doc)
296
- code_info = {
297
- "protocol": (
298
- f"{reasoning_budget}"
299
- if extended
300
- else f"truncated/{raw_budget}" if raw_budget is not None else "base"
301
- ),
302
- "spatial_code_format": spatial_code_format,
303
- "spatial_code_path": cached["path"],
304
- "frames": frames,
305
- "frame_selection": frame_selection if frames else None,
306
- "frame_count": frame_count if frames else None,
307
- "video_path": cached.get("video_path"),
308
- "frame_indices": cached.get("frame_indices"),
309
- "frame_timestamps": cached.get("frame_timestamps"),
310
- }
311
- if write_results:
312
- path, record = write_question_result(
313
- row,
314
- prompt,
315
- answer,
316
- metric_name,
317
- score,
318
- model,
319
- adapter.model_path,
320
- code_info,
321
- results_dir,
322
- )
323
- else:
324
- path = None
325
- record = _build_record(
326
- row,
327
- prompt,
328
- answer,
329
- metric_name,
330
- score,
331
- model,
332
- adapter.model_path,
333
- code_info,
334
- )
335
- record["result_path"] = str(path) if path else None
336
- results.append(record)
337
- finally:
338
- if owns_adapter:
339
- adapter.unload()
340
- return results
341
-
342
-
343
- def main():
344
- parser = argparse.ArgumentParser()
345
- parser.add_argument("--model", required=True, choices=vlm_models.available_models())
346
- parser.add_argument("--scene", default=None, help="restrict to one VSI-Bench scene")
347
- parser.add_argument(
348
- "--spatial-code-format",
349
- default=DEFAULT_SPATIAL_CODE_FORMAT,
350
- choices=SPATIAL_CODE_FORMATS,
351
- dest="spatial_code_format",
352
- )
353
- parser.add_argument(
354
- "--limit", type=int, default=None, help="cap the number of questions"
355
- )
356
- parser.add_argument("--device", default="cuda")
357
- parser.add_argument(
358
- "--results-dir",
359
- default=None,
360
- help="override the default results/D/<model>/<code or code + frames>/<protocol>/<format> root",
361
- )
362
- parser.add_argument(
363
- "--no-write",
364
- action="store_true",
365
- help="skip writing per-question JSON files; print/score only",
366
- )
367
- parser.add_argument(
368
- "--base-protocol",
369
- action="store_true",
370
- help="run harness.A's exact fixed 16-token protocol (plain answer()) instead of "
371
- "the extended 2048-token default",
372
- )
373
- parser.add_argument(
374
- "--with-frames",
375
- action="store_true",
376
- dest="frames",
377
- help="frames+ground-truth-code arm: also sample and show the scene's raw video "
378
- "frames alongside the ground-truth code (default sampling: uniform, 32 frames -- "
379
- "the frozen Step-1 config)",
380
- )
381
- parser.add_argument(
382
- "--frame-selection",
383
- default=DEFAULT_INPUT_SELECTION,
384
- choices=INPUT_SELECTIONS,
385
- dest="frame_selection",
386
- help="only used with --with-frames",
387
- )
388
- parser.add_argument(
389
- "--frames-per-video",
390
- type=int,
391
- default=FRAMES_PER_VIDEO,
392
- dest="frame_count",
393
- help="only used with --with-frames",
394
- )
395
- parser.add_argument(
396
- "--thinking",
397
- action="store_true",
398
- help="enable the model's native thinking mode where supported; errors on models without the switch",
399
- )
400
- parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
401
- parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
402
- parser.add_argument(
403
- "--truncated-budget",
404
- type=int,
405
- default=None,
406
- help="raw-budget arm: base-protocol mechanics (single generation, no forced "
407
- "rescue) at this token cap instead of the hardcoded 16 (mutually exclusive "
408
- "with --base-protocol)",
409
- )
410
- args = parser.parse_args()
411
- if args.reasoning_budget < 1:
412
- parser.error("--reasoning-budget must be positive")
413
- if args.force_budget < 1:
414
- parser.error("--force-budget must be positive")
415
- if args.frame_count < 1:
416
- parser.error("--frames-per-video must be positive")
417
- if args.truncated_budget is not None and args.truncated_budget < 1:
418
- parser.error("--truncated-budget must be positive")
419
- if args.base_protocol and args.truncated_budget is not None:
420
- parser.error("--base-protocol and --truncated-budget are mutually exclusive")
421
-
422
- results = run(
423
- args.model,
424
- spatial_code_format=args.spatial_code_format,
425
- scene=args.scene,
426
- limit=args.limit,
427
- device=args.device,
428
- results_dir=args.results_dir,
429
- write_results=not args.no_write,
430
- extended=not args.base_protocol and args.truncated_budget is None,
431
- thinking=args.thinking,
432
- reasoning_budget=args.reasoning_budget,
433
- force_budget=args.force_budget,
434
- frames=args.frames,
435
- frame_selection=args.frame_selection,
436
- frame_count=args.frame_count,
437
- raw_budget=args.truncated_budget,
438
- )
439
-
440
- for result in results:
441
- print(
442
- f"[{result['scene']}#{result['question_id']}] {result['question_type']}: "
443
- f"pred={result['answer_given']!r} gt={result['answer_expected']!r} "
444
- f"score={result['score']} ({result['generation_seconds']:.2f}s) -> "
445
- f"{result['result_path']}"
446
- )
447
- if results:
448
- mean_score = sum(r["score"] for r in results) / len(results)
449
- total_seconds = sum(r["generation_seconds"] for r in results)
450
- print(
451
- f"\n{len(results)} questions, mean vsibench_score={mean_score:.4f}, "
452
- f"total generation time={total_seconds:.1f}s"
453
- )
454
-
455
-
456
- if __name__ == "__main__":
457
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
harness/D/spatial_codes.py DELETED
@@ -1,32 +0,0 @@
1
- """Load one scene's GROUND-TRUTH spatial code (explicit or compact) as plain JSON.
2
-
3
- Same "no solver-side adaptation" philosophy as harness.B.spatial_codes: the model is
4
- shown literally the same file encoder.ground_truth wrote to disk -- schema legend
5
- included -- 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 ground_truth_spatial_code_path
14
-
15
- from harness.D import SPATIAL_CODE_FORMATS
16
-
17
-
18
- def load_spatial_code(scene, spatial_code_format):
19
- """Return (spatial code dict, path it was loaded from)."""
20
- if spatial_code_format not in SPATIAL_CODE_FORMATS:
21
- raise ValueError(
22
- f"unknown spatial-code format {spatial_code_format!r}; "
23
- f"expected one of {SPATIAL_CODE_FORMATS}"
24
- )
25
- path = ground_truth_spatial_code_path(scene, spatial_code_format)
26
- if not Path(path).is_file():
27
- raise FileNotFoundError(
28
- f"no ground-truth spatial code found for scene {scene!r} at {path} -- "
29
- "run `python -m encoder.ground_truth` to build it"
30
- )
31
- with open(path, encoding="utf-8") as stream:
32
- return json.load(stream), path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
harness/D/sweep.py DELETED
@@ -1,204 +0,0 @@
1
- """Sweep any set of models x spatial-code-formats over ground-truth spatial codes.
2
-
3
- Every (model, spatial_code_format) pair in the sweep is run through
4
- ``harness.D.launch.launch`` in turn, so each pair individually saturates every visible
5
- GPU before the next one starts. No depth/tracking/input-selection/frame-count axes --
6
- ground truth has none of those (see harness/D/__init__.py) -- so by design this sweeps
7
- BOTH spatial_code_formats for every model rather than picking one winning format, per
8
- this session's execution-design decision: ground-truth codes cost nothing extra to build
9
- across formats (no GPU encoder pass at all), so the marginal cost of covering both is
10
- just the extra VLM inference calls, and seeing whether a format's real-vs-perfect
11
- ranking flips is exactly the kind of thing this phase exists to check.
12
- """
13
-
14
- from __future__ import annotations
15
-
16
- import argparse
17
- from pathlib import Path
18
- import sys
19
-
20
- HERE = Path(__file__).resolve().parent
21
- WORKSPACE_ROOT = HERE.parent.parent
22
- if str(WORKSPACE_ROOT) not in sys.path:
23
- sys.path.insert(0, str(WORKSPACE_ROOT))
24
-
25
- from harness.A import models as vlm_models # noqa: E402
26
- from harness.A import EXTENDED_MAX_NEW_TOKENS # noqa: E402
27
- from harness.A.sweep import _parse_csv_choice # noqa: E402
28
- from harness.B import (
29
- DEFAULT_INPUT_SELECTION,
30
- FRAMES_PER_VIDEO,
31
- INPUT_SELECTIONS,
32
- SPATIAL_CODE_FORMATS,
33
- ) # noqa: E402
34
- from harness.D import launch as harness_launch # noqa: E402
35
-
36
-
37
- def build_plan(models, spatial_code_formats):
38
- """Return every (model, spatial_code_format) pair in the sweep."""
39
- return [
40
- (model, spatial_code_format)
41
- for model in models
42
- for spatial_code_format in spatial_code_formats
43
- ]
44
-
45
-
46
- def sweep(
47
- models,
48
- spatial_code_formats,
49
- selected_scenes,
50
- results_dir=None,
51
- rebuild=False,
52
- thinking=False,
53
- extended=True,
54
- reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
55
- frames=False,
56
- frame_selection=DEFAULT_INPUT_SELECTION,
57
- frame_count=FRAMES_PER_VIDEO,
58
- raw_budget=None,
59
- ):
60
- """Run every (model, spatial_code_format) pair across all visible GPUs."""
61
- plan = build_plan(models, spatial_code_formats)
62
- protocol = (
63
- f"{reasoning_budget}"
64
- if extended
65
- else f"truncated/{raw_budget}" if raw_budget is not None else "base"
66
- )
67
- for index, (model, spatial_code_format) in enumerate(plan, start=1):
68
- print(
69
- f"=== sweep {index}/{len(plan)}: {model}/{protocol}/{spatial_code_format}"
70
- + (f"/frames/{frame_selection}/{frame_count}" if frames else "")
71
- + " ===",
72
- flush=True,
73
- )
74
- harness_launch.launch(
75
- model,
76
- spatial_code_format,
77
- selected_scenes,
78
- results_dir=results_dir,
79
- rebuild=rebuild,
80
- thinking=thinking,
81
- extended=extended,
82
- reasoning_budget=reasoning_budget,
83
- frames=frames,
84
- frame_selection=frame_selection,
85
- frame_count=frame_count,
86
- raw_budget=raw_budget,
87
- )
88
-
89
-
90
- def main():
91
- parser = argparse.ArgumentParser()
92
- parser.add_argument("scene", nargs="?")
93
- parser.add_argument(
94
- "--scenes",
95
- help="comma-separated scenes (cannot be combined with positional scene)",
96
- )
97
- parser.add_argument(
98
- "--models",
99
- required=True,
100
- help=f"comma-separated models (or 'all'); one of {vlm_models.available_models()}",
101
- )
102
- parser.add_argument(
103
- "--spatial-code-formats",
104
- default="all",
105
- dest="spatial_code_formats",
106
- help=f"comma-separated formats (or 'all'); one of {SPATIAL_CODE_FORMATS}",
107
- )
108
- parser.add_argument("--results-dir", default=None)
109
- parser.add_argument("--rebuild", action="store_true")
110
- parser.add_argument(
111
- "--base-protocol",
112
- action="store_true",
113
- help="run the whole sweep under harness.A's exact fixed 16-token protocol "
114
- "instead of the extended default",
115
- )
116
- parser.add_argument(
117
- "--thinking",
118
- action="store_true",
119
- help="enable the model's native thinking mode where supported; errors on models without the switch",
120
- )
121
- parser.add_argument(
122
- "--reasoning-budget",
123
- type=int,
124
- default=EXTENDED_MAX_NEW_TOKENS,
125
- dest="reasoning_budget",
126
- help="extended-protocol first-pass budget (the calibrated value from "
127
- "analysis/preregistration.md, e.g. 512)",
128
- )
129
- parser.add_argument(
130
- "--with-frames",
131
- action="store_true",
132
- dest="frames",
133
- help="frames+ground-truth-code arm: also sample and show the scene's raw video "
134
- "frames alongside the ground-truth code (default sampling: uniform, 32 frames -- "
135
- "the frozen Step-1 config)",
136
- )
137
- parser.add_argument(
138
- "--frame-selection",
139
- default=DEFAULT_INPUT_SELECTION,
140
- choices=INPUT_SELECTIONS,
141
- dest="frame_selection",
142
- help="only used with --with-frames",
143
- )
144
- parser.add_argument(
145
- "--frames-per-video",
146
- type=int,
147
- default=FRAMES_PER_VIDEO,
148
- dest="frame_count",
149
- help="only used with --with-frames",
150
- )
151
- parser.add_argument(
152
- "--truncated-budget",
153
- type=int,
154
- default=None,
155
- help="raw-budget arm: base-protocol mechanics (single generation, no forced "
156
- "rescue) at this token cap instead of the hardcoded 16 (mutually exclusive "
157
- "with --base-protocol)",
158
- )
159
- args = parser.parse_args()
160
- if args.scene and args.scenes:
161
- parser.error("positional scene and --scenes cannot be used together")
162
- if args.frame_count < 1:
163
- parser.error("--frames-per-video must be positive")
164
- if args.truncated_budget is not None and args.truncated_budget < 1:
165
- parser.error("--truncated-budget must be positive")
166
- if args.base_protocol and args.truncated_budget is not None:
167
- parser.error("--base-protocol and --truncated-budget are mutually exclusive")
168
-
169
- try:
170
- models = _parse_csv_choice(
171
- args.models, vlm_models.available_models(), "--models"
172
- )
173
- spatial_code_formats = _parse_csv_choice(
174
- args.spatial_code_formats, SPATIAL_CODE_FORMATS, "--spatial-code-formats"
175
- )
176
- except ValueError as exc:
177
- parser.error(str(exc))
178
-
179
- if args.scenes is not None:
180
- selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
181
- if not selected:
182
- parser.error("--scenes must contain at least one scene")
183
- selected = list(dict.fromkeys(selected))
184
- else:
185
- selected = [args.scene] if args.scene else harness_launch.scenes()
186
-
187
- sweep(
188
- models,
189
- spatial_code_formats,
190
- selected,
191
- results_dir=args.results_dir,
192
- rebuild=args.rebuild,
193
- thinking=args.thinking,
194
- extended=not args.base_protocol and args.truncated_budget is None,
195
- reasoning_budget=args.reasoning_budget,
196
- frames=args.frames,
197
- frame_selection=args.frame_selection,
198
- frame_count=args.frame_count,
199
- raw_budget=args.truncated_budget,
200
- )
201
-
202
-
203
- if __name__ == "__main__":
204
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
harness/D/symbolic_eval.py DELETED
@@ -1,152 +0,0 @@
1
- """Run the real symbolic solver directly against ground-truth spatial codes -- no VLM at
2
- all -- the perfect-information ceiling: perfect geometry AND perfect (deterministic,
3
- formula-driven) reasoning over it.
4
-
5
- Reuses symbolic/solver.py and symbolic/adapters.py completely unmodified (the same
6
- solver harness.D.run's VLM path is being compared against use for scoring, and
7
- symbolic/run.py itself uses for the encoder-perceived spatial codes) -- this module only
8
- supplies ground-truth-sourced input instead of a perception-pipeline-sourced one.
9
-
10
- Results are written through symbolic.run's own writer, in symbolic's own native record
11
- shape, landing in the SAME results family every other symbolic-solver result already
12
- lives in: results/symbolic/ground truth/<format>/<scene>/<question_id>.json -- not a
13
- separate results/D/... location -- since this IS a symbolic-solver run, just against
14
- ground-truth input instead of a perception-pipeline selection
15
- (symbolic.run.select_ground_truth_spatial_codes).
16
- """
17
-
18
- from __future__ import annotations
19
-
20
- import argparse
21
- import sys
22
- from pathlib import Path
23
-
24
- WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent
25
- if str(WORKSPACE_ROOT) not in sys.path:
26
- sys.path.insert(0, str(WORKSPACE_ROOT))
27
-
28
- from harness.A.run import _scalar_score, load_questions, vsi_official_eval # noqa: E402
29
- from harness.D import DEFAULT_SPATIAL_CODE_FORMAT, SPATIAL_CODE_FORMATS # noqa: E402
30
- from harness.D import spatial_codes # noqa: E402
31
- from symbolic import adapters, solver # noqa: E402
32
- from symbolic import run as symbolic_run # noqa: E402
33
-
34
-
35
- def run(
36
- spatial_code_format=DEFAULT_SPATIAL_CODE_FORMAT,
37
- scene=None,
38
- scenes=None,
39
- limit=None,
40
- jsonl_path=None,
41
- results_dir=None,
42
- write_results=True,
43
- ):
44
- """Answer every matching question with the real symbolic solver, given each
45
- question's scene's GROUND-TRUTH spatial code. Writes symbolic's own native-shape
46
- record (results/symbolic/ground truth/<format>/...) when ``write_results``."""
47
- rows = load_questions(jsonl_path, scene, scenes, limit)
48
- if not rows:
49
- return []
50
- if write_results:
51
- symbolic_run.select_ground_truth_spatial_codes(spatial_code_format)
52
- code_cache = {}
53
- results = []
54
- for row in rows:
55
- scene_id = row["scene_name"]
56
- if scene_id not in code_cache:
57
- code, path = spatial_codes.load_spatial_code(scene_id, spatial_code_format)
58
- code_cache[scene_id] = {
59
- "adapted": adapters.adapt_spatial_code(code),
60
- "path": path,
61
- }
62
- cached = code_cache[scene_id]
63
- answer = solver.answer(
64
- row["question_type"], row["question"], row["options"], cached["adapted"]
65
- )
66
- pred_str = "" if answer is None else str(answer)
67
- doc = {
68
- "question_type": row["question_type"],
69
- "ground_truth": row["ground_truth"],
70
- }
71
- score_doc = vsi_official_eval.vsibench_process_results(doc, [pred_str])[
72
- "vsibench_score"
73
- ]
74
- _metric_name, score = _scalar_score(row["question_type"], score_doc)
75
- record = {
76
- "scene": scene_id,
77
- "dataset": row.get("dataset"),
78
- "question_id": row["id"],
79
- "question_type": row["question_type"],
80
- "question": row["question"],
81
- "answer_expected": row["ground_truth"],
82
- "answer_given": pred_str,
83
- "score": score,
84
- }
85
- if write_results:
86
- pq = {
87
- "question_id": row["id"],
88
- "dataset": row.get("dataset"),
89
- "question_type": row["question_type"],
90
- "question": row["question"],
91
- "options": row.get("options"),
92
- "engine_answer": answer,
93
- "ground_truth": row["ground_truth"],
94
- "score": score,
95
- }
96
- path = symbolic_run.write_question_result(
97
- scene_id, pq, cached["adapted"], results_dir=results_dir
98
- )
99
- record["result_path"] = str(path)
100
- else:
101
- record["result_path"] = None
102
- results.append(record)
103
- return results
104
-
105
-
106
- def main():
107
- parser = argparse.ArgumentParser()
108
- parser.add_argument("scene", nargs="?")
109
- parser.add_argument("--scenes", help="comma-separated scenes")
110
- parser.add_argument(
111
- "--spatial-code-format",
112
- default=DEFAULT_SPATIAL_CODE_FORMAT,
113
- choices=SPATIAL_CODE_FORMATS,
114
- dest="spatial_code_format",
115
- )
116
- parser.add_argument("--limit", type=int, default=None)
117
- parser.add_argument(
118
- "--results-dir",
119
- default=None,
120
- help="override the default results/symbolic/ground truth/<format> root",
121
- )
122
- parser.add_argument("--no-write", action="store_true")
123
- args = parser.parse_args()
124
- if args.scene and args.scenes:
125
- parser.error("positional scene and --scenes cannot be used together")
126
- selected = None
127
- if args.scenes:
128
- selected = list(
129
- dict.fromkeys(s.strip() for s in args.scenes.split(",") if s.strip())
130
- )
131
-
132
- results = run(
133
- spatial_code_format=args.spatial_code_format,
134
- scene=args.scene,
135
- scenes=selected,
136
- limit=args.limit,
137
- results_dir=args.results_dir,
138
- write_results=not args.no_write,
139
- )
140
- for result in results:
141
- print(
142
- f"[{result['scene']}#{result['question_id']}] {result['question_type']}: "
143
- f"pred={result['answer_given']!r} gt={result['answer_expected']!r} "
144
- f"score={result['score']} -> {result['result_path']}"
145
- )
146
- if results:
147
- mean_score = sum(r["score"] for r in results) / len(results)
148
- print(f"\n{len(results)} questions, mean vsibench_score={mean_score:.4f}")
149
-
150
-
151
- if __name__ == "__main__":
152
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
harness/E/__init__.py DELETED
@@ -1,31 +0,0 @@
1
- """Harness E: the BLIND floor -- question (and options) only, no video frames, no
2
- spatial code, no scene information of any kind.
3
-
4
- VSI-Bench's own paper shows blind LLMs beat chance on several categories through pure
5
- priors (typical room sizes, typical object sizes), so a question-only floor is what
6
- separates "the model used the geometry it was given" from "the prompt shifted its
7
- priors." Every harness A/B/C/D delta is only interpretable against this floor.
8
-
9
- Reuses harness.A's models, generation protocols (base 16-token by default, --extended
10
- opt-in, exactly like harness.A), question-type split, and post-prompts. Results are
11
- written in the identical per-question record shape as every other harness:
12
- results/E/<model>/<protocol>/<scene>/<question_id>.json.
13
- """
14
-
15
- from __future__ import annotations
16
-
17
- import os
18
- from pathlib import Path
19
-
20
- from harness.A import (
21
- DO_SAMPLE,
22
- JSONL,
23
- MAX_NEW_TOKENS,
24
- MODEL_PATHS,
25
- PROTOCOLS,
26
- TEMPERATURE,
27
- WORKSPACE_ROOT,
28
- )
29
-
30
- # One JSON per question: results/E/<model>/<protocol>/<scene>/<question_id>.json
31
- RESULTS_DIR = Path(os.environ.get("VSI_HARNESS_E_RESULTS_DIR", "/root/results/E"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
harness/E/launch.py DELETED
@@ -1,234 +0,0 @@
1
- """Keep every visible GPU busy with persistent harness-E (blind floor) 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
6
- covers one (model, protocol) pair across every requested scene.
7
- """
8
-
9
- from __future__ import annotations
10
-
11
- import argparse
12
- import importlib.util
13
- import multiprocessing as mp
14
- import os
15
- from pathlib import Path
16
- import sys
17
- import traceback
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 EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402
25
- from harness.A import models as vlm_models # noqa: E402
26
- from harness.A.launch import scenes # noqa: E402
27
- from inference.launch import available_cpu_count, visible_gpus # noqa: E402
28
-
29
-
30
- def _load_run_module():
31
- spec = importlib.util.spec_from_file_location("_harness_E_run", HERE / "run.py")
32
- module = importlib.util.module_from_spec(spec)
33
- sys.modules[spec.name] = module
34
- spec.loader.exec_module(module)
35
- return module
36
-
37
-
38
- def _worker(
39
- tasks,
40
- results,
41
- model,
42
- results_dir,
43
- gpu,
44
- cpu_threads,
45
- extended,
46
- reasoning_budget,
47
- force_budget,
48
- thinking,
49
- ):
50
- if gpu is not None:
51
- os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
52
- for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
53
- os.environ[variable] = str(cpu_threads)
54
- run = _load_run_module()
55
- adapter = None
56
- load_error = None
57
- try:
58
- adapter = vlm_models.get_adapter(model)
59
- if thinking and not adapter.set_thinking(True):
60
- raise ValueError(f"{model} has no native thinking mode to enable")
61
- adapter.load_model("cuda:0" if gpu is not None else "cpu")
62
- except Exception:
63
- load_error = traceback.format_exc()
64
- while True:
65
- scene = tasks.get()
66
- if scene is None:
67
- return
68
- if load_error is not None:
69
- results.put((scene, False, load_error))
70
- continue
71
- try:
72
- answered = run.run(
73
- model,
74
- scene=scene,
75
- results_dir=results_dir,
76
- adapter=adapter,
77
- extended=extended,
78
- reasoning_budget=reasoning_budget,
79
- force_budget=force_budget,
80
- thinking=thinking,
81
- )
82
- mean_score = (
83
- sum(r["score"] for r in answered) / len(answered) if answered else None
84
- )
85
- results.put(
86
- (scene, True, f"{len(answered)} question(s), mean_score={mean_score}")
87
- )
88
- except Exception:
89
- results.put((scene, False, traceback.format_exc()))
90
-
91
-
92
- def launch(
93
- model,
94
- selected,
95
- results_dir=None,
96
- rebuild=False,
97
- extended=False,
98
- reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
99
- force_budget=MAX_NEW_TOKENS,
100
- thinking=False,
101
- ):
102
- """Answer every question for ``selected`` scenes, sharded across every visible GPU."""
103
- protocol = f"{reasoning_budget}" if extended else "base"
104
- condition = f"{model}/{protocol}"
105
- run = _load_run_module()
106
- root = run.results_dir_for(model, protocol, results_dir)
107
- pending = []
108
- completed = 0
109
- for scene in selected:
110
- rows = run.load_questions(scene=scene)
111
- if not rows:
112
- raise ValueError(
113
- f"no questions found for scene {scene!r}; check the manifest/scene selection"
114
- )
115
- answered = all((root / scene / f"{row['id']}.json").is_file() for row in rows)
116
- if answered and not rebuild:
117
- completed += 1
118
- print(
119
- f"[{condition} {completed}/{len(selected)}] {scene}: skipped",
120
- flush=True,
121
- )
122
- else:
123
- pending.append(scene)
124
- if not pending:
125
- print(f"[{condition}] DONE: {len(selected)} ok, 0 failed")
126
- return
127
-
128
- gpus = visible_gpus()
129
- worker_count = min(len(pending), len(gpus) if gpus else 1)
130
- assignments = gpus[:worker_count] if gpus else [None]
131
- cpu_count = available_cpu_count()
132
- cpu_threads = max(1, cpu_count // worker_count)
133
- print(
134
- f"[{condition}] starting {worker_count} persistent worker(s); "
135
- f"GPUs={assignments}; CPU threads/worker={cpu_threads}",
136
- flush=True,
137
- )
138
-
139
- context = mp.get_context("spawn")
140
- tasks, results = context.Queue(), context.Queue()
141
- for scene in pending:
142
- tasks.put(scene)
143
- for _ in range(worker_count):
144
- tasks.put(None)
145
- workers = [
146
- context.Process(
147
- target=_worker,
148
- args=(
149
- tasks,
150
- results,
151
- model,
152
- results_dir,
153
- gpu,
154
- cpu_threads,
155
- extended,
156
- reasoning_budget,
157
- force_budget,
158
- thinking,
159
- ),
160
- )
161
- for gpu in assignments
162
- ]
163
- for worker in workers:
164
- worker.start()
165
- failed = []
166
- for finished in range(1, len(pending) + 1):
167
- scene, ok, detail = results.get()
168
- if not ok:
169
- failed.append(scene)
170
- print(
171
- f"[{condition} {completed + finished}/{len(selected)}] {scene}: "
172
- f"{'done' if ok else 'FAILED'}\n{detail}",
173
- flush=True,
174
- )
175
- for worker in workers:
176
- worker.join()
177
- print(
178
- f"[{condition}] DONE: {len(pending) - len(failed)} answered, {completed} skipped, "
179
- f"{len(failed)} failed"
180
- )
181
- if failed:
182
- raise SystemExit(1)
183
-
184
-
185
- def main():
186
- parser = argparse.ArgumentParser()
187
- parser.add_argument("scene", nargs="?")
188
- parser.add_argument(
189
- "--scenes",
190
- help="comma-separated scenes (cannot be combined with positional scene)",
191
- )
192
- parser.add_argument("--model", required=True, choices=vlm_models.available_models())
193
- parser.add_argument("--results-dir", default=None)
194
- parser.add_argument("--rebuild", action="store_true")
195
- parser.add_argument(
196
- "--extended",
197
- action="store_true",
198
- help="use the extended 2048-token protocol instead of the fixed 16-token default",
199
- )
200
- parser.add_argument(
201
- "--thinking",
202
- action="store_true",
203
- help="enable the model's native thinking mode where supported; errors on models without the switch",
204
- )
205
- parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
206
- parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
207
- args = parser.parse_args()
208
- if args.scene and args.scenes:
209
- parser.error("positional scene and --scenes cannot be used together")
210
- if args.scenes is not None:
211
- selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
212
- if not selected:
213
- parser.error("--scenes must contain at least one scene")
214
- selected = list(dict.fromkeys(selected))
215
- else:
216
- selected = [args.scene] if args.scene else scenes()
217
- if args.reasoning_budget < 1:
218
- parser.error("--reasoning-budget must be positive")
219
- if args.force_budget < 1:
220
- parser.error("--force-budget must be positive")
221
- launch(
222
- args.model,
223
- selected,
224
- results_dir=args.results_dir,
225
- rebuild=args.rebuild,
226
- extended=args.extended,
227
- thinking=args.thinking,
228
- reasoning_budget=args.reasoning_budget,
229
- force_budget=args.force_budget,
230
- )
231
-
232
-
233
- if __name__ == "__main__":
234
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
harness/E/prompts.py DELETED
@@ -1,36 +0,0 @@
1
- """VSI-Bench prompt construction with NO scene input at all -- the blind floor.
2
-
3
- Reuses harness.A.prompts's question-type split and final-answer constraints. There
4
- is deliberately NO context line: there are no frames and no spatial code to describe,
5
- and inventing one ("answer from your general knowledge") would itself be an
6
- uncontrolled prompt manipulation. The prompt is exactly the question (and options)
7
- plus the same post-prompt every other harness uses for that question type.
8
- """
9
-
10
- from __future__ import annotations
11
-
12
- from harness.A.prompts import (
13
- MCA_POST_PROMPT,
14
- MCA_QUESTION_TYPES,
15
- NA_POST_PROMPT,
16
- NA_QUESTION_TYPES,
17
- STEP_BY_STEP_REASONING_PROMPT,
18
- )
19
-
20
-
21
- def build_prompt(question_type, question, options=None):
22
- """Return the blind text prompt: the question, options (for MCA types), and the
23
- same VSI-Bench post-prompt harness.A uses for the same question_type."""
24
- if question_type in NA_QUESTION_TYPES:
25
- return "\n".join([question, STEP_BY_STEP_REASONING_PROMPT, NA_POST_PROMPT])
26
- if question_type in MCA_QUESTION_TYPES:
27
- if not options:
28
- raise ValueError(f"question_type {question_type!r} requires options")
29
- options_block = "Options:\n" + "\n".join(options)
30
- return "\n".join(
31
- [question, options_block, STEP_BY_STEP_REASONING_PROMPT, MCA_POST_PROMPT]
32
- )
33
- raise ValueError(
34
- f"unknown question_type {question_type!r}; "
35
- f"expected one of {MCA_QUESTION_TYPES + NA_QUESTION_TYPES}"
36
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
harness/E/run.py DELETED
@@ -1,262 +0,0 @@
1
- """Run one VLM over VSI-Bench questions completely blind -- question text only.
2
-
3
- Writes one JSON file per question in the identical shape harness.A/B/C/D use -- with no
4
- frame or spatial-code provenance fields at all, since E receives no scene input of any
5
- kind. Scoring reuses the same real, unmodified official scorer every harness uses.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- import argparse
11
- import json
12
- import sys
13
- from pathlib import Path
14
-
15
- WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent
16
- if str(WORKSPACE_ROOT) not in sys.path:
17
- sys.path.insert(0, str(WORKSPACE_ROOT))
18
-
19
- from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402
20
- from harness.A import models as vlm_models # noqa: E402
21
- from harness.A.run import _scalar_score, load_questions, vsi_official_eval # noqa: E402
22
- from harness.E import RESULTS_DIR # noqa: E402
23
- from harness.E import prompts as blind_prompts # noqa: E402
24
-
25
-
26
- def results_dir_for(model, protocol, results_dir=None):
27
- """Return the result root isolated by model + protocol. ``protocol`` is "base"
28
- (16-token) or "extended" (2048-token) -- a real path segment, so the two protocols'
29
- records can never collide on disk."""
30
- if results_dir is not None:
31
- return Path(results_dir)
32
- return RESULTS_DIR / model / protocol
33
-
34
-
35
- def _build_record(row, prompt, answer, metric_name, score, model, model_path, protocol):
36
- """Assemble one question's full, untruncated result record (nothing summarized)."""
37
- return {
38
- "model": model,
39
- "model_path": str(model_path),
40
- "device": answer["device"],
41
- "dtype": answer["dtype"],
42
- "library_versions": answer["library_versions"],
43
- "condition": protocol,
44
- "protocol": protocol,
45
- "scene": row["scene_name"],
46
- "dataset": row.get("dataset"),
47
- "question_id": row["id"],
48
- "question_type": row["question_type"],
49
- "question": row["question"],
50
- "options": row.get("options"),
51
- "full_prompt": prompt,
52
- "rendered_prompt": answer["prompt_text"],
53
- "answer_expected": row["ground_truth"],
54
- "answer_given": answer["answer_text"],
55
- "answer_raw": answer["answer_raw"],
56
- "input_token_count": answer["input_token_count"],
57
- "vision_input_shapes": answer["vision_input_shapes"],
58
- "output_token_ids": answer["output_token_ids"],
59
- "output_token_count": answer["output_token_count"],
60
- "hit_token_limit": answer["hit_token_limit"],
61
- "eos_token_ids": answer["eos_token_ids"],
62
- "generation_seconds": answer["generation_seconds"],
63
- "generation_config": answer["generation_config"],
64
- "reasoning_text": answer.get("reasoning_text"),
65
- "reasoning_raw": answer.get("reasoning_raw"),
66
- "reasoning_token_ids": answer.get("reasoning_token_ids"),
67
- "reasoning_token_count": answer.get("reasoning_token_count"),
68
- "reasoning_hit_limit": answer.get("reasoning_hit_limit"),
69
- "forced": answer.get("forced", False),
70
- "forced_input_token_count": answer.get("forced_input_token_count"),
71
- "metric": metric_name,
72
- "score": score,
73
- }
74
-
75
-
76
- def write_question_result(
77
- row,
78
- prompt,
79
- answer,
80
- metric_name,
81
- score,
82
- model,
83
- model_path,
84
- protocol,
85
- results_dir=None,
86
- ):
87
- """Write one question's full, untruncated result record. Return (path, record)."""
88
- record = _build_record(
89
- row, prompt, answer, metric_name, score, model, model_path, protocol
90
- )
91
- root = results_dir_for(model, protocol, results_dir)
92
- scene_dir = root / record["scene"]
93
- scene_dir.mkdir(parents=True, exist_ok=True)
94
- path = scene_dir / f"{row['id']}.json"
95
- with path.open("w", encoding="utf-8") as stream:
96
- json.dump(record, stream, indent=1)
97
- return path, record
98
-
99
-
100
- def run(
101
- model,
102
- scene=None,
103
- scenes=None,
104
- limit=None,
105
- device="cuda",
106
- jsonl_path=None,
107
- results_dir=None,
108
- write_results=True,
109
- adapter=None,
110
- thinking=False,
111
- extended=False,
112
- reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
113
- force_budget=MAX_NEW_TOKENS,
114
- ):
115
- """Answer every matching question with one model, completely blind (question text
116
- only, no frames, no spatial code). Each question's full record is written to its
117
- own JSON file as soon as it is answered (unless ``write_results=False``).
118
-
119
- Base 16-token protocol by default, exactly like harness.A; ``extended=True``
120
- switches to the same ``answer_extended`` protocol every other harness supports.
121
-
122
- Pass a pre-loaded ``adapter`` (as harness.E.launch's persistent per-GPU workers do)
123
- to reuse one already-loaded model across many calls; the caller then owns unloading
124
- it. Without one, ``run`` loads and unloads its own adapter, same as harness.A.
125
- """
126
- rows = load_questions(jsonl_path, scene, scenes, limit)
127
- if not rows:
128
- return []
129
- owns_adapter = adapter is None
130
- if owns_adapter:
131
- adapter = vlm_models.get_adapter(model)
132
- if thinking and not adapter.set_thinking(True):
133
- raise ValueError(f"{model} has no native thinking mode to enable")
134
- adapter.load_model(device)
135
- protocol = f"{reasoning_budget}" if extended else "base"
136
- results = []
137
- try:
138
- for row in rows:
139
- prompt = blind_prompts.build_prompt(
140
- row["question_type"], row["question"], row.get("options")
141
- )
142
- answer = (
143
- adapter.answer_extended(
144
- [],
145
- prompt,
146
- reasoning_budget=reasoning_budget,
147
- force_budget=force_budget,
148
- )
149
- if extended
150
- else adapter.answer([], prompt)
151
- )
152
- doc = {
153
- "question_type": row["question_type"],
154
- "ground_truth": row["ground_truth"],
155
- }
156
- score_doc = vsi_official_eval.vsibench_process_results(
157
- doc, [answer["answer_text"]]
158
- )["vsibench_score"]
159
- metric_name, score = _scalar_score(row["question_type"], score_doc)
160
- if write_results:
161
- path, record = write_question_result(
162
- row,
163
- prompt,
164
- answer,
165
- metric_name,
166
- score,
167
- model,
168
- adapter.model_path,
169
- protocol,
170
- results_dir,
171
- )
172
- else:
173
- path = None
174
- record = _build_record(
175
- row,
176
- prompt,
177
- answer,
178
- metric_name,
179
- score,
180
- model,
181
- adapter.model_path,
182
- protocol,
183
- )
184
- record["result_path"] = str(path) if path else None
185
- results.append(record)
186
- finally:
187
- if owns_adapter:
188
- adapter.unload()
189
- return results
190
-
191
-
192
- def main():
193
- parser = argparse.ArgumentParser()
194
- parser.add_argument("--model", required=True, choices=vlm_models.available_models())
195
- parser.add_argument("--scene", default=None, help="restrict to one VSI-Bench scene")
196
- parser.add_argument(
197
- "--limit", type=int, default=None, help="cap the number of questions"
198
- )
199
- parser.add_argument("--device", default="cuda")
200
- parser.add_argument(
201
- "--results-dir",
202
- default=None,
203
- help="override the default results/E/<model>/<protocol> root",
204
- )
205
- parser.add_argument(
206
- "--no-write",
207
- action="store_true",
208
- help="skip writing per-question JSON files; print/score only",
209
- )
210
- parser.add_argument(
211
- "--extended",
212
- action="store_true",
213
- help=(
214
- f"use a {EXTENDED_MAX_NEW_TOKENS}-token reasoning budget instead of the fixed "
215
- f"{MAX_NEW_TOKENS}-token VSI-Bench protocol, with a short forced second call "
216
- "only if the model doesn't conclude within it"
217
- ),
218
- )
219
- parser.add_argument(
220
- "--thinking",
221
- action="store_true",
222
- help="enable the model's native thinking mode where supported; errors on models without the switch",
223
- )
224
- parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
225
- parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
226
- args = parser.parse_args()
227
- if args.reasoning_budget < 1:
228
- parser.error("--reasoning-budget must be positive")
229
- if args.force_budget < 1:
230
- parser.error("--force-budget must be positive")
231
-
232
- results = run(
233
- args.model,
234
- scene=args.scene,
235
- limit=args.limit,
236
- device=args.device,
237
- results_dir=args.results_dir,
238
- write_results=not args.no_write,
239
- extended=args.extended,
240
- thinking=args.thinking,
241
- reasoning_budget=args.reasoning_budget,
242
- force_budget=args.force_budget,
243
- )
244
-
245
- for result in results:
246
- print(
247
- f"[{result['scene']}#{result['question_id']}] {result['question_type']}: "
248
- f"pred={result['answer_given']!r} gt={result['answer_expected']!r} "
249
- f"score={result['score']} ({result['generation_seconds']:.2f}s) -> "
250
- f"{result['result_path']}"
251
- )
252
- if results:
253
- mean_score = sum(r["score"] for r in results) / len(results)
254
- total_seconds = sum(r["generation_seconds"] for r in results)
255
- print(
256
- f"\n{len(results)} questions, mean vsibench_score={mean_score:.4f}, "
257
- f"total generation time={total_seconds:.1f}s"
258
- )
259
-
260
-
261
- if __name__ == "__main__":
262
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
harness/E/sweep.py DELETED
@@ -1,115 +0,0 @@
1
- """Sweep any set of models over the blind floor (question-only, no scene input).
2
-
3
- Every model in the sweep is run through ``harness.E.launch.launch`` in turn, so each
4
- model individually saturates every visible GPU before the next one starts. The only
5
- other axis is the generation protocol (--extended), matching harness.A's flag.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- import argparse
11
- from pathlib import Path
12
- import sys
13
-
14
- HERE = Path(__file__).resolve().parent
15
- WORKSPACE_ROOT = HERE.parent.parent
16
- if str(WORKSPACE_ROOT) not in sys.path:
17
- sys.path.insert(0, str(WORKSPACE_ROOT))
18
-
19
- from harness.A import EXTENDED_MAX_NEW_TOKENS # noqa: E402
20
- from harness.A import models as vlm_models # noqa: E402
21
- from harness.A.sweep import _parse_csv_choice # noqa: E402
22
- from harness.E import launch as harness_launch # noqa: E402
23
-
24
-
25
- def sweep(
26
- models,
27
- selected_scenes,
28
- results_dir=None,
29
- rebuild=False,
30
- thinking=False,
31
- extended=False,
32
- reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
33
- ):
34
- """Run every model across all visible GPUs."""
35
- protocol = "extended" if extended else "base"
36
- for index, model in enumerate(models, start=1):
37
- print(f"=== sweep {index}/{len(models)}: {model}/{protocol} ===", flush=True)
38
- harness_launch.launch(
39
- model,
40
- selected_scenes,
41
- results_dir=results_dir,
42
- rebuild=rebuild,
43
- thinking=thinking,
44
- extended=extended,
45
- reasoning_budget=reasoning_budget,
46
- )
47
-
48
-
49
- def main():
50
- parser = argparse.ArgumentParser()
51
- parser.add_argument("scene", nargs="?")
52
- parser.add_argument(
53
- "--scenes",
54
- help="comma-separated scenes (cannot be combined with positional scene)",
55
- )
56
- parser.add_argument(
57
- "--models",
58
- required=True,
59
- help=f"comma-separated models (or 'all'); one of {vlm_models.available_models()}",
60
- )
61
- parser.add_argument("--results-dir", default=None)
62
- parser.add_argument("--rebuild", action="store_true")
63
- parser.add_argument(
64
- "--extended",
65
- action="store_true",
66
- help="run the whole sweep under the extended protocol instead of the fixed "
67
- "16-token default",
68
- )
69
- parser.add_argument(
70
- "--thinking",
71
- action="store_true",
72
- help="enable the model's native thinking mode where supported; errors on models without the switch",
73
- )
74
- parser.add_argument(
75
- "--reasoning-budget",
76
- type=int,
77
- default=EXTENDED_MAX_NEW_TOKENS,
78
- dest="reasoning_budget",
79
- help="extended-protocol first-pass budget (the calibrated value from "
80
- "analysis/preregistration.md, e.g. 512)",
81
- )
82
- args = parser.parse_args()
83
- if args.scene and args.scenes:
84
- parser.error("positional scene and --scenes cannot be used together")
85
-
86
- try:
87
- models = _parse_csv_choice(
88
- args.models, vlm_models.available_models(), "--models"
89
- )
90
- except ValueError as exc:
91
- parser.error(str(exc))
92
-
93
- if args.scenes is not None:
94
- selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
95
- if not selected:
96
- parser.error("--scenes must contain at least one scene")
97
- selected = list(dict.fromkeys(selected))
98
- else:
99
- from harness.A.launch import scenes
100
-
101
- selected = [args.scene] if args.scene else scenes()
102
-
103
- sweep(
104
- models,
105
- selected,
106
- results_dir=args.results_dir,
107
- rebuild=args.rebuild,
108
- thinking=args.thinking,
109
- extended=args.extended,
110
- reasoning_budget=args.reasoning_budget,
111
- )
112
-
113
-
114
- if __name__ == "__main__":
115
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
harness/F/__init__.py DELETED
@@ -1,8 +0,0 @@
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 DELETED
@@ -1,6 +0,0 @@
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 DELETED
@@ -1,188 +0,0 @@
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 DELETED
@@ -1,79 +0,0 @@
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 DELETED
@@ -1,2 +0,0 @@
1
- """Top-level namespace for direct VLM-inference harnesses (as opposed to the
2
- encoder/symbolic spatial-code pipeline)."""