AntonioJun commited on
Commit
d5ae17d
·
verified ·
1 Parent(s): 1f7076d

Add files using upload-large-folder tool

Browse files
analysis/letters_reports.py CHANGED
@@ -19,7 +19,7 @@ from itertools import combinations
19
  from pathlib import Path
20
 
21
  ROOT = Path(__file__).resolve().parent.parent
22
- DEFAULT_DIRS = {h: Path("/root/results") / h for h in "ABC"}
23
  NUMERIC_FIELDS = (
24
  "input_token_count",
25
  "output_token_count",
@@ -249,6 +249,14 @@ def summarize_cell(records, code_cache):
249
  if records
250
  else None
251
  ),
 
 
 
 
 
 
 
 
252
  "forced": (
253
  statistics.mean(bool(r.get("forced")) for r in records)
254
  if records
@@ -414,7 +422,7 @@ def main():
414
  "--protocol",
415
  action="append",
416
  default=[],
417
- help="repeatable; family 'truncated' includes truncated/<budget>",
418
  )
419
  parser.add_argument(
420
  "--output-dir",
@@ -485,13 +493,6 @@ BUILTINS = {
485
  ],
486
  "capabilities": ["tokens", "latency", "reasoning", "frames", "spatial_code"],
487
  },
488
- "D": {
489
- "letter": "D",
490
- "kind": "vlm",
491
- "input_source": "ground_truth",
492
- "axes": ["model", "protocol", "format", "selection", "frames"],
493
- "capabilities": ["tokens", "latency", "reasoning", "frames", "spatial_code"],
494
- },
495
  "F": {
496
  "letter": "F",
497
  "kind": "solver",
@@ -515,8 +516,6 @@ def validate_profile(profile):
515
  letter = str(p.get("letter", "")).upper()
516
  if len(letter) != 1 or not letter.isalpha():
517
  raise ValueError("profile letter must be one alphabetic character")
518
- if letter == "E":
519
- raise ValueError("E is explicitly excluded")
520
  p["letter"] = letter
521
  p.setdefault("kind", "generic")
522
  p.setdefault("input_source", "unknown")
@@ -528,8 +527,6 @@ def validate_profile(profile):
528
 
529
  def load_profile(letter, path=None):
530
  letter = letter.upper()
531
- if letter == "E":
532
- raise ValueError("E is explicitly excluded")
533
  if path:
534
  p = json.loads(Path(path).read_text())
535
  p.setdefault("letter", letter)
@@ -623,35 +620,25 @@ def _normalize_record(letter, r, profile):
623
  if letter == "F":
624
  parts = list(r.get("_relative_path", ()))
625
  top = parts[0].lower() if parts else ""
626
- if top in ("ground truth", "ground_truth"):
627
- r.update(
628
- source="ground_truth",
629
- depth=None,
630
- tracking=None,
631
- selection=None,
632
- frames=None,
633
- )
634
- r["format"] = r.get("format") or (parts[1] if len(parts) > 1 else None)
635
- else:
636
- r["source"] = "perceived"
637
- offset = 1
638
- if top == "perceived":
639
- r["depth"] = r.get("depth") or (parts[1] if len(parts) > 1 else None)
640
- offset = 2
641
- elif top in ("metric", "relative"):
642
- r["depth"] = r.get("depth") or top
643
- r["tracking"] = r.get("tracking") or (
644
- parts[offset] if len(parts) > offset else None
645
- )
646
- r["selection"] = r.get("selection") or (
647
- parts[offset + 1] if len(parts) > offset + 1 else None
648
- )
649
- r["frames"] = r.get("frames") or (
650
- parts[offset + 2] if len(parts) > offset + 2 else None
651
- )
652
- candidate = parts[offset + 3] if len(parts) > offset + 3 else None
653
- if candidate and not candidate.startswith("scene") and len(candidate) != 10:
654
- r["format"] = r.get("format") or candidate
655
  r["spatial_code_model"] = r.get("spatial_code_model")
656
  r["protocol"] = None
657
  return r
@@ -687,11 +674,7 @@ def _compatible(a, b, profiles):
687
  f = x if lx == "F" else y if ly == "F" else None
688
  other = y if lx == "F" else x
689
  if f:
690
- expected = (
691
- "ground_truth"
692
- if other["harness"] == "D"
693
- else "perceived" if other["harness"] in ("B", "C") else None
694
- )
695
  if expected and f.get("source") != expected:
696
  return False, [], ["incompatible_F_source"]
697
  shared = []
@@ -806,9 +789,9 @@ def parse_assignment(value, option):
806
  raise argparse.ArgumentTypeError(f"{option} must be LETTER=PATH")
807
  letter, path = value.split("=", 1)
808
  letter = letter.upper()
809
- if len(letter) != 1 or not letter.isalpha() or letter == "E":
810
  raise argparse.ArgumentTypeError(
811
- "letter must be one alphabetic character other than E"
812
  )
813
  return letter, path
814
 
@@ -835,7 +818,7 @@ def main():
835
  "--cell",
836
  action="append",
837
  default=[],
838
- help="repeatable LETTER=PATH; E is excluded",
839
  )
840
  parser.add_argument(
841
  "--profile", action="append", default=[], help="optional LETTER=profile.json"
@@ -850,7 +833,7 @@ def main():
850
  "--protocol",
851
  action="append",
852
  default=[],
853
- help="repeatable; truncated includes truncated/<budget>",
854
  )
855
  parser.add_argument("--output-dir", default=str(ROOT / "reports"))
856
  parser.add_argument(
@@ -858,11 +841,11 @@ def main():
858
  default=None,
859
  help="optional local root used to rebase stale recorded code paths",
860
  )
861
- for h in "abc":
862
  parser.add_argument(f"--{h}-results-dir", default=None, help=argparse.SUPPRESS)
863
  args = parser.parse_args()
864
  cells = dict(parse_assignment(v, "--cell") for v in args.cell)
865
- for h in "abc":
866
  value = getattr(args, f"{h}_results_dir")
867
  if value:
868
  cells[h.upper()] = value
@@ -1100,8 +1083,6 @@ def generate(
1100
  spatial_codes_dir=None,
1101
  ):
1102
  normalized = {str(k).upper(): Path(v) for k, v in cells.items()}
1103
- if "E" in normalized:
1104
- raise ValueError("E is explicitly excluded")
1105
  profile_paths = {str(k).upper(): v for k, v in (profile_paths or {}).items()}
1106
  profiles = {l: load_profile(l, profile_paths.get(l)) for l in normalized}
1107
  pairs = []
@@ -1121,7 +1102,7 @@ def generate(
1121
 
1122
  def main():
1123
  parser = argparse.ArgumentParser(
1124
- description="Generate arbitrary mixed letter reports; E is excluded."
1125
  )
1126
  parser.add_argument("--cell", action="append", required=True)
1127
  parser.add_argument("--profile", action="append", default=[])
 
19
  from pathlib import Path
20
 
21
  ROOT = Path(__file__).resolve().parent.parent
22
+ DEFAULT_DIRS = {h: Path("/root/results") / h for h in "ABCE"}
23
  NUMERIC_FIELDS = (
24
  "input_token_count",
25
  "output_token_count",
 
249
  if records
250
  else None
251
  ),
252
+ "reasoning_present": (
253
+ statistics.mean(
254
+ bool(r.get("reasoning_text") or r.get("reasoning_raw"))
255
+ for r in records
256
+ )
257
+ if records
258
+ else None
259
+ ),
260
  "forced": (
261
  statistics.mean(bool(r.get("forced")) for r in records)
262
  if records
 
422
  "--protocol",
423
  action="append",
424
  default=[],
425
+ help="repeatable; select base or thinking protocol families",
426
  )
427
  parser.add_argument(
428
  "--output-dir",
 
493
  ],
494
  "capabilities": ["tokens", "latency", "reasoning", "frames", "spatial_code"],
495
  },
 
 
 
 
 
 
 
496
  "F": {
497
  "letter": "F",
498
  "kind": "solver",
 
516
  letter = str(p.get("letter", "")).upper()
517
  if len(letter) != 1 or not letter.isalpha():
518
  raise ValueError("profile letter must be one alphabetic character")
 
 
519
  p["letter"] = letter
520
  p.setdefault("kind", "generic")
521
  p.setdefault("input_source", "unknown")
 
527
 
528
  def load_profile(letter, path=None):
529
  letter = letter.upper()
 
 
530
  if path:
531
  p = json.loads(Path(path).read_text())
532
  p.setdefault("letter", letter)
 
620
  if letter == "F":
621
  parts = list(r.get("_relative_path", ()))
622
  top = parts[0].lower() if parts else ""
623
+ r["source"] = "perceived"
624
+ offset = 1
625
+ if top == "perceived":
626
+ r["depth"] = r.get("depth") or (parts[1] if len(parts) > 1 else None)
627
+ offset = 2
628
+ elif top in ("metric", "relative"):
629
+ r["depth"] = r.get("depth") or top
630
+ r["tracking"] = r.get("tracking") or (
631
+ parts[offset] if len(parts) > offset else None
632
+ )
633
+ r["selection"] = r.get("selection") or (
634
+ parts[offset + 1] if len(parts) > offset + 1 else None
635
+ )
636
+ r["frames"] = r.get("frames") or (
637
+ parts[offset + 2] if len(parts) > offset + 2 else None
638
+ )
639
+ candidate = parts[offset + 3] if len(parts) > offset + 3 else None
640
+ if candidate and not candidate.startswith("scene") and len(candidate) != 10:
641
+ r["format"] = r.get("format") or candidate
 
 
 
 
 
 
 
 
 
 
642
  r["spatial_code_model"] = r.get("spatial_code_model")
643
  r["protocol"] = None
644
  return r
 
674
  f = x if lx == "F" else y if ly == "F" else None
675
  other = y if lx == "F" else x
676
  if f:
677
+ expected = "perceived" if other["harness"] in ("B", "C") else None
 
 
 
 
678
  if expected and f.get("source") != expected:
679
  return False, [], ["incompatible_F_source"]
680
  shared = []
 
789
  raise argparse.ArgumentTypeError(f"{option} must be LETTER=PATH")
790
  letter, path = value.split("=", 1)
791
  letter = letter.upper()
792
+ if len(letter) != 1 or not letter.isalpha() or letter == "D":
793
  raise argparse.ArgumentTypeError(
794
+ "letter must be one alphabetic character other than D"
795
  )
796
  return letter, path
797
 
 
818
  "--cell",
819
  action="append",
820
  default=[],
821
+ help="repeatable LETTER=PATH; D is removed",
822
  )
823
  parser.add_argument(
824
  "--profile", action="append", default=[], help="optional LETTER=profile.json"
 
833
  "--protocol",
834
  action="append",
835
  default=[],
836
+ help="repeatable; select base or thinking protocol families",
837
  )
838
  parser.add_argument("--output-dir", default=str(ROOT / "reports"))
839
  parser.add_argument(
 
841
  default=None,
842
  help="optional local root used to rebase stale recorded code paths",
843
  )
844
+ for h in "abce":
845
  parser.add_argument(f"--{h}-results-dir", default=None, help=argparse.SUPPRESS)
846
  args = parser.parse_args()
847
  cells = dict(parse_assignment(v, "--cell") for v in args.cell)
848
+ for h in "abce":
849
  value = getattr(args, f"{h}_results_dir")
850
  if value:
851
  cells[h.upper()] = value
 
1083
  spatial_codes_dir=None,
1084
  ):
1085
  normalized = {str(k).upper(): Path(v) for k, v in cells.items()}
 
 
1086
  profile_paths = {str(k).upper(): v for k, v in (profile_paths or {}).items()}
1087
  profiles = {l: load_profile(l, profile_paths.get(l)) for l in normalized}
1088
  pairs = []
 
1102
 
1103
  def main():
1104
  parser = argparse.ArgumentParser(
1105
+ description="Generate arbitrary mixed letter reports; D is removed."
1106
  )
1107
  parser.add_argument("--cell", action="append", required=True)
1108
  parser.add_argument("--profile", action="append", default=[])
data/spatial codes/sam3+depth-anything-3/metric/tracking/uniform/32/compact/42898826.json ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "spatial code schema": {
3
+ "objects": {
4
+ "<object class>": [
5
+ {
6
+ "3D oriented bounding box": {
7
+ "3D oriented bounding box center coordinates": {
8
+ "components": [
9
+ "x",
10
+ "y",
11
+ "height above floor"
12
+ ],
13
+ "unit": "meters",
14
+ "description": "center of the 3D oriented bounding box in the shared room coordinate system"
15
+ },
16
+ "3D oriented bounding box dimensions": {
17
+ "components": [
18
+ "dimension 1",
19
+ "dimension 2",
20
+ "dimension 3"
21
+ ],
22
+ "unit": "meters",
23
+ "description": "full lengths of the 3D oriented bounding box along the corresponding orientation unit vectors"
24
+ },
25
+ "3D oriented bounding box orientation unit vectors": {
26
+ "components": [
27
+ [
28
+ "x",
29
+ "y",
30
+ "height"
31
+ ],
32
+ [
33
+ "x",
34
+ "y",
35
+ "height"
36
+ ],
37
+ [
38
+ "x",
39
+ "y",
40
+ "height"
41
+ ]
42
+ ],
43
+ "unit": null,
44
+ "description": "three perpendicular directions corresponding in order to the three 3D oriented bounding box dimensions"
45
+ }
46
+ },
47
+ "first visible time": {
48
+ "unit": "seconds",
49
+ "description": "earliest time at which this object instance is visibly observed"
50
+ }
51
+ }
52
+ ]
53
+ },
54
+ "room": {
55
+ "floor boundary polygons": [
56
+ {
57
+ "outer boundary coordinates": {
58
+ "components": [
59
+ [
60
+ "x",
61
+ "y"
62
+ ],
63
+ [
64
+ "x",
65
+ "y"
66
+ ]
67
+ ],
68
+ "unit": "meters",
69
+ "description": "ordered vertices enclosing one floor region"
70
+ },
71
+ "interior hole boundary coordinates": {
72
+ "components": [
73
+ [
74
+ [
75
+ "x",
76
+ "y"
77
+ ],
78
+ [
79
+ "x",
80
+ "y"
81
+ ]
82
+ ]
83
+ ],
84
+ "unit": "meters",
85
+ "description": "ordered boundaries enclosing regions excluded from the floor area"
86
+ }
87
+ }
88
+ ]
89
+ }
90
+ },
91
+ "objects": {
92
+ "bathtub": [
93
+ {
94
+ "3D oriented bounding box": {
95
+ "3D oriented bounding box center coordinates": [
96
+ 0.46,
97
+ -0.1,
98
+ -0.21
99
+ ],
100
+ "3D oriented bounding box dimensions": [
101
+ 1.21,
102
+ 0.92,
103
+ 0.5
104
+ ],
105
+ "3D oriented bounding box orientation unit vectors": [
106
+ [
107
+ 0.66,
108
+ 0.75,
109
+ 0.0
110
+ ],
111
+ [
112
+ -0.75,
113
+ 0.66,
114
+ 0.0
115
+ ],
116
+ [
117
+ 0.0,
118
+ 0.0,
119
+ 1.0
120
+ ]
121
+ ]
122
+ },
123
+ "first visible time": 1.0
124
+ }
125
+ ],
126
+ "toilet": [
127
+ {
128
+ "3D oriented bounding box": {
129
+ "3D oriented bounding box center coordinates": [
130
+ -0.64,
131
+ -1.26,
132
+ -0.35
133
+ ],
134
+ "3D oriented bounding box dimensions": [
135
+ 0.36,
136
+ 0.34,
137
+ 0.39
138
+ ],
139
+ "3D oriented bounding box orientation unit vectors": [
140
+ [
141
+ 0.76,
142
+ 0.65,
143
+ 0.0
144
+ ],
145
+ [
146
+ -0.65,
147
+ 0.76,
148
+ 0.0
149
+ ],
150
+ [
151
+ 0.0,
152
+ 0.0,
153
+ 1.0
154
+ ]
155
+ ]
156
+ },
157
+ "first visible time": 2.5
158
+ }
159
+ ]
160
+ },
161
+ "room": {
162
+ "floor boundary polygons": [
163
+ {
164
+ "outer boundary coordinates": [
165
+ [
166
+ -2.22,
167
+ -0.7
168
+ ],
169
+ [
170
+ -1.82,
171
+ -0.7
172
+ ],
173
+ [
174
+ -1.72,
175
+ -0.8
176
+ ],
177
+ [
178
+ -1.52,
179
+ -0.8
180
+ ],
181
+ [
182
+ -1.32,
183
+ -1.0
184
+ ],
185
+ [
186
+ -1.32,
187
+ -1.9
188
+ ],
189
+ [
190
+ 0.58,
191
+ -1.9
192
+ ],
193
+ [
194
+ 0.58,
195
+ -1.6
196
+ ],
197
+ [
198
+ 0.68,
199
+ -1.5
200
+ ],
201
+ [
202
+ 0.68,
203
+ -1.3
204
+ ],
205
+ [
206
+ 0.78,
207
+ -1.2
208
+ ],
209
+ [
210
+ 0.78,
211
+ -1.1
212
+ ],
213
+ [
214
+ 0.88,
215
+ -1.0
216
+ ],
217
+ [
218
+ 0.88,
219
+ -0.8
220
+ ],
221
+ [
222
+ 0.98,
223
+ -0.7
224
+ ],
225
+ [
226
+ 0.98,
227
+ -0.5
228
+ ],
229
+ [
230
+ 1.08,
231
+ -0.4
232
+ ],
233
+ [
234
+ 1.38,
235
+ -0.4
236
+ ],
237
+ [
238
+ 1.38,
239
+ 1.9
240
+ ],
241
+ [
242
+ -0.62,
243
+ 1.9
244
+ ],
245
+ [
246
+ -0.62,
247
+ 1.7
248
+ ],
249
+ [
250
+ -0.72,
251
+ 1.6
252
+ ],
253
+ [
254
+ -0.72,
255
+ 1.5
256
+ ],
257
+ [
258
+ -0.92,
259
+ 1.3
260
+ ],
261
+ [
262
+ -1.52,
263
+ 1.3
264
+ ],
265
+ [
266
+ -1.62,
267
+ 1.4
268
+ ],
269
+ [
270
+ -1.62,
271
+ 1.6
272
+ ],
273
+ [
274
+ -2.22,
275
+ 1.6
276
+ ]
277
+ ],
278
+ "interior hole boundary coordinates": []
279
+ }
280
+ ]
281
+ }
282
+ }
encoder/.ipynb_checkpoints/geometric-checkpoint.py ADDED
@@ -0,0 +1,2333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Geometric assembler (runs in the pipeline venv). Imported by encoder/render.py.
2
+
3
+ Pure math/assembly -- builds the per-instance spatial code (object positions/sizes, pairwise
4
+ distances, closeness ranks, room outline, camera trajectory, appearance order) FROM
5
+ already-computed depth/pose/masks. Does NOT run DA3 or SAM3, and does not call cache_or_load()
6
+ -- that's run.py's job entirely (the only file that calls the actual model-inference functions).
7
+ Callers may provide raw depth/intr/c2w/conf/ftimes/per inputs or canonical world-space
8
+ geometry; both feed build_compact_spatial_code() (see its own docstring for how it handles
9
+ that duality). The explicit schema is no longer built independently: it is a strict derivation
10
+ of the compact schema (build_explicit_spatial_code() calls build_compact_spatial_code() first,
11
+ then reads every explicit value directly off compact's own oriented boxes and floor polygons --
12
+ positions/dimensions/counts/appearance-order are direct subsets, and the distance table is
13
+ computed purely from compact's 3D oriented boxes). This guarantees the two schemas can never
14
+ silently disagree about the same scene's geometry.
15
+
16
+ Formerly this file called into perceptual.py (as a dynamically-loaded `pl` module) for its own
17
+ geometry helpers -- build_instances, room_gravity, answer_closest_distance, and everything else
18
+ in this file below _room_outline(). Those functions are now merged in directly, verbatim, since
19
+ they were never DA3/SAM3 calls -- they're geometric computations over already-extracted
20
+ depth/masks, which is exactly this file's job. perceptual.py's OTHER half (the actual
21
+ model-calling functions) moved to run.py instead; perceptual.py itself no longer exists.
22
+
23
+ The spatial code is the sole spatial representation the downstream VLM sees; no answer engine
24
+ is computed here (the harness runs the model).
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import os
30
+ import json
31
+ import numpy as np
32
+ import cv2
33
+
34
+ # ==========================================================================================
35
+ # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
36
+ # affect only the math below (build_instances/backproject_frame/etc.), never model inference.
37
+ # ==========================================================================================
38
+
39
+ SCHEMA = [
40
+ "x",
41
+ "y",
42
+ "z",
43
+ "e1",
44
+ "e2",
45
+ "e3",
46
+ "px",
47
+ "pz",
48
+ "size_median",
49
+ "size_IQR",
50
+ "time",
51
+ "n",
52
+ ] # legacy row schema, see to_labeled()
53
+ KD_WORKERS = max(1, int(os.environ.get("VSI_KD_WORKERS", "4")))
54
+ # Batch workers set VSI_KD_WORKERS from their per-process CPU budget. Keeping a
55
+ # bounded default avoids pathological all-core thread spawning for small queries.
56
+ MIN_INSTANCE_PTS = (
57
+ 1 # bare geometry floor only: need >=1 valid depth pixel to place a 3D point.
58
+ )
59
+ # NO quality filtering / dedup -- count = exactly SAM3's tracked masklets (honest)
60
+ FLOOR_BAND = (
61
+ 0.15 # m above the floor to count as floor-level (LEGACY -- currently unreferenced;
62
+ )
63
+ # compute_floor_area now uses the RANSAC gravity plane directly instead)
64
+ # ---- geometry-cleanup levers (improve abs_distance etc.; env-tunable) ----
65
+ # DEPTH_COHERENCE (Tukey-fence bleed removal): SAFE + helpful everywhere -> default ON.
66
+ # ablation: ARKit abs_distance 0.757->0.729 (no harm), ScanNet++ d755 0.443->0.486 (helps).
67
+ # CONF_PCT (per-frame confidence percentile): noisy-dataset ONLY -> default OFF.
68
+ # helps ScanNet++ distance more (~0.56) but DESTROYS clean ARKit (0.757->0.429). Opt in via VSI_CONF_PCT=55.
69
+ CONF_PCT = float(os.environ.get("VSI_CONF_PCT", "0"))
70
+ DEPTH_COHERENCE = os.environ.get("VSI_DEPTH_COHERENCE", "1") == "1"
71
+ # cut mask-bleed at per-frame depth edges. Default OFF: it's a NO-OP on the dominant failure (same-depth bleed
72
+ # -- adjacent objects at similar range have no depth edge), and only helps depth-SEPARATED bleed. Enable per-need.
73
+ DEPTH_EDGE_REFINE = os.environ.get("VSI_DEPTH_EDGE_REFINE", "0") == "1"
74
+ # MASK_REFINE (appearance-guided boundary snap): uses the RGB color edge to clip same-depth mask bleed that
75
+ # depth can't see. Principled + cheap (CPU, no model). Default OFF until validated; enable via VSI_MASK_REFINE=1.
76
+ MASK_REFINE = os.environ.get("VSI_MASK_REFINE", "0") == "1"
77
+
78
+
79
+ # ==========================================================================================
80
+ # ROOM/OBJECT GEOMETRY -- gravity, floor basis, per-instance spatial-code records. Merged in
81
+ # from perceptual.py, verbatim.
82
+ # ==========================================================================================
83
+
84
+
85
+ def to_labeled(objects, floor_area):
86
+ """LEGACY per-class summary (kept for --format array-compat). Superseded by to_spatial_code."""
87
+ out = {"objects": {}}
88
+ for cls, row in objects.items():
89
+ d = dict(zip(SCHEMA, row))
90
+ out["objects"][cls] = {
91
+ "count": int(d["n"]),
92
+ "centroid_meters": {"x": d["x"], "y": d["y"], "z": d["z"]},
93
+ "longest_dimension_meters": {
94
+ "median": d["size_median"],
95
+ "iqr": d["size_IQR"],
96
+ },
97
+ "centroid_spread": {
98
+ "eigenvalues": [d["e1"], d["e2"], d["e3"]],
99
+ "principal_axis_xz": [d["px"], d["pz"]],
100
+ },
101
+ "first_seen_seconds": d["time"],
102
+ }
103
+ out["room"] = {"floor_area_square_meters": floor_area}
104
+ return out
105
+
106
+
107
+ def room_up_axis(instances, c2w):
108
+ """up axis = smallest-extent axis of all object points; sign from gravity (floor->camera).
109
+ Floor = densest horizontal slab; cameras are always above it, which fixes the sign.
110
+ Returns (axis_index, signed_unit_vector)."""
111
+ points = np.concatenate([i["pts"] for v in instances.values() for i in v], 0)
112
+ ext = np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
113
+ up = int(np.argmin(ext))
114
+ h, edges = np.histogram(points[:, up], bins=80)
115
+ floor = 0.5 * (edges[h.argmax()] + edges[h.argmax() + 1]) # densest slab = floor
116
+ cam_up = c2w[:, :3, 3][:, up].mean()
117
+ e = np.zeros(3, np.float32)
118
+ e[up] = 1.0 if cam_up > floor else -1.0
119
+ return up, e
120
+
121
+
122
+ def room_gravity(
123
+ depth, intr, c2w, conf, conf_pct=40, stride=12, fstride=15, iters=300, thr=0.05
124
+ ):
125
+ """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
126
+ the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
127
+ Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
128
+ """
129
+ points = []
130
+ for f in range(0, len(depth), fstride):
131
+ height, width = depth[f].shape
132
+ ys, xs = np.mgrid[0:height:stride, 0:width:stride]
133
+ ys = ys.ravel()
134
+ xs = xs.ravel()
135
+ z = depth[f][ys, xs]
136
+ ok = (z > 0) & np.isfinite(z)
137
+ if conf is not None and conf_pct > 0:
138
+ ok &= conf[f][ys, xs] >= np.percentile(conf[f], conf_pct)
139
+ ys, xs, z = ys[ok], xs[ok], z[ok]
140
+ if not len(z):
141
+ continue
142
+ intrinsics = intr[f]
143
+ camera_points = np.stack(
144
+ [
145
+ (xs - intrinsics[0, 2]) * z / intrinsics[0, 0],
146
+ (ys - intrinsics[1, 2]) * z / intrinsics[1, 1],
147
+ z,
148
+ ],
149
+ 1,
150
+ )
151
+ points.append((c2w[f][:3, :3] @ camera_points.T).T + c2w[f][:3, 3])
152
+ points = np.concatenate(points).astype(np.float64) if points else np.zeros((0, 3))
153
+ cam = c2w[:, :3, 3].mean(0)
154
+ if len(points) < 100: # fallback to axis-extent
155
+ ext = (
156
+ np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
157
+ if len(points)
158
+ else np.ones(3)
159
+ )
160
+ ax = int(np.argmin(ext))
161
+ g = np.zeros(3)
162
+ g[ax] = 1.0
163
+ return g, ax
164
+ rng = np.random.RandomState(0)
165
+ best = None
166
+ best_score = -1
167
+ for _ in range(iters):
168
+ a, b, c = points[rng.choice(len(points), 3, False)]
169
+ nrm = np.cross(b - a, c - a)
170
+ ln = np.linalg.norm(nrm)
171
+ if ln < 1e-6:
172
+ continue
173
+ nrm /= ln
174
+ d = -nrm @ a
175
+ side = points @ nrm + d
176
+ ninl = int((np.abs(side) < thr).sum())
177
+ if ninl < 50:
178
+ continue
179
+ score = ninl * max(
180
+ np.mean(side > thr), np.mean(side < -thr)
181
+ ) # big + one-sided = floor
182
+ if score > best_score:
183
+ best_score = score
184
+ best = (nrm, d)
185
+ if best is None:
186
+ ext = np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
187
+ ax = int(np.argmin(ext))
188
+ g = np.zeros(3)
189
+ g[ax] = 1.0
190
+ return g, ax
191
+ nrm, d = best
192
+ if (cam @ nrm + d) < 0:
193
+ nrm = -nrm # orient toward cameras (up)
194
+ return nrm.astype(np.float32), int(np.argmax(np.abs(nrm)))
195
+
196
+
197
+ def pos3(rec):
198
+ """Read either legacy numeric or current unit-string position formatting."""
199
+ p = rec.get("position") or {}
200
+
201
+ def meters(current, legacy):
202
+ value = p.get(current, p.get(legacy, 0.0))
203
+ if isinstance(value, str):
204
+ if value.endswith(" meters"):
205
+ value = value[: -len(" meters")]
206
+ value = value.strip()
207
+ return float(value)
208
+
209
+ return [
210
+ meters("x coordinate", "floor_x_meters"),
211
+ meters("y coordinate", "floor_y_meters"),
212
+ meters("height above floor", "height_above_floor_meters"),
213
+ ]
214
+
215
+
216
+ def _floor_basis(up_vec):
217
+ """Orthonormal floor basis (u, v horizontal; g = up) from the gravity vector. u is the OLD
218
+ floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
219
+ differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
220
+ rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
221
+ all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
222
+ """
223
+ g = np.asarray(up_vec, np.float64)
224
+ g = g / (np.linalg.norm(g) + 1e-12)
225
+ up_ax = int(np.argmax(np.abs(g)))
226
+ floor_axes = [
227
+ a for a in range(3) if a != up_ax
228
+ ] # the two world axes the old frame used
229
+ e0 = np.zeros(3)
230
+ e0[floor_axes[0]] = 1.0 # old floor_x world axis
231
+ u = e0 - (e0 @ g) * g
232
+ u = u / (np.linalg.norm(u) + 1e-12) # project it into the gravity plane
233
+ v = np.cross(g, u)
234
+ if v[floor_axes[1]] < 0:
235
+ v = -v # keep floor_y sign aligned with the old axis
236
+ return u, v, g
237
+
238
+
239
+ def _floor_level(points, gravity, v2=None):
240
+ """Reference floor estimator shared by every model representation.
241
+
242
+ The supplied geometry uses the densest gravity-height slab for its reproducible v1
243
+ behavior and the robust second percentile for v2. Keep that switch here, after model
244
+ adapters have produced world points, so it cannot become model-specific.
245
+ """
246
+ heights = np.asarray(points, np.float64) @ np.asarray(gravity, np.float64)
247
+ heights = heights[np.isfinite(heights)]
248
+ if not len(heights):
249
+ return 0.0
250
+ if v2 is None:
251
+ v2 = os.environ.get("VSI_CODE_V2") == "1"
252
+ if v2:
253
+ return float(np.percentile(heights, 2))
254
+ counts, edges = np.histogram(heights, bins=80)
255
+ index = int(counts.argmax())
256
+ return float(0.5 * (edges[index] + edges[index + 1]))
257
+
258
+
259
+ # ==========================================================================================
260
+ # DETERMINISTIC ANSWER LAYER (parameter-free; validated on VSI GT). Reads the in-memory
261
+ # instances (pos for direction/route, point clouds for distance). Merged in from
262
+ # perceptual.py, verbatim.
263
+ # ==========================================================================================
264
+
265
+
266
+ def _find_cls(name, classes):
267
+ """Mirrors symbolic/solver.py's _find_class exactly (see its docstring): word-TOKEN
268
+ subset, not raw character substring -- "washer" must not match "dishwasher" just
269
+ because the characters appear inside it (2026-07-26 fix, found via the citation-
270
+ fidelity audit)."""
271
+ name = name.strip().lower()
272
+ for c in classes:
273
+ if c == name or c.replace(" ", "") == name.replace(" ", ""):
274
+ return c
275
+ name_tokens = set(name.split())
276
+ for c in classes:
277
+ class_tokens = set(c.split())
278
+ if (
279
+ name_tokens
280
+ and class_tokens
281
+ and (name_tokens <= class_tokens or class_tokens <= name_tokens)
282
+ ):
283
+ return c
284
+ return None
285
+
286
+
287
+ def _rep(insts):
288
+ """representative instance = most observed points (best-segmented, validated 8/8 on direction)."""
289
+ return max(insts, key=lambda i: i["n"])
290
+
291
+
292
+ def answer_rel_direction(point_a, point_b, point_c, up_vec, up_ax, mode="hard"):
293
+ """Standing at A facing B, where is C? front/back=dot(C-A,fwd); left/right=dot(C-A, up x fwd).
294
+ Right-handed world (OpenCV cam frame + det+1 c2w) makes up x fwd = left a fixed identity.
295
+ Projection uses the gravity VECTOR (v-(v.g)g), so a tilted floor (ScanNet++) is handled; for an
296
+ axis-aligned up this reduces to zeroing that axis (ARKit unchanged)."""
297
+ g = np.asarray(up_vec, np.float64)
298
+ g = g / (np.linalg.norm(g) + 1e-12)
299
+
300
+ def fl(v):
301
+ w = v.astype(np.float64)
302
+ return w - (w @ g) * g
303
+
304
+ fwd = fl(point_b - point_a)
305
+ n = np.linalg.norm(fwd)
306
+ if n < 1e-6:
307
+ return None
308
+ fwd /= n
309
+ left = np.cross(g, fwd)
310
+ left /= np.linalg.norm(left) + 1e-9
311
+ d = fl(point_c - point_a)
312
+ f = float(d @ fwd)
313
+ lateral = float(d @ left)
314
+ if mode == "medium":
315
+ if abs(np.degrees(np.arctan2(lateral, f))) >= 135:
316
+ return "back"
317
+ return "left" if lateral > 0 else "right"
318
+ return f"{'front' if f > 0 else 'back'}-{'left' if lateral > 0 else 'right'}"
319
+
320
+
321
+ def _classify_turn(h_in, h_out, up_vec, up_ax):
322
+ """rotation h_in->h_out in floor plane -> turn left/right/back (135deg = VSI's own 'back' cutoff)."""
323
+ g = np.asarray(up_vec, np.float64)
324
+ g = g / (np.linalg.norm(g) + 1e-12)
325
+
326
+ def fl(v):
327
+ w = v.astype(np.float64)
328
+ return w - (w @ g) * g
329
+
330
+ a, b = fl(h_in), fl(h_out)
331
+ na, nb = np.linalg.norm(a), np.linalg.norm(b)
332
+ if na < 1e-6 or nb < 1e-6:
333
+ return None
334
+ a /= na
335
+ b /= nb
336
+ ang = np.degrees(np.arctan2(float(up_vec @ np.cross(a, b)), float(a @ b)))
337
+ if abs(ang) >= 135:
338
+ return "turn back"
339
+ return "turn left" if ang > 0 else "turn right"
340
+
341
+
342
+ def answer_route(ql, cents, up_vec, up_ax):
343
+ """Chain the turn primitive over the waypoint sequence -> ordered ['turn left/right/back', ...]."""
344
+ import re as _re
345
+
346
+ m = _re.search(r"beginning at the (.+?) (?:and )?facing the (.+?)\.", ql)
347
+ if not m:
348
+ return None
349
+
350
+ def position(name):
351
+ class_name = _find_cls(name, cents)
352
+ return cents[class_name] if class_name else None
353
+
354
+ steps_txt = ql.split(":", 1)[1] if ":" in ql else ql
355
+ steps = _re.findall(
356
+ r"\d+\.\s*(\[please fill in\]|Go forward until the [^0-9\[]+?)(?=\s*\d+\.|$)",
357
+ steps_txt,
358
+ )
359
+ cur_pos = position(m.group(1).strip())
360
+ if cur_pos is None:
361
+ return None
362
+ fac = position(m.group(2).strip())
363
+ cur_head = (fac - cur_pos) if fac is not None else None
364
+ turns = []
365
+ i = 0
366
+ while i < len(steps):
367
+ s = steps[i].strip()
368
+ if s.startswith("Go forward"):
369
+ tp = position(_re.sub(r"^Go forward until the ", "", s).strip().rstrip("."))
370
+ if tp is not None:
371
+ cur_head = tp - cur_pos
372
+ cur_pos = tp
373
+ else:
374
+ nxt = next(
375
+ (
376
+ _re.sub(r"^Go forward until the ", "", steps[j].strip())
377
+ .strip()
378
+ .rstrip(".")
379
+ for j in range(i + 1, len(steps))
380
+ if steps[j].strip().startswith("Go forward")
381
+ ),
382
+ None,
383
+ )
384
+ tp = position(nxt) if nxt else None
385
+ if tp is None or cur_head is None:
386
+ turns.append(None)
387
+ else:
388
+ turns.append(_classify_turn(cur_head, tp - cur_pos, up_vec, up_ax))
389
+ cur_head = tp - cur_pos
390
+ i += 1
391
+ return turns
392
+
393
+
394
+ # ==========================================================================================
395
+ # POINT-CLOUD CLEANING + DISTANCE ANSWERS -- outlier removal, closest-distance queries. Merged
396
+ # in from perceptual.py, verbatim.
397
+ # ==========================================================================================
398
+
399
+
400
+ def _sor(pts, k=16, std=2.0, cap=4000):
401
+ """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
402
+ mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
403
+ k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
404
+ """
405
+ from scipy.spatial import cKDTree
406
+
407
+ if len(pts) < k + 2:
408
+ return pts
409
+ rs = np.random.RandomState(0)
410
+ points = pts if len(pts) <= cap else pts[rs.choice(len(pts), cap, False)]
411
+ d, _ = cKDTree(points).query(points, k=k + 1, workers=KD_WORKERS)
412
+ md = d[:, 1:].mean(1)
413
+ return points[md <= md.mean() + std * md.std()]
414
+
415
+
416
+ def _main_cluster(pts):
417
+ """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
418
+ object forms a disconnected component (a gap separates two objects); the true object is the largest one.
419
+ Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
420
+ """
421
+ from scipy.spatial import cKDTree
422
+
423
+ if len(pts) < 30:
424
+ return pts
425
+ tree = cKDTree(pts)
426
+ nn, _ = tree.query(pts, k=2)
427
+ eps = 3.0 * float(np.median(nn[:, 1])) # 3x median NN gap (data-derived)
428
+ pairs = tree.query_pairs(eps, output_type="ndarray")
429
+ if len(pairs) == 0:
430
+ return pts
431
+ parent = np.arange(len(pts))
432
+
433
+ def find(x):
434
+ r = x
435
+ while parent[r] != r:
436
+ r = parent[r]
437
+ while parent[x] != r:
438
+ parent[x], x = r, parent[x]
439
+ return r
440
+
441
+ for a, b in pairs:
442
+ ra, rb = find(int(a)), find(int(b))
443
+ if ra != rb:
444
+ parent[ra] = rb
445
+ roots = np.array([find(i) for i in range(len(pts))])
446
+ v, cnt = np.unique(roots, return_counts=True)
447
+ return pts[roots == v[cnt.argmax()]]
448
+
449
+
450
+ def _clean(inst, cap=4000):
451
+ """Outlier removal self-calibrated from the pipeline's OWN per-object signals -- no universal constant,
452
+ no benchmark knob. Cached on the instance so the O(classes^2) distance table cleans each object once.
453
+ (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
454
+ object's OWN median confidence (data-derived cut);
455
+ (2) statistical density outlier removal on the survivors;
456
+ (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
457
+ """
458
+ if inst.get("_cleanpts") is not None:
459
+ return inst["_cleanpts"]
460
+ pts = inst["pts"]
461
+ conf = inst.get("conf")
462
+ rs = np.random.RandomState(0)
463
+ if len(pts) > cap:
464
+ idx = rs.choice(len(pts), cap, False)
465
+ pts = pts[idx]
466
+ conf = conf[idx] if conf is not None else None
467
+ if conf is not None and len(conf) > 20: # self-calibrating: object's OWN median
468
+ keep = conf >= np.median(conf)
469
+ if keep.sum() >= 10:
470
+ pts = pts[keep]
471
+ pts = _sor(pts, cap=cap) # density outlier removal on the survivors
472
+ # NOTE: spatial de-bleeding (_main_cluster) was tried and REVERTED -- "largest cluster = the object" is
473
+ # not guaranteed; when an object's near edge splits off it drops the true closest part (overshoot). You
474
+ # cannot post-hoc recover the true object from a bleeding mask in 3D -- that needs better SOURCE masks.
475
+ inst["_cleanpts"] = pts
476
+ return pts
477
+
478
+
479
+ def answer_closest_distance(instances_a, instances_b, k=4000):
480
+ """Closest distance between the two objects' point clouds ('closest point of each object'). Points are
481
+ cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
482
+ KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
483
+ boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
484
+ """
485
+ points_a = _clean(_rep(instances_a), cap=k)
486
+ points_b = _clean(_rep(instances_b), cap=k)
487
+ if len(points_a) == 0 or len(points_b) == 0:
488
+ return float("inf")
489
+ from scipy.spatial import cKDTree
490
+
491
+ if len(points_a) <= len(points_b):
492
+ d, _ = cKDTree(points_a).query(points_b, k=1, workers=KD_WORKERS)
493
+ else:
494
+ d, _ = cKDTree(points_b).query(points_a, k=1, workers=KD_WORKERS)
495
+ return float(d.min())
496
+
497
+
498
+ # ==========================================================================================
499
+ # MASK/DEPTH CLEANUP + BACK-PROJECTION -- per-frame refinement before points enter an
500
+ # instance's point cloud. Merged in from perceptual.py, verbatim.
501
+ # ==========================================================================================
502
+
503
+
504
+ def depth_edges(depth_f, valid_f):
505
+ """Per-frame depth-DISCONTINUITY map: gradient magnitude above median + 3*MAD over the valid pixels.
506
+ The threshold is data-derived (robust, universal statistical cut -- NOT benchmark-tuned). These edges are
507
+ where mask-bleed crosses onto an adjacent object at a different depth."""
508
+ if valid_f.sum() < 100:
509
+ return np.zeros_like(depth_f, bool)
510
+ d = np.where(valid_f, depth_f, np.median(depth_f[valid_f]))
511
+ gy, gx = np.gradient(d)
512
+ grad = np.hypot(gx, gy)
513
+ g = grad[valid_f]
514
+ med = np.median(g)
515
+ mad = np.median(np.abs(g - med)) + 1e-9
516
+ return (grad > med + 3.0 * 1.4826 * mad) & valid_f
517
+
518
+
519
+ try:
520
+ _GUIDED = (
521
+ cv2.ximgproc.guidedFilter
522
+ ) # opencv-contrib; appearance-guided boundary snap
523
+ except AttributeError:
524
+ _GUIDED = None
525
+
526
+
527
+ def refine_mask(mask, rgb):
528
+ """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
529
+ bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
530
+ cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
531
+ variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
532
+ """
533
+ if mask.shape[:2] != rgb.shape[:2]:
534
+ mask = cv2.resize(
535
+ mask.astype(np.uint8),
536
+ (rgb.shape[1], rgb.shape[0]),
537
+ interpolation=cv2.INTER_NEAREST,
538
+ ).astype(bool)
539
+ a = int(mask.sum())
540
+ if a < 60: # too small to refine meaningfully -> 1px erode as before
541
+ me = cv2.erode(mask.astype(np.uint8), np.ones((3, 3), np.uint8), 1).astype(bool)
542
+ return me if me.any() else mask
543
+ if _GUIDED is not None:
544
+ r = max(
545
+ 4, int(round(0.02 * float(np.hypot(*mask.shape[:2]))))
546
+ ) # radius ~2% of frame diagonal
547
+ eps = (
548
+ float(np.var(rgb.astype(np.float32) / 255.0)) * 0.01 + 1e-6
549
+ ) # smoothness ~ image color variance
550
+ soft = _GUIDED(rgb, mask.astype(np.float32), r, eps)
551
+ out = soft > 0.5
552
+ return out if out.sum() >= 0.4 * a else mask # majority guard: don't over-carve
553
+ # fallback (base opencv, no ximgproc): grabCut seeded FG=mask, PR_FG=dilated ring, BG=far exterior
554
+ try:
555
+ gc = np.full(mask.shape[:2], cv2.GC_PR_BGD, np.uint8)
556
+ dil = cv2.dilate(mask.astype(np.uint8), np.ones((15, 15), np.uint8), 1).astype(
557
+ bool
558
+ )
559
+ er = cv2.erode(mask.astype(np.uint8), np.ones((5, 5), np.uint8), 1).astype(bool)
560
+ gc[dil] = cv2.GC_PR_FGD
561
+ gc[er] = cv2.GC_FGD
562
+ bgm = np.zeros((1, 65), np.float64)
563
+ fgm = np.zeros((1, 65), np.float64)
564
+ cv2.grabCut(rgb, gc, None, bgm, fgm, 3, cv2.GC_INIT_WITH_MASK)
565
+ out = (gc == cv2.GC_FGD) | (gc == cv2.GC_PR_FGD)
566
+ return out if 0.4 * a <= out.sum() <= 1.5 * a else mask
567
+ except Exception:
568
+ me = cv2.erode(mask.astype(np.uint8), np.ones((3, 3), np.uint8), 1).astype(bool)
569
+ return me if me.any() else mask
570
+
571
+
572
+ def backproject_frame(
573
+ depth_f,
574
+ intrinsics,
575
+ c2w_f,
576
+ mask_f,
577
+ conf_f=None,
578
+ conf_thr=0.0,
579
+ valid_f=None,
580
+ return_conf=False,
581
+ edges_f=None,
582
+ ):
583
+ """Return (M,3) world points for the masked pixels of one frame (c2w_f = cam->world 4x4).
584
+ valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
585
+ return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
586
+ edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
587
+ (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
588
+ """
589
+ height, width = depth_f.shape
590
+ empty = (
591
+ (np.empty((0, 3), np.float32), np.empty((0,), np.float32))
592
+ if return_conf
593
+ else np.empty((0, 3), np.float32)
594
+ )
595
+ if mask_f.shape != (height, width):
596
+ mask_f = cv2.resize(
597
+ mask_f.astype(np.uint8), (width, height), interpolation=cv2.INTER_NEAREST
598
+ ).astype(bool)
599
+ if valid_f is None:
600
+ valid_f = np.isfinite(depth_f) & (depth_f > 0)
601
+ m = mask_f & valid_f
602
+ if conf_f is not None and conf_thr > 0:
603
+ m &= conf_f >= conf_thr
604
+ if (
605
+ edges_f is not None and m.sum() >= 30
606
+ ): # keep the largest depth-coherent piece of the mask
607
+ from scipy import ndimage
608
+
609
+ lab, nlab = ndimage.label(m & ~edges_f)
610
+ if nlab >= 1:
611
+ sizes = np.bincount(lab.ravel())
612
+ sizes[0] = 0
613
+ big = int(sizes.argmax())
614
+ if (
615
+ sizes[big] >= 0.5 * m.sum()
616
+ ): # object is the MAJORITY piece (bleed is a minority)
617
+ m = lab == big
618
+ if not m.any():
619
+ return empty
620
+ ys, xs = np.nonzero(m)
621
+ z = depth_f[ys, xs]
622
+ if DEPTH_COHERENCE and len(z) >= 8:
623
+ # an object is a coherent depth surface; floor/background BLEED pixels are depth outliers.
624
+ # Drop them via the standard Tukey fence (1.5*IQR) on the masked region's depths -- parameter-free.
625
+ q1, q3 = np.percentile(z, [25, 75])
626
+ iqr = q3 - q1
627
+ keep = (z >= q1 - 1.5 * iqr) & (z <= q3 + 1.5 * iqr)
628
+ if keep.sum() >= 1:
629
+ ys, xs, z = ys[keep], xs[keep], z[keep]
630
+ fx, fy, cx, cy = (
631
+ intrinsics[0, 0],
632
+ intrinsics[1, 1],
633
+ intrinsics[0, 2],
634
+ intrinsics[1, 2],
635
+ )
636
+ camera_points = np.stack(
637
+ [(xs - cx) * z / fx, (ys - cy) * z / fy, z], axis=1
638
+ ) # camera coords
639
+ world_points = (c2w_f[:3, :3] @ camera_points.T).T + c2w_f[:3, 3] # -> world
640
+ if return_conf:
641
+ cw = (
642
+ conf_f[ys, xs].astype(np.float32)
643
+ if conf_f is not None
644
+ else np.ones(len(ys), np.float32)
645
+ )
646
+ return world_points.astype(np.float32), cw
647
+ return world_points.astype(np.float32)
648
+
649
+
650
+ # ==========================================================================================
651
+ # INSTANCE BUILDING -- oriented extent, 3D box-overlap re-identification, and the main
652
+ # build_instances() driver that turns per-frame masks into per-class 3D instances. Merged in
653
+ # from perceptual.py, verbatim.
654
+ # ==========================================================================================
655
+
656
+
657
+ def robust_centroid_extent(pts, up_axis=None):
658
+ """median centroid + ORIENTED robust extent.
659
+ If up_axis is given: YAW-ONLY oriented extent -- rotation is found by 2D PCA on the
660
+ floor-projected points only, with the up axis left untouched. This matches VSI-Bench's
661
+ own annotation convention for indoor scans (ScanNet/ARKitScenes OrientedBoundingBox
662
+ objects follow a Manhattan-world assumption: rotated only around the vertical axis,
663
+ never tilted). Unconstrained 3D PCA (the previous behavior) can chase noise on the
664
+ vertical axis for flat/elongated objects and drift away from the true yaw.
665
+ If up_axis is None (unknown at the call site): falls back to unconstrained 3D PCA.
666
+ Either way: parameter-free, rotation-invariant in-plane, p2..p98 robust extent."""
667
+ c = np.median(pts, axis=0)
668
+ centered = pts - c
669
+ if len(centered) > 5000: # PCA on a sample (deterministic)
670
+ centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
671
+ if up_axis is not None:
672
+ floor_axes = [i for i in range(3) if i != up_axis]
673
+ floor_points = centered[:, floor_axes]
674
+ try:
675
+ _, _, floor_rotation = np.linalg.svd(
676
+ floor_points - floor_points.mean(0), full_matrices=False
677
+ )
678
+ proj_floor = (
679
+ floor_points @ floor_rotation.T
680
+ ) # (N,2) along the object's own floor-plane axes
681
+ except np.linalg.LinAlgError:
682
+ proj_floor = floor_points
683
+ up_col = centered[:, up_axis : up_axis + 1] # up axis untouched (yaw-only)
684
+ proj = np.concatenate([proj_floor, up_col], axis=1)
685
+ else:
686
+ try:
687
+ _, _, rotation = np.linalg.svd(
688
+ centered - centered.mean(0), full_matrices=False
689
+ )
690
+ proj = centered @ rotation.T # coordinates along principal axes
691
+ except np.linalg.LinAlgError:
692
+ proj = centered
693
+ lo = np.percentile(proj, 2, axis=0)
694
+ hi = np.percentile(proj, 98, axis=0)
695
+ ext = np.maximum(hi - lo, 0.0)
696
+ dims = np.sort(ext)[::-1] # the object's 3 oriented side lengths, longest first
697
+ return c.astype(np.float32), float(dims[0]), dims
698
+
699
+
700
+ def _aabb(pts):
701
+ """robust (p2..p98) axis-aligned 3D box of an instance's world points."""
702
+ return np.percentile(pts, 2, axis=0), np.percentile(pts, 98, axis=0)
703
+
704
+
705
+ def merge_by_box_overlap(insts, up_axis=None):
706
+ """Parameter-free 3D re-identification, with a temporal-exclusion gate.
707
+
708
+ SAM3 (a 2D tracker) emits a NEW masklet each time the camera revisits an object, so one
709
+ physical object -> several masklets at the same 3D location. We fuse two same-class masklets
710
+ iff BOTH:
711
+ (a) their measured 3D boxes overlap (or one centroid is inside the other) -- same volume, and
712
+ (b) they NEVER appear in the same frame -- temporal exclusion.
713
+ (b) is the key parameter-free invariant: two masklets co-visible in one frame were tracked by
714
+ SAM3 as distinct objects in that frame, so they ARE distinct (e.g. two chairs around a table);
715
+ we must never merge them, even if depth noise makes their boxes overlap. A revisit-duplicate,
716
+ by contrast, lives in DISJOINT frames. Both tests are exact/measured -- NO tuned threshold.
717
+ """
718
+ n = len(insts)
719
+ if n <= 1:
720
+ return insts
721
+ # Precompute the FULL pairwise box-match as one vectorized boolean matrix. With the per-frame
722
+ # batched detector a class can have 100+ raw instances; the old O(n^3) loop called np.all-based
723
+ # box_match millions of times. Here every pairwise test is one broadcast -> O(1) lookups below.
724
+ lo = np.stack([_aabb(i["pts"])[0] for i in insts]).astype(np.float32) # (n,3)
725
+ hi = np.stack([_aabb(i["pts"])[1] for i in insts]).astype(np.float32) # (n,3)
726
+ cents = np.stack([i["centroid"] for i in insts]).astype(np.float32) # (n,3)
727
+ overlap = (hi[:, None, :] >= lo[None, :, :]).all(-1) & (
728
+ hi[None, :, :] >= lo[:, None, :]
729
+ ).all(-1)
730
+ ins = (cents[:, None, :] >= lo[None, :, :]).all(-1) & (
731
+ cents[:, None, :] <= hi[None, :, :]
732
+ ).all(-1)
733
+ match = (
734
+ overlap | ins | ins.T
735
+ ) # box_match[i,j]: same 3D volume (identical semantics to old code)
736
+ # group-level agglomeration: merge two groups only if their COMBINED frame sets are disjoint
737
+ # (so no two co-visible masklets ever land in one object) AND some cross-pair shares a 3D volume.
738
+ groups = [
739
+ {"members": [i], "frames": set(insts[i].get("frames", set()))} for i in range(n)
740
+ ]
741
+ changed = True
742
+ while changed:
743
+ changed = False
744
+ for a in range(len(groups)):
745
+ for b in range(a + 1, len(groups)):
746
+ if (
747
+ groups[a]["frames"] & groups[b]["frames"]
748
+ ): # co-visible -> distinct objects
749
+ continue
750
+ if match[np.ix_(groups[a]["members"], groups[b]["members"])].any():
751
+ groups[a]["members"] += groups[b]["members"]
752
+ groups[a]["frames"] |= groups[b]["frames"]
753
+ groups.pop(b)
754
+ changed = True
755
+ break
756
+ if changed:
757
+ break
758
+ merged = []
759
+ for g in groups:
760
+ idxs = g["members"]
761
+ pts = np.concatenate([insts[k]["pts"] for k in idxs], 0)
762
+ cpts = np.concatenate(
763
+ [
764
+ insts[k].get("conf", np.ones(len(insts[k]["pts"]), np.float32))
765
+ for k in idxs
766
+ ],
767
+ 0,
768
+ )
769
+ best = max(
770
+ (insts[k]["best_pts"] for k in idxs), key=len
771
+ ) # largest single obs in the group
772
+ c, longest, dims = robust_centroid_extent(
773
+ best, up_axis
774
+ ) # size+pos+3 oriented dims from best view (#2/#4)
775
+ merged.append(
776
+ {
777
+ "centroid": c,
778
+ "size": longest,
779
+ "dims": dims,
780
+ "first_time": min(insts[k]["first_time"] for k in idxs),
781
+ "pts": pts,
782
+ "conf": cpts,
783
+ "best_pts": best,
784
+ "observations": [
785
+ observation
786
+ for k in idxs
787
+ for observation in insts[k].get("observations", [insts[k]["pts"]])
788
+ ],
789
+ "frames": g["frames"],
790
+ "n": sum(insts[k]["n"] for k in idxs),
791
+ "nframes": len(g["frames"]),
792
+ "oids": [oid for k in idxs for oid in insts[k].get("oids", [])],
793
+ }
794
+ ) # track persistence (evidence strength)
795
+ return merged
796
+
797
+
798
+ def build_instances(
799
+ per_class, depth, intr, c2w, conf, frame_times, frame_paths=None, up_axis=None
800
+ ):
801
+ """-> {class: [ {centroid(3), size(longest dim), first_time, npts} ]}
802
+ up_axis: if known (from room_gravity, computed BEFORE this call), threads through to
803
+ robust_centroid_extent for yaw-only oriented sizing. If None, size falls back to
804
+ unconstrained 3D PCA."""
805
+ out = {}
806
+ stats = {}
807
+ nframes = len(depth)
808
+ # precompute each frame's valid-depth mask ONCE (was recomputed per mask -> per class).
809
+ valid = {}
810
+ edges = {}
811
+ rgb = {}
812
+ used_frames = {fi for frames in per_class.values() for fi in frames if fi < nframes}
813
+ for fi in used_frames:
814
+ valid[fi] = np.isfinite(depth[fi]) & (depth[fi] > 0)
815
+ edges[fi] = depth_edges(depth[fi], valid[fi]) if DEPTH_EDGE_REFINE else None
816
+ if MASK_REFINE and frame_paths and fi < len(frame_paths):
817
+ im = cv2.imread(frame_paths[fi]) # BGR; guidedFilter/grabCut want 3ch uint8
818
+ rgb[fi] = (
819
+ cv2.resize(im, (depth[fi].shape[1], depth[fi].shape[0]))
820
+ if im is not None
821
+ else None
822
+ )
823
+ for cls, frames in per_class.items():
824
+ # peak co-visibility: max distinct masklets SAM3 tracks SIMULTANEOUSLY in any one frame.
825
+ # geometry-free, parameter-free, immune to revisit over-count; provable lower bound on count.
826
+ peak = max((len(objs) for objs in frames.values()), default=0)
827
+ # gather world points + first-seen time + frame set per obj_id (SAM3 track id = masklet)
828
+ pts_by_id, conf_by_id, first_t, frames_by_id = {}, {}, {}, {}
829
+ # px_by_id: (fidx, frame_time, mask_pixel_count) per obj_id, for appearance-order timing.
830
+ # VSI-Bench's own GT defines "first appearance" as the timestamp where an object's pixel
831
+ # count crosses a threshold (paper appendix B.1) -- NOT the first frame with any pixel at
832
+ # all. A single stray mask-bleed/false-positive pixel would otherwise register as "first
833
+ # seen" far too early. The threshold is self-calibrated per instance (that instance's OWN
834
+ # median observed pixel count across its frames), same convention as _clean's median cut.
835
+ px_by_id = {}
836
+ for fidx, objs in frames.items():
837
+ if fidx >= nframes: # guard: SAM3 frame idx vs DA3 frames
838
+ continue
839
+ for oid, mask in objs.items():
840
+ if MASK_REFINE and rgb.get(fidx) is not None:
841
+ me = (
842
+ mask
843
+ if os.environ.get("VSI_NO_REFINE") == "1"
844
+ else refine_mask(mask, rgb[fidx])
845
+ ) # appearance-guided boundary snap (clips same-depth bleed)
846
+ else:
847
+ # erode 1px to drop mask-edge / background depth bleed
848
+ me = cv2.erode(
849
+ mask.astype(np.uint8), np.ones((3, 3), np.uint8), 1
850
+ ).astype(bool)
851
+ if not me.any():
852
+ me = mask
853
+ conf_f = conf[fidx] if conf is not None else None
854
+ conf_thr = (
855
+ np.percentile(conf_f, CONF_PCT)
856
+ if (conf_f is not None and CONF_PCT > 0)
857
+ else 0.0
858
+ )
859
+ world_points, cw = backproject_frame(
860
+ depth[fidx],
861
+ intr[fidx],
862
+ c2w[fidx],
863
+ me,
864
+ conf_f,
865
+ conf_thr=conf_thr,
866
+ valid_f=valid.get(fidx),
867
+ return_conf=True,
868
+ edges_f=edges.get(fidx),
869
+ )
870
+ if len(world_points):
871
+ pts_by_id.setdefault(oid, []).append(world_points)
872
+ conf_by_id.setdefault(oid, []).append(
873
+ cw
874
+ ) # per-point DA3 confidence (for _clean)
875
+ frames_by_id.setdefault(oid, set()).add(
876
+ fidx
877
+ ) # for co-occurrence gate
878
+ t = frame_times[fidx]
879
+ px_by_id.setdefault(oid, []).append((fidx, t, int(me.sum())))
880
+ # appearance_order timing: per instance, first frame at/above its OWN median pixel count
881
+ for oid, obs in px_by_id.items():
882
+ counts = [c for _, _, c in obs]
883
+ thresh = float(np.median(counts))
884
+ crossing = [t for _, t, c in obs if c >= thresh]
885
+ first_t[oid] = min(crossing) if crossing else min(t for _, t, c in obs)
886
+ insts = []
887
+ for oid, plist in pts_by_id.items():
888
+ pts = np.concatenate(plist, 0)
889
+ cpts = np.concatenate(conf_by_id[oid], 0)
890
+ if len(pts) < MIN_INSTANCE_PTS:
891
+ continue
892
+ best = max(
893
+ plist, key=len
894
+ ) # #2/#4: largest single-frame observation (closest/most pixels)
895
+ bc, bsize, bdims = robust_centroid_extent(
896
+ best, up_axis
897
+ ) # size + position + 3 oriented dims from best view
898
+ insts.append(
899
+ {
900
+ "centroid": bc,
901
+ "size": bsize,
902
+ "dims": bdims,
903
+ "first_time": first_t[oid],
904
+ "pts": pts,
905
+ "conf": cpts,
906
+ "best_pts": best,
907
+ "observations": list(plist),
908
+ "n": len(pts),
909
+ "frames": frames_by_id[oid],
910
+ # Raw SAM3 masklet id this fragment came from -- carried through every
911
+ # later merge/consolidation step (never emitted in the JSON schema) so
912
+ # a strong-correspondence overlay can draw SAM3's OWN per-frame
913
+ # box/mask for a code instance instead of re-deriving one via 3D
914
+ # projection. See encoder.geometric.instance_source_track_ids.
915
+ "oids": [int(oid)],
916
+ }
917
+ )
918
+ raw = len(insts)
919
+ # 3D re-ID: fuse same-class masklets that occupy the same measured 3D volume (parameter-free).
920
+ insts = merge_by_box_overlap(insts, up_axis)
921
+ if insts:
922
+ out[cls] = insts
923
+ stats[cls] = {"raw": raw, "merged": len(insts), "peak": peak}
924
+ return out, stats
925
+
926
+
927
+ # ==========================================================================================
928
+ # PER-CLASS SUMMARY -- legacy array-schema row builder. Merged in from perceptual.py, verbatim.
929
+ # (The room-scale floor area calculation that used to live here is gone -- the explicit
930
+ # schema's floor area is now a direct derivation of the compact schema's floor boundary
931
+ # polygons; see build_explicit_spatial_code() near build_compact_spatial_code().)
932
+ # ==========================================================================================
933
+
934
+
935
+ # ---- Per-class spatial code (legacy array-schema row) -------------------------------------
936
+ def class_spatial_code(insts, peak=0):
937
+ cents = np.stack([i["centroid"] for i in insts], 0) # (n,3)
938
+ sizes = np.array([i["size"] for i in insts], np.float32)
939
+ n = len(insts) # merged centroids (for spatial stats)
940
+ count = peak if peak else n # reported count = peak co-visibility
941
+ x, y, z = cents.mean(0)
942
+ if n == 1:
943
+ e1 = e2 = e3 = px = pz = 0.0
944
+ size_iqr = 0.0
945
+ else:
946
+ cov = np.cov(cents.T) # 3x3
947
+ vals, vecs = np.linalg.eigh(cov) # ascending
948
+ order = np.argsort(vals)[::-1]
949
+ vals = np.clip(vals[order], 0, None)
950
+ vecs = vecs[:, order]
951
+ e1, e2, e3 = vals.tolist()
952
+ pv = vecs[:, 0] # principal eigenvector
953
+ px, pz = float(pv[0]), float(pv[2])
954
+ q1, q3 = np.percentile(sizes, [25, 75])
955
+ size_iqr = float(q3 - q1)
956
+ size_median = float(np.median(sizes))
957
+ first_time = float(min(i["first_time"] for i in insts))
958
+ row = [x, y, z, e1, e2, e3, px, pz, size_median, size_iqr, first_time, count]
959
+ row = [
960
+ (lambda r: 0.0 if r == 0 else r)(round(float(v), 1)) for v in row
961
+ ] # kill -0.0
962
+ row[-1] = int(count)
963
+ return row
964
+
965
+
966
+ def _reference_object_records(insts, count, u, v, g, floor_level):
967
+ """Object record formatter used by the original V2 spatial-code builder."""
968
+ ranked = sorted(insts, key=lambda i: (i["n"], i.get("nframes", 0)), reverse=True)[
969
+ : max(int(count), 1)
970
+ ]
971
+ recs = []
972
+ for it in ranked:
973
+ center = np.asarray(it["centroid"], np.float64)
974
+ points = np.asarray(it["pts"], np.float64)
975
+ floor_x = points @ u
976
+ floor_y = points @ v
977
+ height = points @ g - floor_level
978
+ recs.append(
979
+ {
980
+ "position": {
981
+ "floor_x_meters": round(float(center @ u), 2),
982
+ "floor_y_meters": round(float(center @ v), 2),
983
+ "height_above_floor_meters": round(
984
+ float(center @ g - floor_level), 2
985
+ ),
986
+ },
987
+ "longest_dimension_meters": round(float(it["size"]), 2),
988
+ "bounding_box": {
989
+ "floor_x_meters": [
990
+ round(float(np.percentile(floor_x, 2)), 2),
991
+ round(float(np.percentile(floor_x, 98)), 2),
992
+ ],
993
+ "floor_y_meters": [
994
+ round(float(np.percentile(floor_y, 2)), 2),
995
+ round(float(np.percentile(floor_y, 98)), 2),
996
+ ],
997
+ "height_above_floor_meters": [
998
+ round(float(np.percentile(height, 2)), 2),
999
+ round(float(np.percentile(height, 98)), 2),
1000
+ ],
1001
+ },
1002
+ "dimensions_meters": [round(float(d), 2) for d in it["dims"]],
1003
+ }
1004
+ )
1005
+ return recs
1006
+
1007
+
1008
+ def _reference_to_spatial_code(
1009
+ instances, stats, floor_area, up_axis, up_vec, floor_level
1010
+ ):
1011
+ """Per-instance spatial code shape from the original geometric V2 pipeline."""
1012
+ u, v, g = _floor_basis(up_vec)
1013
+ out = {"objects": {}}
1014
+ for class_name, insts in instances.items():
1015
+ count = int(stats[class_name]["peak"])
1016
+ out["objects"][class_name] = {
1017
+ "count": count,
1018
+ "instances": _reference_object_records(insts, count, u, v, g, floor_level),
1019
+ }
1020
+ out["room"] = {"floor_area_square_meters": floor_area}
1021
+ return out
1022
+
1023
+
1024
+ def compute_floor_area(depth, intr, c2w, conf, sky, stride=8, up_vec=None):
1025
+ """Reference floor-area computation from the original geometric pipeline."""
1026
+ points = []
1027
+ for frame_index in range(depth.shape[0]):
1028
+ height, width = depth[frame_index].shape
1029
+ rows, columns = np.mgrid[0:height:stride, 0:width:stride]
1030
+ rows = rows.ravel()
1031
+ columns = columns.ravel()
1032
+ values = depth[frame_index][rows, columns]
1033
+ keep = np.isfinite(values) & (values > 0)
1034
+ if sky is not None:
1035
+ keep &= ~sky[frame_index][rows, columns].astype(bool)
1036
+ if conf is not None:
1037
+ keep &= conf[frame_index][rows, columns] >= np.percentile(
1038
+ conf[frame_index], 40
1039
+ )
1040
+ rows, columns, values = rows[keep], columns[keep], values[keep]
1041
+ if not len(values):
1042
+ continue
1043
+ current = intr[frame_index]
1044
+ camera = np.stack(
1045
+ [
1046
+ (columns - current[0, 2]) * values / current[0, 0],
1047
+ (rows - current[1, 2]) * values / current[1, 1],
1048
+ values,
1049
+ ],
1050
+ 1,
1051
+ )
1052
+ world = (c2w[frame_index][:3, :3] @ camera.T).T + c2w[frame_index][:3, 3]
1053
+ points.append(world.astype(np.float32))
1054
+ if not points:
1055
+ return 0.0
1056
+ scene_points = np.concatenate(points, 0)
1057
+ if up_vec is not None:
1058
+ gravity = np.asarray(up_vec, np.float64)
1059
+ gravity /= np.linalg.norm(gravity) + 1e-12
1060
+ axis = (
1061
+ np.array([1.0, 0.0, 0.0])
1062
+ if abs(gravity[0]) < 0.9
1063
+ else np.array([0.0, 1.0, 0.0])
1064
+ )
1065
+ u = np.cross(gravity, axis)
1066
+ u /= np.linalg.norm(u)
1067
+ v = np.cross(gravity, u)
1068
+ floor_points = np.stack([scene_points @ u, scene_points @ v], 1)
1069
+ else:
1070
+ up_axis = int(np.argmin(scene_points.max(0) - scene_points.min(0)))
1071
+ floor_axes = [axis for axis in range(3) if axis != up_axis]
1072
+ floor_points = scene_points[:, floor_axes]
1073
+ lower = np.percentile(floor_points, 0.5, 0)
1074
+ upper = np.percentile(floor_points, 99.5, 0)
1075
+ floor_points = floor_points[
1076
+ (floor_points[:, 0] >= lower[0])
1077
+ & (floor_points[:, 0] <= upper[0])
1078
+ & (floor_points[:, 1] >= lower[1])
1079
+ & (floor_points[:, 1] <= upper[1])
1080
+ ]
1081
+ if len(floor_points) < 10:
1082
+ return 0.0
1083
+ try:
1084
+ import alphashape
1085
+
1086
+ sample = np.random.RandomState(0).choice(
1087
+ len(floor_points), min(10000, len(floor_points))
1088
+ )
1089
+ return round(
1090
+ float(alphashape.alphashape(floor_points[sample], alpha=2).area), 1
1091
+ )
1092
+ except Exception:
1093
+ from scipy import ndimage
1094
+
1095
+ resolution = 0.10
1096
+ rows = ((floor_points[:, 0] - floor_points[:, 0].min()) / resolution).astype(
1097
+ int
1098
+ )
1099
+ columns = ((floor_points[:, 1] - floor_points[:, 1].min()) / resolution).astype(
1100
+ int
1101
+ )
1102
+ grid = np.zeros((rows.max() + 3, columns.max() + 3), np.uint8)
1103
+ grid[rows + 1, columns + 1] = 1
1104
+ grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
1105
+ grid = ndimage.binary_fill_holes(grid).astype(np.uint8)
1106
+ return round(float(grid.sum()) * resolution * resolution, 1)
1107
+
1108
+
1109
+ # ---------------------------------------------------------------------------
1110
+
1111
+ # ==========================================================================================
1112
+ # SPATIAL CODE ASSEMBLY -- the top-level entry point this whole file exists for:
1113
+ # build_spatial_code() calls everything above to turn already-computed depth/pose/masks into
1114
+ # the final spatial code dict. Room outline + JSON writer. This section was already in
1115
+ # geometric.py before the perceptual.py merge; build_spatial_code() below is updated to call
1116
+ # the geometry functions above DIRECTLY (no `pl.` prefix -- they're plain local functions now
1117
+ # that everything is in one file), same logic, unchanged otherwise.
1118
+ # ==========================================================================================
1119
+
1120
+
1121
+ def _room_outline(depth, intr, c2w, conf, bu, bv):
1122
+ """(Unemitted by explicit format; compact format derives its boundary separately. This
1123
+ math is kept intact for reuse.) Room floor-boundary polygon from the SAME grid as
1124
+ compute_floor_area: floor points
1125
+ projected onto the shared gravity plane (bu, bv), 10cm grid, close 7x7, fill holes,
1126
+ largest contour, 0.2m polygon simplification. Same (bu, bv) as objects/camera, so the
1127
+ outline, object positions, and floor_area all live in one consistent frame."""
1128
+ from scipy import ndimage
1129
+
1130
+ pts, stride = [], 8
1131
+ for f in range(0, depth.shape[0], 3):
1132
+ height, width = depth[f].shape
1133
+ ys, xs = np.mgrid[0:height:stride, 0:width:stride]
1134
+ ys = ys.ravel()
1135
+ xs = xs.ravel()
1136
+ z = depth[f][ys, xs]
1137
+ ok = np.isfinite(z) & (z > 0)
1138
+ if conf is not None:
1139
+ ok &= conf[f][ys, xs] >= np.percentile(conf[f], 40)
1140
+ ys, xs, z = ys[ok], xs[ok], z[ok]
1141
+ if not len(z):
1142
+ continue
1143
+ intrinsics = intr[f]
1144
+ camera_points = np.stack(
1145
+ [
1146
+ (xs - intrinsics[0, 2]) * z / intrinsics[0, 0],
1147
+ (ys - intrinsics[1, 2]) * z / intrinsics[1, 1],
1148
+ z,
1149
+ ],
1150
+ 1,
1151
+ )
1152
+ pts.append(
1153
+ ((c2w[f][:3, :3] @ camera_points.T).T + c2w[f][:3, 3]).astype(np.float32)
1154
+ )
1155
+ if not pts:
1156
+ return []
1157
+ world_points = np.concatenate(pts, 0)
1158
+ points = np.stack(
1159
+ [world_points @ bu, world_points @ bv], 1
1160
+ ) # gravity-plane projection (same bu,bv as objects/area)
1161
+ lo = np.percentile(points, 0.5, 0)
1162
+ hi = np.percentile(points, 99.5, 0)
1163
+ points = points[
1164
+ (points[:, 0] >= lo[0])
1165
+ & (points[:, 0] <= hi[0])
1166
+ & (points[:, 1] >= lo[1])
1167
+ & (points[:, 1] <= hi[1])
1168
+ ]
1169
+ if len(points) < 10:
1170
+ return []
1171
+ res = 0.10
1172
+ x0, y0 = points[:, 0].min(), points[:, 1].min()
1173
+ ai = ((points[:, 0] - x0) / res).astype(int)
1174
+ bi = ((points[:, 1] - y0) / res).astype(int)
1175
+ grid = np.zeros((ai.max() + 3, bi.max() + 3), np.uint8)
1176
+ grid[ai + 1, bi + 1] = 1
1177
+ grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
1178
+ grid = ndimage.binary_fill_holes(grid).astype(np.uint8)
1179
+ cs, _ = cv2.findContours(grid, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
1180
+ if not cs:
1181
+ return []
1182
+ poly = cv2.approxPolyDP(max(cs, key=cv2.contourArea), 0.2 / res, True)[:, 0, :]
1183
+ # cv2 contour points are (col=bi, row=ai) -> (floor_y, floor_x)
1184
+ return [
1185
+ {
1186
+ "floor_x_meters": round(float((r - 1) * res + x0), 1),
1187
+ "floor_y_meters": round(float((c - 1) * res + y0), 1),
1188
+ }
1189
+ for c, r in poly
1190
+ ]
1191
+
1192
+
1193
+ def dump_spatial_code(code, path):
1194
+ """Save a spatial_code.json exactly like json.dump(code, f, indent=1), EXCEPT
1195
+ "appearance order" is written as one compact line instead of one line per entry -- it's a
1196
+ single ordered sequence meant to be scanned, not structured data meant to be read field by
1197
+ field like the rest of the code. Every writer of spatial_code.json should go through this
1198
+ (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
1199
+ """
1200
+ body = dict(code)
1201
+ ao = body.pop("appearance order", None)
1202
+ text = json.dumps(body, indent=1).rstrip()
1203
+ if ao is not None:
1204
+ assert text.endswith("}")
1205
+ text = text[:-1].rstrip() + ',\n "appearance order": ' + json.dumps(ao) + "\n}"
1206
+ with open(path, "w") as f:
1207
+ f.write(text)
1208
+
1209
+
1210
+ # Canonical world-space fallback used by SegVGGT and similar adapters.
1211
+ def _canonical_room_gravity(points, cameras=None, iters=300, thr=0.05):
1212
+ """Robust UP vector = normal of the RANSAC floor plane, oriented toward the cameras."""
1213
+ points = np.asarray(points, np.float64)
1214
+ points = points[np.isfinite(points).all(1)]
1215
+ if len(points) > 100000:
1216
+ points = points[np.random.RandomState(0).choice(len(points), 100000, False)]
1217
+ cam = (
1218
+ np.asarray(cameras, np.float64).mean(0)
1219
+ if cameras is not None and len(cameras)
1220
+ else None
1221
+ )
1222
+ if len(points) < 100:
1223
+ ext = (
1224
+ np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
1225
+ if len(points)
1226
+ else np.ones(3)
1227
+ )
1228
+ ax = int(np.argmin(ext))
1229
+ g = np.zeros(3)
1230
+ g[ax] = 1.0
1231
+ return (g, ax)
1232
+ rng = np.random.RandomState(0)
1233
+ best = None
1234
+ best_score = -1
1235
+ for _ in range(iters):
1236
+ a, b, c = points[rng.choice(len(points), 3, False)]
1237
+ nrm = np.cross(b - a, c - a)
1238
+ ln = np.linalg.norm(nrm)
1239
+ if ln < 1e-06:
1240
+ continue
1241
+ nrm /= ln
1242
+ d = -nrm @ a
1243
+ side = points @ nrm + d
1244
+ ninl = int((np.abs(side) < thr).sum())
1245
+ if ninl < 50:
1246
+ continue
1247
+ score = ninl * max(np.mean(side > thr), np.mean(side < -thr))
1248
+ if score > best_score:
1249
+ best_score = score
1250
+ best = (nrm, d)
1251
+ if best is None:
1252
+ ext = np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
1253
+ ax = int(np.argmin(ext))
1254
+ g = np.zeros(3)
1255
+ g[ax] = 1.0
1256
+ return (g, ax)
1257
+ nrm, d = best
1258
+ if cam is not None and cam @ nrm + d < 0:
1259
+ nrm = -nrm
1260
+ return (nrm.astype(np.float32), int(np.argmax(np.abs(nrm))))
1261
+
1262
+
1263
+ def _canonical_floor_basis(up_vec):
1264
+ """Orthonormal floor basis (u, v horizontal; g = up), unchanged from the old file."""
1265
+ g = np.asarray(up_vec, np.float64)
1266
+ g = g / (np.linalg.norm(g) + 1e-12)
1267
+ up_ax = int(np.argmax(np.abs(g)))
1268
+ floor_axes = [a for a in range(3) if a != up_ax]
1269
+ e0 = np.zeros(3)
1270
+ e0[floor_axes[0]] = 1.0
1271
+ u = e0 - e0 @ g * g
1272
+ u = u / (np.linalg.norm(u) + 1e-12)
1273
+ v = np.cross(g, u)
1274
+ if v[floor_axes[1]] < 0:
1275
+ v = -v
1276
+ return (u, v, g)
1277
+
1278
+
1279
+ def _canonical_robust_centroid_extent(pts, up_axis=None):
1280
+ c = np.median(pts, axis=0)
1281
+ centered = pts - c
1282
+ if len(centered) > 5000:
1283
+ centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
1284
+ if up_axis is not None:
1285
+ floor_axes = [i for i in range(3) if i != up_axis]
1286
+ floor_points = centered[:, floor_axes]
1287
+ try:
1288
+ _, _, floor_rotation = np.linalg.svd(
1289
+ floor_points - floor_points.mean(0), full_matrices=False
1290
+ )
1291
+ proj_floor = floor_points @ floor_rotation.T
1292
+ except np.linalg.LinAlgError:
1293
+ proj_floor = floor_points
1294
+ proj = np.concatenate([proj_floor, centered[:, up_axis : up_axis + 1]], 1)
1295
+ else:
1296
+ try:
1297
+ _, _, rotation = np.linalg.svd(
1298
+ centered - centered.mean(0), full_matrices=False
1299
+ )
1300
+ proj = centered @ rotation.T
1301
+ except np.linalg.LinAlgError:
1302
+ proj = centered
1303
+ ext = np.maximum(np.percentile(proj, 98, 0) - np.percentile(proj, 2, 0), 0.0)
1304
+ dims = np.sort(ext)[::-1]
1305
+ return (c.astype(np.float32), float(dims[0]), dims)
1306
+
1307
+
1308
+ def _canonical_aabb(pts):
1309
+ return (np.percentile(pts, 2, 0), np.percentile(pts, 98, 0))
1310
+
1311
+
1312
+ def _canonical_merge_by_box_overlap(insts, up_axis=None):
1313
+ """Parameter-free 3D re-identification with temporal exclusion, unchanged."""
1314
+ n = len(insts)
1315
+ if n <= 1:
1316
+ return insts
1317
+ lo = np.stack([_canonical_aabb(i["pts"])[0] for i in insts])
1318
+ hi = np.stack([_canonical_aabb(i["pts"])[1] for i in insts])
1319
+ cents = np.stack([i["centroid"] for i in insts])
1320
+ overlap = (hi[:, None] >= lo[None]).all(-1) & (hi[None] >= lo[:, None]).all(-1)
1321
+ ins = (cents[:, None] >= lo[None]).all(-1) & (cents[:, None] <= hi[None]).all(-1)
1322
+ match = overlap | ins | ins.T
1323
+ groups = [
1324
+ {"members": [i], "frames": set(insts[i].get("frames", ()))} for i in range(n)
1325
+ ]
1326
+ changed = True
1327
+ while changed:
1328
+ changed = False
1329
+ for a in range(len(groups)):
1330
+ for b in range(a + 1, len(groups)):
1331
+ if groups[a]["frames"] & groups[b]["frames"]:
1332
+ continue
1333
+ if match[np.ix_(groups[a]["members"], groups[b]["members"])].any():
1334
+ groups[a]["members"] += groups[b]["members"]
1335
+ groups[a]["frames"] |= groups[b]["frames"]
1336
+ groups.pop(b)
1337
+ changed = True
1338
+ break
1339
+ if changed:
1340
+ break
1341
+ out = []
1342
+ for g in groups:
1343
+ ii = g["members"]
1344
+ pts = np.concatenate([insts[k]["pts"] for k in ii], 0)
1345
+ best = max((insts[k]["best_pts"] for k in ii), key=len)
1346
+ c, size, dims = _canonical_robust_centroid_extent(best, up_axis)
1347
+ confs = [insts[k].get("conf") for k in ii]
1348
+ conf = (
1349
+ np.concatenate([x for x in confs if x is not None], 0)
1350
+ if any((x is not None for x in confs))
1351
+ else None
1352
+ )
1353
+ out.append(
1354
+ {
1355
+ "centroid": c,
1356
+ "size": size,
1357
+ "dims": dims,
1358
+ "pts": pts,
1359
+ "best_pts": best,
1360
+ "observations": [
1361
+ observation
1362
+ for k in ii
1363
+ for observation in insts[k].get("observations", [insts[k]["pts"]])
1364
+ ],
1365
+ "conf": conf,
1366
+ "frames": g["frames"],
1367
+ "nframes": len(g["frames"]),
1368
+ "n": sum((insts[k]["n"] for k in ii)),
1369
+ "first_time": min((insts[k]["first_time"] for k in ii)),
1370
+ }
1371
+ )
1372
+ return out
1373
+
1374
+
1375
+ def _canonical_sor(pts, k=16, std=2.0, cap=4000):
1376
+ from scipy.spatial import cKDTree
1377
+
1378
+ if len(pts) < k + 2:
1379
+ return pts
1380
+ points = (
1381
+ pts
1382
+ if len(pts) <= cap
1383
+ else pts[np.random.RandomState(0).choice(len(pts), cap, False)]
1384
+ )
1385
+ d, _ = cKDTree(points).query(points, k=k + 1, workers=KD_WORKERS)
1386
+ md = d[:, 1:].mean(1)
1387
+ return points[md <= md.mean() + std * md.std()]
1388
+
1389
+
1390
+ def _canonical_clean(inst, cap=4000):
1391
+ if inst.get("_cleanpts") is not None:
1392
+ return inst["_cleanpts"]
1393
+ pts, conf = (inst["pts"], inst.get("conf"))
1394
+ if len(pts) > cap:
1395
+ idx = np.random.RandomState(0).choice(len(pts), cap, False)
1396
+ pts = pts[idx]
1397
+ if conf is not None:
1398
+ conf = conf[idx]
1399
+ if conf is not None and len(conf) > 20:
1400
+ keep = conf >= np.median(conf)
1401
+ if keep.sum() >= 10:
1402
+ pts = pts[keep]
1403
+ inst["_cleanpts"] = _canonical_sor(pts, cap=cap)
1404
+ return inst["_cleanpts"]
1405
+
1406
+
1407
+ # ==========================================================================================
1408
+ # COMPACT SPATIAL CODE -- reusable geometry and time primitives, with no derived answers.
1409
+ # ==========================================================================================
1410
+
1411
+
1412
+ COMPACT_SPATIAL_CODE_SCHEMA = {
1413
+ "objects": {
1414
+ "<object class>": [
1415
+ {
1416
+ "3D oriented bounding box": {
1417
+ "3D oriented bounding box center coordinates": {
1418
+ "components": ["x", "y", "height above floor"],
1419
+ "unit": "meters",
1420
+ "description": (
1421
+ "center of the 3D oriented bounding box in the shared room "
1422
+ "coordinate system"
1423
+ ),
1424
+ },
1425
+ "3D oriented bounding box dimensions": {
1426
+ "components": ["dimension 1", "dimension 2", "dimension 3"],
1427
+ "unit": "meters",
1428
+ "description": (
1429
+ "full lengths of the 3D oriented bounding box along the "
1430
+ "corresponding orientation unit vectors"
1431
+ ),
1432
+ },
1433
+ "3D oriented bounding box orientation unit vectors": {
1434
+ "components": [
1435
+ ["x", "y", "height"],
1436
+ ["x", "y", "height"],
1437
+ ["x", "y", "height"],
1438
+ ],
1439
+ "unit": None,
1440
+ "description": (
1441
+ "three perpendicular directions corresponding in order to the "
1442
+ "three 3D oriented bounding box dimensions"
1443
+ ),
1444
+ },
1445
+ },
1446
+ "first visible time": {
1447
+ "unit": "seconds",
1448
+ "description": (
1449
+ "earliest time at which this object instance is visibly observed"
1450
+ ),
1451
+ },
1452
+ }
1453
+ ]
1454
+ },
1455
+ "room": {
1456
+ "floor boundary polygons": [
1457
+ {
1458
+ "outer boundary coordinates": {
1459
+ "components": [["x", "y"], ["x", "y"]],
1460
+ "unit": "meters",
1461
+ "description": "ordered vertices enclosing one floor region",
1462
+ },
1463
+ "interior hole boundary coordinates": {
1464
+ "components": [[["x", "y"], ["x", "y"]]],
1465
+ "unit": "meters",
1466
+ "description": (
1467
+ "ordered boundaries enclosing regions excluded from the floor area"
1468
+ ),
1469
+ },
1470
+ }
1471
+ ]
1472
+ },
1473
+ }
1474
+
1475
+
1476
+ def _rounded_list(values):
1477
+ """Round one numeric vector to stable JSON values without negative zero."""
1478
+ return [0.0 if (value := round(float(x), 2)) == 0 else value for x in values]
1479
+
1480
+
1481
+ def _weighted_quantile(values, weights, quantile):
1482
+ """Return one deterministic weighted quantile for observation consensus."""
1483
+ values = np.asarray(values, np.float64)
1484
+ weights = np.asarray(weights, np.float64)
1485
+ order = np.argsort(values)
1486
+ values, weights = values[order], weights[order]
1487
+ cumulative = np.cumsum(weights) - 0.5 * weights
1488
+ cumulative /= weights.sum()
1489
+ return float(np.interp(quantile, cumulative, values))
1490
+
1491
+
1492
+ def _compact_oriented_box(instance, u, v, g, floor_level):
1493
+ """Fit one floor-aligned OBB from the same per-instance math as the reference code."""
1494
+ center = np.asarray(instance["centroid"], np.float64)
1495
+ points = np.asarray(instance["best_pts"], np.float64)
1496
+ room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
1497
+ centered = room_points[:, :2] - np.median(room_points[:, :2], axis=0)
1498
+ if len(centered) > 5000:
1499
+ centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
1500
+ try:
1501
+ _, _, rotation = np.linalg.svd(
1502
+ centered - centered.mean(axis=0), full_matrices=False
1503
+ )
1504
+ except np.linalg.LinAlgError:
1505
+ rotation = np.eye(2)
1506
+ first = rotation[0]
1507
+ dominant = int(np.argmax(np.abs(first)))
1508
+ if first[dominant] < 0:
1509
+ first = -first
1510
+ second = np.array([-first[1], first[0]])
1511
+ orientation = np.array(
1512
+ [[first[0], first[1], 0.0], [second[0], second[1], 0.0], [0.0, 0.0, 1.0]]
1513
+ )
1514
+ box_center = np.array([center @ u, center @ v, center @ g - floor_level])
1515
+ box_dimensions = np.asarray(instance["dims"], np.float64)
1516
+ return {
1517
+ "3D oriented bounding box center coordinates": _rounded_list(box_center),
1518
+ "3D oriented bounding box dimensions": _rounded_list(box_dimensions),
1519
+ "3D oriented bounding box orientation unit vectors": [
1520
+ _rounded_list(axis) for axis in orientation
1521
+ ],
1522
+ }
1523
+
1524
+
1525
+ def _contour_coordinates(contour, x_origin, y_origin, resolution):
1526
+ """Translate one OpenCV grid contour to ordered shared-room coordinates."""
1527
+ return [
1528
+ _rounded_list(
1529
+ [x_origin + (row - 1) * resolution, y_origin + (column - 1) * resolution]
1530
+ )
1531
+ for column, row in contour[:, 0, :]
1532
+ ]
1533
+
1534
+
1535
+ def _compact_scene_points(scene):
1536
+ """Return the same dense floor-support sample used by explicit room-area math."""
1537
+ raw_inputs = scene.get("raw_inputs")
1538
+ if raw_inputs is None:
1539
+ return scene["scene_pts"]
1540
+ depth = raw_inputs["depth"]
1541
+ intrinsics = raw_inputs["intr"]
1542
+ poses = raw_inputs["c2w"]
1543
+ confidence = raw_inputs.get("conf")
1544
+ points = []
1545
+ for frame_index in range(len(depth)):
1546
+ height, width = depth[frame_index].shape
1547
+ rows, columns = np.mgrid[0:height:8, 0:width:8]
1548
+ rows, columns = rows.ravel(), columns.ravel()
1549
+ values = depth[frame_index][rows, columns]
1550
+ keep = np.isfinite(values) & (values > 0)
1551
+ if confidence is not None:
1552
+ threshold = np.percentile(confidence[frame_index], 40)
1553
+ keep &= confidence[frame_index][rows, columns] >= threshold
1554
+ rows, columns, values = rows[keep], columns[keep], values[keep]
1555
+ if not len(values):
1556
+ continue
1557
+ current = intrinsics[frame_index]
1558
+ camera = np.stack(
1559
+ [
1560
+ (columns - current[0, 2]) * values / current[0, 0],
1561
+ (rows - current[1, 2]) * values / current[1, 1],
1562
+ values,
1563
+ ],
1564
+ axis=1,
1565
+ )
1566
+ world = poses[frame_index][:3, :3] @ camera.T
1567
+ points.append((world.T + poses[frame_index][:3, 3]).astype(np.float32))
1568
+ return np.concatenate(points, axis=0) if points else scene["scene_pts"]
1569
+
1570
+
1571
+ def _compact_floor_boundary_polygons(points, u, v, object_points=None):
1572
+ """Extract the reference room outline as a compact floor-boundary polygon."""
1573
+ from scipy import ndimage
1574
+
1575
+ points = np.asarray(points, np.float64)
1576
+ floor_points = np.stack([points @ u, points @ v], axis=1)
1577
+ floor_points = floor_points[np.isfinite(floor_points).all(axis=1)]
1578
+ if len(floor_points) < 3:
1579
+ return []
1580
+ lower = np.percentile(floor_points, 0.5, axis=0)
1581
+ upper = np.percentile(floor_points, 99.5, axis=0)
1582
+ floor_points = floor_points[
1583
+ (floor_points[:, 0] >= lower[0])
1584
+ & (floor_points[:, 0] <= upper[0])
1585
+ & (floor_points[:, 1] >= lower[1])
1586
+ & (floor_points[:, 1] <= upper[1])
1587
+ ]
1588
+ if len(floor_points) < 3:
1589
+ return []
1590
+ resolution = 0.1
1591
+ x_origin, y_origin = floor_points.min(axis=0)
1592
+ x_max, y_max = floor_points.max(axis=0)
1593
+ row_count = int((x_max - x_origin) / resolution) + 3
1594
+ column_count = int((y_max - y_origin) / resolution) + 3
1595
+ grid = np.zeros((row_count, column_count), np.uint8)
1596
+ rows = ((floor_points[:, 0] - x_origin) / resolution).astype(int)
1597
+ columns = ((floor_points[:, 1] - y_origin) / resolution).astype(int)
1598
+ grid[rows + 1, columns + 1] = 1
1599
+ grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
1600
+ grid = ndimage.binary_fill_holes(grid).astype(np.uint8)
1601
+ contours, _ = cv2.findContours(grid, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
1602
+ if not contours:
1603
+ return []
1604
+ contour = cv2.approxPolyDP(
1605
+ max(contours, key=cv2.contourArea), 0.2 / resolution, True
1606
+ )
1607
+ return [
1608
+ {
1609
+ "outer boundary coordinates": _contour_coordinates(
1610
+ contour, x_origin, y_origin, resolution
1611
+ ),
1612
+ "interior hole boundary coordinates": [],
1613
+ }
1614
+ ]
1615
+
1616
+
1617
+ def _compact_duplicate_groups(instances):
1618
+ """Group near-identical co-visible boxes that represent duplicate mask tracks."""
1619
+ count = len(instances)
1620
+ parent = list(range(count))
1621
+
1622
+ def root(index):
1623
+ while parent[index] != index:
1624
+ parent[index] = parent[parent[index]]
1625
+ index = parent[index]
1626
+ return index
1627
+
1628
+ def union(first, second):
1629
+ first, second = root(first), root(second)
1630
+ if first != second:
1631
+ parent[second] = first
1632
+
1633
+ bounds = [_canonical_aabb(_canonical_clean(instance)) for instance in instances]
1634
+ for first in range(count):
1635
+ lower_a, upper_a = bounds[first]
1636
+ extent_a = np.maximum(upper_a - lower_a, 1e-6)
1637
+ volume_a = float(np.prod(extent_a))
1638
+ for second in range(first + 1, count):
1639
+ lower_b, upper_b = bounds[second]
1640
+ extent_b = np.maximum(upper_b - lower_b, 1e-6)
1641
+ volume_b = float(np.prod(extent_b))
1642
+ intersection = np.maximum(
1643
+ np.minimum(upper_a, upper_b) - np.maximum(lower_a, lower_b), 0.0
1644
+ )
1645
+ overlap = float(np.prod(intersection)) / min(volume_a, volume_b)
1646
+ if overlap >= 0.8:
1647
+ union(first, second)
1648
+ groups = {}
1649
+ for index in range(count):
1650
+ groups.setdefault(root(index), []).append(index)
1651
+ return list(groups.values())
1652
+
1653
+
1654
+ def _combine_compact_instances(instances, members, up_axis):
1655
+ """Combine one duplicate group while retaining all evidence and earliest timing."""
1656
+ selected = [instances[index] for index in members]
1657
+ points = np.concatenate([instance["pts"] for instance in selected], axis=0)
1658
+ best = max((instance["best_pts"] for instance in selected), key=len)
1659
+ confidence = [instance.get("conf") for instance in selected]
1660
+ confidence = (
1661
+ np.concatenate(confidence, axis=0)
1662
+ if all(value is not None for value in confidence)
1663
+ else None
1664
+ )
1665
+ centroid, size, dimensions = _canonical_robust_centroid_extent(points, up_axis)
1666
+ frames = set().union(*(set(instance.get("frames", ())) for instance in selected))
1667
+ return {
1668
+ "centroid": centroid,
1669
+ "size": size,
1670
+ "dims": dimensions,
1671
+ "first_time": min(instance["first_time"] for instance in selected),
1672
+ "pts": points,
1673
+ "conf": confidence,
1674
+ "best_pts": best,
1675
+ "observations": [
1676
+ observation
1677
+ for instance in selected
1678
+ for observation in instance.get("observations", [instance["pts"]])
1679
+ ],
1680
+ "frames": frames,
1681
+ "n": sum(instance.get("n", len(instance["pts"])) for instance in selected),
1682
+ "nframes": len(frames),
1683
+ "oids": [oid for instance in selected for oid in instance.get("oids", [])],
1684
+ }
1685
+
1686
+
1687
+ def _compact_instance_evidence(instance):
1688
+ """Rank one physical-instance hypothesis by persistence and geometric support."""
1689
+ observations = instance.get("observations", [instance["pts"]])
1690
+ observed_points = np.array([len(observation) for observation in observations])
1691
+ return (
1692
+ instance.get("nframes", len(instance.get("frames", ()))),
1693
+ len(observations),
1694
+ float(np.median(observed_points)) if len(observed_points) else 0.0,
1695
+ instance.get("n", len(instance["pts"])),
1696
+ )
1697
+
1698
+
1699
+ def _consolidate_compact_instances(instances, stats, up_axis):
1700
+ """Suppress duplicate tracks and retain the strongest co-visible instance set."""
1701
+ consolidated = {}
1702
+ for class_name, items in instances.items():
1703
+ combined = [
1704
+ _combine_compact_instances(items, members, up_axis)
1705
+ for members in _compact_duplicate_groups(items)
1706
+ ]
1707
+ peak = int(stats.get(class_name, {}).get("peak", 0))
1708
+ limit = min(len(combined), max(peak, 1))
1709
+ ranked = sorted(combined, key=_compact_instance_evidence, reverse=True)
1710
+ retained = ranked[:limit]
1711
+ for fragment in ranked[limit:]:
1712
+ nearest = min(
1713
+ retained,
1714
+ key=lambda instance: np.linalg.norm(
1715
+ instance["centroid"] - fragment["centroid"]
1716
+ ),
1717
+ )
1718
+ nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
1719
+ consolidated[class_name] = retained
1720
+ return consolidated
1721
+
1722
+
1723
+ def _compact_instances(scene, up_axis):
1724
+ """Return consolidated physical instances for raw or canonical adapter geometry."""
1725
+ raw_inputs = scene.get("raw_inputs")
1726
+ if raw_inputs is not None:
1727
+ instances, stats = build_instances(
1728
+ raw_inputs["per"],
1729
+ raw_inputs["depth"],
1730
+ raw_inputs["intr"],
1731
+ raw_inputs["c2w"],
1732
+ raw_inputs.get("conf"),
1733
+ raw_inputs["ftimes"],
1734
+ up_axis=up_axis,
1735
+ )
1736
+ else:
1737
+ instances = {}
1738
+ stats = {
1739
+ class_name: dict(values) for class_name, values in scene["stats"].items()
1740
+ }
1741
+ for class_name, items in scene["instances"].items():
1742
+ measured = []
1743
+ for item in items:
1744
+ points = _canonical_clean(item)
1745
+ if not len(points):
1746
+ points = item["pts"]
1747
+ centroid, size, dimensions = _canonical_robust_centroid_extent(
1748
+ points, up_axis
1749
+ )
1750
+ record = dict(item)
1751
+ record.update({"centroid": centroid, "size": size, "dims": dimensions})
1752
+ measured.append(record)
1753
+ instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
1754
+ for class_name, items in instances.items():
1755
+ stats.setdefault(class_name, {})
1756
+ stats[class_name]["merged"] = len(items)
1757
+ return instances, stats
1758
+
1759
+
1760
+ def instance_source_track_ids(scene):
1761
+ """Return {emitted_class_name: [oids_for_instance_1, oids_for_instance_2, ...]},
1762
+ one ordered list of raw SAM3 masklet ids per FINAL consolidated instance -- in
1763
+ EXACTLY the rank order build_compact_spatial_code() emits instances in (same
1764
+ (n, nframes)-descending sort, same class-name aliasing), so index i here IS the
1765
+ "<class> {i+1}" instance id the strong correspondence overlay stamps. A raw-only
1766
+ lookup: reruns nothing but the consolidation build_compact_spatial_code() already
1767
+ does, just exposing the "oids" field that pipeline discards before emission (the
1768
+ on-disk schema never carries SAM3 ids -- this function is the only place that does).
1769
+ """
1770
+ alias = {"coat hanger": "coat rack"}
1771
+ raw_inputs = scene.get("raw_inputs")
1772
+ if raw_inputs is None:
1773
+ raise ValueError(
1774
+ "instance_source_track_ids needs raw depth/intr/c2w inputs; this geometry "
1775
+ "cache carries only canonical points (no SAM3 track ids to recover)"
1776
+ )
1777
+ up_vec, up_ax = room_gravity(
1778
+ raw_inputs["depth"],
1779
+ raw_inputs["intr"],
1780
+ raw_inputs["c2w"],
1781
+ raw_inputs.get("conf"),
1782
+ )
1783
+ instances, _stats = _compact_instances(scene, up_ax)
1784
+ out = {}
1785
+ for class_name, items in instances.items():
1786
+ emitted_name = alias.get(class_name, class_name)
1787
+ ranked = sorted(
1788
+ items,
1789
+ key=lambda item: (item.get("n", 0), item.get("nframes", 0)),
1790
+ reverse=True,
1791
+ )
1792
+ out.setdefault(emitted_name, []).extend(item.get("oids", []) for item in ranked)
1793
+ return out
1794
+
1795
+
1796
+ def build_compact_spatial_code(scene):
1797
+ """Build reusable OBB, visibility-time, and floor-boundary primitives."""
1798
+ alias = {"coat hanger": "coat rack"}
1799
+ raw_inputs = scene.get("raw_inputs")
1800
+ if raw_inputs is not None:
1801
+ up_vec, up_ax = room_gravity(
1802
+ raw_inputs["depth"],
1803
+ raw_inputs["intr"],
1804
+ raw_inputs["c2w"],
1805
+ raw_inputs.get("conf"),
1806
+ )
1807
+ u, v, g = _floor_basis(up_vec)
1808
+ else:
1809
+ up_vec, up_ax = _canonical_room_gravity(
1810
+ scene["scene_pts"], scene.get("cameras")
1811
+ )
1812
+ u, v, g = _canonical_floor_basis(up_vec)
1813
+ instances, stats = _compact_instances(scene, up_ax)
1814
+ all_points = np.concatenate(
1815
+ [item["pts"] for values in instances.values() for item in values], axis=0
1816
+ )
1817
+ floor_level = _floor_level(all_points, g)
1818
+ objects = {}
1819
+ for class_name, items in instances.items():
1820
+ emitted_name = alias.get(class_name, class_name)
1821
+ ranked = sorted(
1822
+ items,
1823
+ key=lambda item: (item.get("n", 0), item.get("nframes", 0)),
1824
+ reverse=True,
1825
+ )
1826
+ count = int(stats.get(class_name, {}).get("peak", 0))
1827
+ ranked = ranked[: max(count, 1)]
1828
+ objects.setdefault(emitted_name, []).extend(
1829
+ {
1830
+ "3D oriented bounding box": _compact_oriented_box(
1831
+ item, u, v, g, floor_level
1832
+ ),
1833
+ "first visible time": round(float(item["first_time"]), 2),
1834
+ }
1835
+ for item in ranked
1836
+ )
1837
+ code = {
1838
+ "objects": objects,
1839
+ "room": {
1840
+ "floor boundary polygons": _compact_floor_boundary_polygons(
1841
+ _compact_scene_points(scene), u, v
1842
+ )
1843
+ },
1844
+ }
1845
+ return code, instances, stats, up_ax, up_vec, None
1846
+
1847
+
1848
+ # ==========================================================================================
1849
+ # EXPLICIT SPATIAL CODE -- a strict derivation of the compact schema above. Every object
1850
+ # position/dimension/count/appearance-order value is read directly off compact's own oriented
1851
+ # boxes and "first visible time" (a direct subset, not independently recomputed); the distance
1852
+ # table is the one thing compact never stores, so it is computed here purely from compact's own
1853
+ # 3D oriented boxes -- exact surface-to-surface separation via bounded least squares (same
1854
+ # convex, closed-form-adjacent optimization symbolic/adapters.py's solver-side derivation
1855
+ # already used for compact input, now the ACTUAL on-disk construction for explicit too, so the
1856
+ # two schemas can never independently disagree about the same scene's geometry).
1857
+ # ==========================================================================================
1858
+
1859
+
1860
+ EXPLICIT_SPATIAL_CODE_SCHEMA = {
1861
+ "objects": {
1862
+ "<object class>": {
1863
+ "count": {
1864
+ "unit": None,
1865
+ "description": (
1866
+ "number of instances of this class in the compact spatial code "
1867
+ "(that schema's per-class oriented-box list length)"
1868
+ ),
1869
+ },
1870
+ "instances": [
1871
+ {
1872
+ "position": {
1873
+ "x coordinate": {
1874
+ "unit": "meters",
1875
+ "description": (
1876
+ "x coordinate of this instance's compact 3D oriented "
1877
+ "bounding box center"
1878
+ ),
1879
+ },
1880
+ "y coordinate": {
1881
+ "unit": "meters",
1882
+ "description": (
1883
+ "y coordinate of this instance's compact 3D oriented "
1884
+ "bounding box center"
1885
+ ),
1886
+ },
1887
+ "height above floor": {
1888
+ "unit": "meters",
1889
+ "description": (
1890
+ "height coordinate of this instance's compact 3D oriented "
1891
+ "bounding box center"
1892
+ ),
1893
+ },
1894
+ },
1895
+ "longest dimension": {
1896
+ "unit": "meters",
1897
+ "description": (
1898
+ "longest of this instance's compact 3D oriented bounding box "
1899
+ "dimensions"
1900
+ ),
1901
+ },
1902
+ }
1903
+ ],
1904
+ }
1905
+ },
1906
+ "room": {
1907
+ "floor area": {
1908
+ "unit": "square meters",
1909
+ "description": (
1910
+ "shoelace area of the compact spatial code's floor boundary polygons, "
1911
+ "with every interior hole subtracted"
1912
+ ),
1913
+ }
1914
+ },
1915
+ "closest classes distance meters from": {
1916
+ "<object class>": {
1917
+ "<other object class>": {
1918
+ "distance": {
1919
+ "unit": "meters",
1920
+ "description": (
1921
+ "estimated distance in meters between an object of this class "
1922
+ "and an object of the other class"
1923
+ ),
1924
+ },
1925
+ "closeness rank": {
1926
+ "unit": None,
1927
+ "description": (
1928
+ "1 = the nearest other class to this one, 2 = second-nearest, "
1929
+ "and so on; ranked by nearest-instance proximity, so use the "
1930
+ "rank (not the distance values) to compare which class is "
1931
+ "closest"
1932
+ ),
1933
+ },
1934
+ }
1935
+ }
1936
+ },
1937
+ "appearance order": {
1938
+ "unit": None,
1939
+ "description": (
1940
+ "class names ordered by earliest compact 'first visible time' across all of "
1941
+ "that class's instances"
1942
+ ),
1943
+ },
1944
+ }
1945
+
1946
+
1947
+ def _compact_box_distance(box_a, box_b):
1948
+ """Return the true minimum Euclidean separation of two compact 3D oriented boxes.
1949
+
1950
+ Verbatim derivation from symbolic/adapters.py's oriented_box_distance(): the six box
1951
+ coefficients form one convex bounded least-squares problem, solved exactly by BVLS -- no
1952
+ center, corner, or longest-dimension shortcut, so touching/intersecting boxes return zero.
1953
+
1954
+ Orientation vectors are renormalized to unit length before use, exactly like
1955
+ symbolic/adapters.py's _oriented_box() -- compact's on-disk vectors are rounded to 2
1956
+ decimals, so they are no longer *exactly* unit length, and the matrix below implicitly
1957
+ assumes they are (each column is dimension/2 along that axis). Skipping this step is a
1958
+ real source of error, not just a rounding artifact: it measurably shifted computed
1959
+ distances in testing (up to ~0.01 m on real scenes), and would make explicit silently
1960
+ disagree with what the solver derives from the identical compact box at read time.
1961
+ """
1962
+ from scipy.optimize import lsq_linear
1963
+
1964
+ center_a = np.asarray(
1965
+ box_a["3D oriented bounding box center coordinates"], np.float64
1966
+ )
1967
+ dimensions_a = np.asarray(box_a["3D oriented bounding box dimensions"], np.float64)
1968
+ orientation_a = np.asarray(
1969
+ box_a["3D oriented bounding box orientation unit vectors"], np.float64
1970
+ )
1971
+ orientation_a = orientation_a / np.linalg.norm(orientation_a, axis=1, keepdims=True)
1972
+ center_b = np.asarray(
1973
+ box_b["3D oriented bounding box center coordinates"], np.float64
1974
+ )
1975
+ dimensions_b = np.asarray(box_b["3D oriented bounding box dimensions"], np.float64)
1976
+ orientation_b = np.asarray(
1977
+ box_b["3D oriented bounding box orientation unit vectors"], np.float64
1978
+ )
1979
+ orientation_b = orientation_b / np.linalg.norm(orientation_b, axis=1, keepdims=True)
1980
+ matrix = np.column_stack(
1981
+ [
1982
+ *(dimensions_a[index] * orientation_a[index] / 2 for index in range(3)),
1983
+ *(-dimensions_b[index] * orientation_b[index] / 2 for index in range(3)),
1984
+ ]
1985
+ )
1986
+ result = lsq_linear(
1987
+ matrix,
1988
+ center_b - center_a,
1989
+ bounds=(-1, 1),
1990
+ method="bvls",
1991
+ lsq_solver="exact",
1992
+ tol=1e-12,
1993
+ max_iter=200,
1994
+ )
1995
+ if not result.success:
1996
+ raise RuntimeError(
1997
+ f"oriented-box distance optimization failed: {result.message}"
1998
+ )
1999
+ distance = float(np.linalg.norm(matrix @ result.x + center_a - center_b))
2000
+ return 0.0 if distance < 1e-10 else distance
2001
+
2002
+
2003
+ def _compact_class_distance(instances_a, instances_b):
2004
+ """Return the minimum compact oriented-box distance across every cross-class instance pair."""
2005
+ return min(
2006
+ _compact_box_distance(
2007
+ a["3D oriented bounding box"], b["3D oriented bounding box"]
2008
+ )
2009
+ for a in instances_a
2010
+ for b in instances_b
2011
+ )
2012
+
2013
+
2014
+ def _primary_instance_distance_floor(instances_a, instances_b):
2015
+ """A sphere-approximation floor on the two classes' PRIMARY (instance[0]) distance:
2016
+ 3D center-to-center distance minus each primary box's longest dimension / 2, floored
2017
+ at 0. Mirrors symbolic/solver.py's _primary_instance_distance_estimate exactly (the
2018
+ same correction, applied at ENCODING time so the table value a reader looks up
2019
+ already carries it -- see _corrected_class_distance below)."""
2020
+ box_a = instances_a[0]["3D oriented bounding box"]
2021
+ box_b = instances_b[0]["3D oriented bounding box"]
2022
+ center_a = box_a["3D oriented bounding box center coordinates"]
2023
+ center_b = box_b["3D oriented bounding box center coordinates"]
2024
+ center_distance = (
2025
+ sum((float(a) - float(b)) ** 2 for a, b in zip(center_a, center_b)) ** 0.5
2026
+ )
2027
+ radius_a = max(box_a["3D oriented bounding box dimensions"]) / 2
2028
+ radius_b = max(box_b["3D oriented bounding box dimensions"]) / 2
2029
+ return max(0.0, center_distance - (radius_a + radius_b))
2030
+
2031
+
2032
+ def _corrected_class_distance(instances_a, instances_b):
2033
+ """max(min-across-pairs surface distance, primary-instance sphere floor) -- the
2034
+ combination symbolic/solver.py applies at ANSWER time for ABSOLUTE-distance
2035
+ questions. TRIED AND REVERTED as the table's stored value (2026-07-25, see
2036
+ preregistration.md): baking it in re-derived the closeness RANKS from
2037
+ corrected distances, and closest-of-class ranking is exactly where the raw
2038
+ min-across-instances is the semantically correct quantity -- solver relative-
2039
+ distance accuracy fell 59.2 -> 47.5 on real perceived codes and the VLM pilot
2040
+ dropped in the same direction.
2041
+
2042
+ REINSTATED (2026-07-25, second amendment, see preregistration.md) as the
2043
+ table's PRINTED distance only, with the fix the first attempt lacked: closeness
2044
+ ranks stay computed from the raw min-across-instances distance (the correct
2045
+ closest-of-class quantity), and the solver's relative-distance answer reads the
2046
+ rank field rather than comparing printed values. The printed value IS the solver's
2047
+ absolute-distance answer, making abs-distance a pure lookup for any reader."""
2048
+ return max(
2049
+ _compact_class_distance(instances_a, instances_b),
2050
+ _primary_instance_distance_floor(instances_a, instances_b),
2051
+ )
2052
+
2053
+
2054
+ def _compact_polygon_area(coordinates):
2055
+ """Return the unsigned shoelace area of one ordered compact floor-boundary polygon."""
2056
+ if len(coordinates) < 3:
2057
+ return 0.0
2058
+ return abs(
2059
+ sum(
2060
+ coordinates[index][0] * coordinates[(index + 1) % len(coordinates)][1]
2061
+ - coordinates[(index + 1) % len(coordinates)][0] * coordinates[index][1]
2062
+ for index in range(len(coordinates))
2063
+ )
2064
+ / 2
2065
+ )
2066
+
2067
+
2068
+ def _compact_room_floor_area(polygons):
2069
+ """Sum outer areas and subtract every interior hole across compact's floor regions."""
2070
+ area = 0.0
2071
+ for polygon in polygons:
2072
+ area += _compact_polygon_area(polygon.get("outer boundary coordinates", []))
2073
+ area -= sum(
2074
+ _compact_polygon_area(hole)
2075
+ for hole in polygon.get("interior hole boundary coordinates", [])
2076
+ )
2077
+ return max(0.0, area)
2078
+
2079
+
2080
+ def _compact_box_axis_bounds(box):
2081
+ center = np.asarray(box["3D oriented bounding box center coordinates"], np.float64)
2082
+ dimensions = np.asarray(box["3D oriented bounding box dimensions"], np.float64)
2083
+ orientation = np.asarray(
2084
+ box["3D oriented bounding box orientation unit vectors"], np.float64
2085
+ )
2086
+ orientation = orientation / np.linalg.norm(orientation, axis=1, keepdims=True)
2087
+ offsets = []
2088
+ for sx in (-1.0, 1.0):
2089
+ for sy in (-1.0, 1.0):
2090
+ for sz in (-1.0, 1.0):
2091
+ offsets.append(
2092
+ sx * dimensions[0] * orientation[0] / 2
2093
+ + sy * dimensions[1] * orientation[1] / 2
2094
+ + sz * dimensions[2] * orientation[2] / 2
2095
+ )
2096
+ corners = center + np.asarray(offsets)
2097
+ return [
2098
+ [
2099
+ round(float(corners[:, axis].min()), 2),
2100
+ round(float(corners[:, axis].max()), 2),
2101
+ ]
2102
+ for axis in range(3)
2103
+ ]
2104
+
2105
+
2106
+ def _compact_outline_for_v2(compact_code):
2107
+ polygons = compact_code.get("room", {}).get("floor boundary polygons", [])
2108
+ if not polygons:
2109
+ return []
2110
+ outline = []
2111
+ for x, y in polygons[0].get("outer boundary coordinates", []):
2112
+ outline.append(
2113
+ {"floor_x_meters": round(float(x), 1), "floor_y_meters": round(float(y), 1)}
2114
+ )
2115
+ return outline
2116
+
2117
+
2118
+ def _explicit_from_compact(compact_code):
2119
+ """Derive a V2 explicit spatial code from an already-built compact spatial code.
2120
+
2121
+ This is used for canonical adapter geometry and ground truth. It mirrors the V2 envelope
2122
+ used by the raw encoder path: no embedded legend, numeric closest-class table, V2 room
2123
+ keys, and compact "appearance order".
2124
+ """
2125
+ compact_objects = compact_code["objects"]
2126
+
2127
+ objects = {}
2128
+ first_visible = {}
2129
+ for class_name, items in compact_objects.items():
2130
+ rendered = []
2131
+ for item in items:
2132
+ box = item["3D oriented bounding box"]
2133
+ center = box["3D oriented bounding box center coordinates"]
2134
+ dimensions = box["3D oriented bounding box dimensions"]
2135
+ bounds = _compact_box_axis_bounds(box)
2136
+ rendered.append(
2137
+ {
2138
+ "position": {
2139
+ "floor_x_meters": round(float(center[0]), 2),
2140
+ "floor_y_meters": round(float(center[1]), 2),
2141
+ "height_above_floor_meters": round(float(center[2]), 2),
2142
+ },
2143
+ "longest_dimension_meters": round(float(max(dimensions)), 2),
2144
+ "bounding_box": {
2145
+ "floor_x_meters": bounds[0],
2146
+ "floor_y_meters": bounds[1],
2147
+ "height_above_floor_meters": bounds[2],
2148
+ },
2149
+ "dimensions_meters": [
2150
+ round(float(value), 2) for value in dimensions
2151
+ ],
2152
+ }
2153
+ )
2154
+ time = item["first visible time"]
2155
+ if time is not None:
2156
+ first_visible[class_name] = min(
2157
+ first_visible.get(class_name, float("inf")), float(time)
2158
+ )
2159
+ objects[class_name] = {"count": len(items), "instances": rendered}
2160
+
2161
+ classes = [name for name, items in compact_objects.items() if items]
2162
+ raw_distances = {class_name: {} for class_name in classes}
2163
+ printed_distances = {class_name: {} for class_name in classes}
2164
+ for index, class_name in enumerate(classes):
2165
+ for other in classes[index + 1 :]:
2166
+ raw = _compact_class_distance(
2167
+ compact_objects[class_name], compact_objects[other]
2168
+ )
2169
+ printed = _corrected_class_distance(
2170
+ compact_objects[class_name], compact_objects[other]
2171
+ )
2172
+ raw_distances[class_name][other] = raw
2173
+ raw_distances[other][class_name] = raw
2174
+ printed_distances[class_name][other] = printed
2175
+ printed_distances[other][class_name] = printed
2176
+ closest = {}
2177
+ for class_name, distances in raw_distances.items():
2178
+ ranked = sorted(distances.items(), key=lambda item: (item[1], item[0]))
2179
+ closest[class_name] = {
2180
+ other: {
2181
+ "closeness_rank": rank + 1,
2182
+ "distance_meters": round(printed_distances[class_name][other], 2),
2183
+ }
2184
+ for rank, (other, _raw) in enumerate(ranked)
2185
+ }
2186
+
2187
+ floor_area = round(
2188
+ _compact_room_floor_area(
2189
+ compact_code["room"].get("floor boundary polygons", [])
2190
+ ),
2191
+ 1,
2192
+ )
2193
+
2194
+ return {
2195
+ "objects": objects,
2196
+ "room": {
2197
+ "outline": _compact_outline_for_v2(compact_code),
2198
+ "floor_area_square_meters": floor_area,
2199
+ },
2200
+ "closest_classes_from": closest,
2201
+ "appearance order": sorted(
2202
+ classes, key=lambda name: first_visible.get(name, float("inf"))
2203
+ ),
2204
+ }, floor_area
2205
+
2206
+
2207
+ def _build_reference_v2_spatial_code(raw_inputs):
2208
+ """Build the raw encoder spatial code exactly like the reference V2 branch."""
2209
+ alias = {"coat hanger": "coat rack"}
2210
+ per = {
2211
+ alias.get(class_name, class_name): frames
2212
+ for class_name, frames in raw_inputs["per"].items()
2213
+ }
2214
+ depth = raw_inputs["depth"]
2215
+ intr = raw_inputs["intr"]
2216
+ c2w = raw_inputs["c2w"]
2217
+ conf = raw_inputs.get("conf")
2218
+ frame_times = raw_inputs["ftimes"]
2219
+
2220
+ up_vec, up_axis = room_gravity(depth, intr, c2w, conf)
2221
+ instances, stats = build_instances(
2222
+ per, depth, intr, c2w, conf, frame_times, up_axis=up_axis
2223
+ )
2224
+ u, v, g = _floor_basis(up_vec)
2225
+ all_points = np.concatenate(
2226
+ [item["pts"] for values in instances.values() for item in values], axis=0
2227
+ )
2228
+ floor_level = float(np.percentile(all_points @ g, 2))
2229
+ floor_area = compute_floor_area(depth, intr, c2w, conf, None, up_vec=up_vec)
2230
+ code = _reference_to_spatial_code(
2231
+ instances, stats, floor_area, up_axis, up_vec, floor_level
2232
+ )
2233
+ classes = list(instances.keys())
2234
+ class_first = {
2235
+ class_name: min(item["first_time"] for item in values)
2236
+ for class_name, values in instances.items()
2237
+ }
2238
+
2239
+ for class_name in classes:
2240
+ ranked = sorted(
2241
+ instances[class_name],
2242
+ key=lambda item: (item["n"], item.get("nframes", 0)),
2243
+ reverse=True,
2244
+ )
2245
+ for record, item in zip(code["objects"][class_name]["instances"], ranked):
2246
+ record["seen_in_video_frames"] = int(
2247
+ item.get("nframes", len(item.get("frames", ())))
2248
+ )
2249
+
2250
+ closest = {}
2251
+ for class_name in classes:
2252
+ distances = sorted(
2253
+ (
2254
+ round(
2255
+ answer_closest_distance(instances[class_name], instances[other]), 2
2256
+ ),
2257
+ other,
2258
+ )
2259
+ for other in classes
2260
+ if other != class_name
2261
+ )
2262
+ closest[class_name] = {
2263
+ other: {"closeness_rank": rank + 1, "distance_meters": distance}
2264
+ for rank, (distance, other) in enumerate(distances)
2265
+ }
2266
+ code["closest_classes_from"] = closest
2267
+
2268
+ waypoints = []
2269
+ next_time = 0.0
2270
+ for index, time_seconds in enumerate(np.asarray(frame_times, np.float64)):
2271
+ if time_seconds + 1e-9 < next_time:
2272
+ continue
2273
+ next_time = float(time_seconds) + 5.0
2274
+ position = c2w[index][:3, 3]
2275
+ forward = c2w[index][:3, 2]
2276
+ waypoints.append(
2277
+ {
2278
+ "time_seconds": round(float(time_seconds), 1),
2279
+ "floor_x_meters": round(float(position @ u), 2),
2280
+ "floor_y_meters": round(float(position @ v), 2),
2281
+ "heading_degrees": round(
2282
+ float(np.degrees(np.arctan2(forward @ v, forward @ u)))
2283
+ ),
2284
+ }
2285
+ )
2286
+ code["camera_trajectory"] = {
2287
+ "sample_interval_seconds": 5,
2288
+ "waypoints": waypoints,
2289
+ }
2290
+ code["room"] = {
2291
+ "outline": _room_outline(depth, intr, c2w, conf, u, v),
2292
+ "floor_area_square_meters": code["room"]["floor_area_square_meters"],
2293
+ }
2294
+ code["appearance order"] = [
2295
+ class_name
2296
+ for class_name, _time in sorted(class_first.items(), key=lambda item: item[1])
2297
+ ]
2298
+ return code, instances, stats, up_axis, up_vec, floor_area
2299
+
2300
+
2301
+ def build_explicit_spatial_code(scene):
2302
+ """Build the selected explicit code.
2303
+
2304
+ Raw encoder inputs follow the original geometric V2 spatial-code construction. Canonical
2305
+ geometry keeps the compact-derived schema used by ground-truth and non-raw adapters.
2306
+ """
2307
+ raw_inputs = scene.get("raw_inputs")
2308
+ if raw_inputs is not None:
2309
+ return _build_reference_v2_spatial_code(raw_inputs)
2310
+
2311
+ compact_code, instances, stats, up_ax, up_vec, _ = build_compact_spatial_code(scene)
2312
+ code, floor_area = _explicit_from_compact(compact_code)
2313
+ return code, instances, stats, up_ax, up_vec, floor_area
2314
+
2315
+
2316
+ # ==========================================================================================
2317
+ # MODEL-AGNOSTIC ENTRY POINT
2318
+ # ==========================================================================================
2319
+
2320
+
2321
+ def build_spatial_code(scene, spatial_code_format="explicit"):
2322
+ """Build one selected spatial-code schema from canonical scene geometry.
2323
+
2324
+ Compact is built directly from raw depth/pose/mask bundles or canonical world-space
2325
+ geometry (build_compact_spatial_code() handles that duality). Explicit is always a
2326
+ derivation of compact (build_explicit_spatial_code() calls build_compact_spatial_code()
2327
+ first), so there is no separate raw/canonical branch for explicit any more.
2328
+ """
2329
+ if spatial_code_format == "compact":
2330
+ return build_compact_spatial_code(scene)
2331
+ if spatial_code_format != "explicit":
2332
+ raise ValueError(f"unknown spatial-code format {spatial_code_format!r}")
2333
+ return build_explicit_spatial_code(scene)
encoder/launch.py CHANGED
@@ -28,18 +28,20 @@ def _scenes():
28
  return list(dict.fromkeys(str(json.loads(line)["scene_name"]) for line in f))
29
 
30
 
31
- def _video_cache_files(scene):
32
- """Return full-video perception-cache files for one scene."""
33
  return (
34
- Path(config.video_da3_cache_file(scene)),
35
- Path(config.video_sam3_cache_file(scene)),
36
  )
37
 
38
 
39
- def _has_required_caches(scene, depth, input_selection, tracking, frame_count, videos=False):
 
 
40
  """Return whether all inference caches needed for encoding exist."""
41
- if videos:
42
- paths = _video_cache_files(scene)
43
  else:
44
  paths = (
45
  config.sam3_cache_file(scene, input_selection, tracking, frame_count),
@@ -48,12 +50,16 @@ def _has_required_caches(scene, depth, input_selection, tracking, frame_count, v
48
  return all(os.path.isfile(path) for path in paths)
49
 
50
 
51
- def _scenes_with_required_caches(depth, input_selection, tracking, frame_count, videos=False):
 
 
52
  """Return manifest scenes having every cache required by this encoder run."""
53
  return [
54
  scene
55
  for scene in _scenes()
56
- if _has_required_caches(scene, depth, input_selection, tracking, frame_count, videos)
 
 
57
  ]
58
 
59
 
@@ -97,8 +103,7 @@ def _worker(
97
  frame_count,
98
  rebuild,
99
  cpu_threads,
100
- spatial_code_format,
101
- videos,
102
  ):
103
  for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
104
  os.environ[variable] = str(cpu_threads)
@@ -133,8 +138,7 @@ def _worker(
133
  tracking,
134
  frame_count,
135
  rebuild,
136
- spatial_code_format,
137
- videos,
138
  )
139
  result_queue.put((scene, "done", f"{how} -> {path}"))
140
  except EmptySceneError:
@@ -145,11 +149,9 @@ def _worker(
145
 
146
  def _launch(args, selected):
147
  label = (
148
- f"{args.depth}/{args.tracking}/{args.input_selection}/"
149
- f"{args.spatial_code_format}"
150
- if args.videos
151
- else f"{args.depth}/{args.tracking}/{args.input_selection}/{args.frames}/"
152
- f"{args.spatial_code_format}"
153
  )
154
  pending = []
155
  completed = 0
@@ -160,8 +162,8 @@ def _launch(args, selected):
160
  args.depth,
161
  args.input_selection,
162
  args.tracking,
163
- args.frames,
164
- args.spatial_code_format,
165
  )
166
  )
167
  if output_exists and not args.rebuild:
@@ -202,11 +204,10 @@ def _launch(args, selected):
202
  args.depth,
203
  args.input_selection,
204
  args.tracking,
205
- args.frames,
206
  args.rebuild,
207
  cpu_threads,
208
- args.spatial_code_format,
209
- args.videos,
210
  ),
211
  )
212
  for _ in range(worker_count)
@@ -248,19 +249,14 @@ def main():
248
  choices=config.INPUT_SELECTIONS,
249
  dest="input_selection",
250
  )
251
- parser.add_argument("--frames", type=int, default=config.FRAMES_PER_VIDEO)
252
- parser.add_argument("--tracking", choices=config.TRACKING_MODES)
253
- parser.add_argument(
254
- "--format",
255
- choices=config.SPATIAL_CODE_FORMATS,
256
- default="explicit",
257
- dest="spatial_code_format",
258
- )
259
- parser.add_argument(
260
- "--videos",
261
  action="store_true",
262
- help="use full-video caches from caches/depth-anything-3/metric/uniform/video and caches/sam3/tracking/uniform/video",
263
  )
 
264
  parser.add_argument(
265
  "--workers",
266
  type=int,
@@ -269,19 +265,19 @@ def main():
269
  )
270
  parser.add_argument("--rebuild", action="store_true")
271
  args = parser.parse_args()
272
- if args.videos:
273
- args.depth = "metric"
 
 
 
 
 
274
  args.input_selection = config.VIDEO_INPUT_SELECTION
275
- args.tracking = "no tracking"
276
- else:
277
- if args.depth is None:
278
- parser.error("--depth is required unless --videos is used")
279
- if args.input_selection is None:
280
- parser.error("--input is required unless --videos is used")
281
- if args.tracking is None:
282
- parser.error("--tracking is required unless --videos is used")
283
- if args.frames < 1:
284
  parser.error("--frames must be positive")
 
285
  if args.workers < 0:
286
  parser.error("--workers must be positive or zero for automatic")
287
  selected = (
@@ -291,8 +287,8 @@ def main():
291
  args.depth,
292
  args.input_selection,
293
  args.tracking,
294
- args.frames,
295
- args.videos,
296
  )
297
  )
298
  if not selected:
 
28
  return list(dict.fromkeys(str(json.loads(line)["scene_name"]) for line in f))
29
 
30
 
31
+ def _video_cache_files(scene, depth, tracking):
32
+ """Return full-video perception-cache files for the selected axes."""
33
  return (
34
+ Path(config.video_da3_cache_file(scene, depth)),
35
+ Path(config.video_sam3_cache_file(scene, tracking)),
36
  )
37
 
38
 
39
+ def _has_required_caches(
40
+ scene, depth, input_selection, tracking, frame_count, video=False
41
+ ):
42
  """Return whether all inference caches needed for encoding exist."""
43
+ if video:
44
+ paths = _video_cache_files(scene, depth, tracking)
45
  else:
46
  paths = (
47
  config.sam3_cache_file(scene, input_selection, tracking, frame_count),
 
50
  return all(os.path.isfile(path) for path in paths)
51
 
52
 
53
+ def _scenes_with_required_caches(
54
+ depth, input_selection, tracking, frame_count, video=False
55
+ ):
56
  """Return manifest scenes having every cache required by this encoder run."""
57
  return [
58
  scene
59
  for scene in _scenes()
60
+ if _has_required_caches(
61
+ scene, depth, input_selection, tracking, frame_count, video
62
+ )
63
  ]
64
 
65
 
 
103
  frame_count,
104
  rebuild,
105
  cpu_threads,
106
+ video,
 
107
  ):
108
  for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
109
  os.environ[variable] = str(cpu_threads)
 
138
  tracking,
139
  frame_count,
140
  rebuild,
141
+ video,
 
142
  )
143
  result_queue.put((scene, "done", f"{how} -> {path}"))
144
  except EmptySceneError:
 
149
 
150
  def _launch(args, selected):
151
  label = (
152
+ f"{args.depth}/{args.tracking}/video"
153
+ if args.video
154
+ else f"{args.depth}/{args.tracking}/{args.input_selection}/{args.frames}"
 
 
155
  )
156
  pending = []
157
  completed = 0
 
162
  args.depth,
163
  args.input_selection,
164
  args.tracking,
165
+ args.frame_count,
166
+ "explicit",
167
  )
168
  )
169
  if output_exists and not args.rebuild:
 
204
  args.depth,
205
  args.input_selection,
206
  args.tracking,
207
+ args.frame_count,
208
  args.rebuild,
209
  cpu_threads,
210
+ args.video,
 
211
  ),
212
  )
213
  for _ in range(worker_count)
 
249
  choices=config.INPUT_SELECTIONS,
250
  dest="input_selection",
251
  )
252
+ input_mode = parser.add_mutually_exclusive_group(required=True)
253
+ input_mode.add_argument("--frames", type=int)
254
+ input_mode.add_argument(
255
+ "--video",
 
 
 
 
 
 
256
  action="store_true",
257
+ help="use full-video DA3 and SAM3 caches",
258
  )
259
+ parser.add_argument("--tracking", choices=config.TRACKING_MODES)
260
  parser.add_argument(
261
  "--workers",
262
  type=int,
 
265
  )
266
  parser.add_argument("--rebuild", action="store_true")
267
  args = parser.parse_args()
268
+ if args.depth is None:
269
+ parser.error("--depth is required")
270
+ if args.tracking is None:
271
+ parser.error("--tracking is required")
272
+ if args.video:
273
+ if args.input_selection is not None:
274
+ parser.error("--input cannot be used with --video")
275
  args.input_selection = config.VIDEO_INPUT_SELECTION
276
+ elif args.input_selection is None:
277
+ parser.error("--input is required with --frames")
278
+ if args.frames is not None and args.frames < 1:
 
 
 
 
 
 
279
  parser.error("--frames must be positive")
280
+ args.frame_count = args.frames
281
  if args.workers < 0:
282
  parser.error("--workers must be positive or zero for automatic")
283
  selected = (
 
287
  args.depth,
288
  args.input_selection,
289
  args.tracking,
290
+ args.frame_count,
291
+ args.video,
292
  )
293
  )
294
  if not selected:
encoder/render.py CHANGED
@@ -16,20 +16,14 @@ def build_spatial_code_for(
16
  tracking,
17
  frame_count=config.FRAMES_PER_VIDEO,
18
  rebuild=False,
19
- spatial_code_format="explicit",
20
- videos=False,
21
  da3_path=None,
22
  sam3_path=None,
23
  ):
24
  """Build a spatial code from cached or newly adapted scene geometry."""
25
- spatial_code_format = perceive.adapters.validate_spatial_code_format(
26
- spatial_code_format
27
- )
28
- if videos:
29
- depth = "metric"
30
  input_selection = config.VIDEO_INPUT_SELECTION
31
- tracking = "no tracking"
32
- kwargs = {"videos": videos}
33
  if da3_path is not None:
34
  kwargs["da3_path"] = da3_path
35
  if sam3_path is not None:
@@ -37,7 +31,7 @@ def build_spatial_code_for(
37
  geometry, how = perceive.cache_or_load(
38
  scene, depth, input_selection, tracking, frame_count, rebuild, **kwargs
39
  )
40
- code, *_ = geometry_math.build_spatial_code(geometry, spatial_code_format)
41
  return code, how
42
 
43
 
@@ -48,16 +42,13 @@ def write_spatial_code_for(
48
  tracking,
49
  frame_count=config.FRAMES_PER_VIDEO,
50
  rebuild=False,
51
- spatial_code_format="explicit",
52
- videos=False,
53
  da3_path=None,
54
  sam3_path=None,
55
  ):
56
  """Build and write one scene's spatial-code JSON."""
57
- if videos:
58
- depth = "metric"
59
  input_selection = config.VIDEO_INPUT_SELECTION
60
- tracking = "no tracking"
61
  code, how = build_spatial_code_for(
62
  scene,
63
  depth,
@@ -65,8 +56,7 @@ def write_spatial_code_for(
65
  tracking,
66
  frame_count,
67
  rebuild,
68
- spatial_code_format,
69
- videos,
70
  da3_path,
71
  sam3_path,
72
  )
@@ -76,7 +66,7 @@ def write_spatial_code_for(
76
  input_selection,
77
  tracking,
78
  frame_count,
79
- spatial_code_format,
80
  )
81
  os.makedirs(os.path.dirname(path), exist_ok=True)
82
  geometry_math.dump_spatial_code(code, path)
 
16
  tracking,
17
  frame_count=config.FRAMES_PER_VIDEO,
18
  rebuild=False,
19
+ video=False,
 
20
  da3_path=None,
21
  sam3_path=None,
22
  ):
23
  """Build a spatial code from cached or newly adapted scene geometry."""
24
+ if video:
 
 
 
 
25
  input_selection = config.VIDEO_INPUT_SELECTION
26
+ kwargs = {"video": video}
 
27
  if da3_path is not None:
28
  kwargs["da3_path"] = da3_path
29
  if sam3_path is not None:
 
31
  geometry, how = perceive.cache_or_load(
32
  scene, depth, input_selection, tracking, frame_count, rebuild, **kwargs
33
  )
34
+ code, *_ = geometry_math.build_spatial_code(geometry, "explicit")
35
  return code, how
36
 
37
 
 
42
  tracking,
43
  frame_count=config.FRAMES_PER_VIDEO,
44
  rebuild=False,
45
+ video=False,
 
46
  da3_path=None,
47
  sam3_path=None,
48
  ):
49
  """Build and write one scene's spatial-code JSON."""
50
+ if video:
 
51
  input_selection = config.VIDEO_INPUT_SELECTION
 
52
  code, how = build_spatial_code_for(
53
  scene,
54
  depth,
 
56
  tracking,
57
  frame_count,
58
  rebuild,
59
+ video,
 
60
  da3_path,
61
  sam3_path,
62
  )
 
66
  input_selection,
67
  tracking,
68
  frame_count,
69
+ "explicit",
70
  )
71
  os.makedirs(os.path.dirname(path), exist_ok=True)
72
  geometry_math.dump_spatial_code(code, path)
encoder/run.py CHANGED
@@ -29,6 +29,7 @@ from encoder import config # noqa: E402
29
  PROVENANCE_KEY = "source_provenance"
30
  PROVENANCE_VERSION = 1
31
 
 
32
  def _source_record(path):
33
  """Describe one native cache without copying its payload."""
34
  source = Path(path)
@@ -77,27 +78,27 @@ def _verify_source_provenance(provenance):
77
  )
78
 
79
 
80
- def _video_cache_files(scene):
81
- """Return the full-video DA3 + SAM3 cache pair."""
82
  return (
83
- config.video_da3_cache_file(scene),
84
- config.video_sam3_cache_file(scene),
85
  )
86
 
87
 
88
- def _effective_dimensions(depth, input_selection, tracking, videos):
89
- """Map full-video perception caches onto their fixed output branch."""
90
- if videos:
91
- return "metric", config.VIDEO_INPUT_SELECTION, "no tracking"
92
  return depth, input_selection, tracking
93
 
94
 
95
  def _cache_source_paths(
96
- scene, depth, input_selection, tracking, frame_count, videos, da3_path, sam3_path
97
  ):
98
  """Resolve the selected DA3/SAM3 source pair without changing adapter semantics."""
99
- if videos:
100
- default_da3, default_sam3 = _video_cache_files(scene)
101
  else:
102
  default_da3 = config.da3_cache_file(scene, depth, input_selection, frame_count)
103
  default_sam3 = config.sam3_cache_file(
@@ -107,12 +108,12 @@ def _cache_source_paths(
107
 
108
 
109
  def _combined_cache_file(
110
- scene, depth, input_selection, tracking, frame_count, videos, da3_path, sam3_path
111
  ):
112
  """Return a combined-cache path isolated by source cache format and explicit paths."""
113
- if not videos and da3_path is None and sam3_path is None:
114
  return config.cache_file(scene, depth, input_selection, tracking, frame_count)
115
- label = config.VIDEO_INPUT_SELECTION if videos else "custom"
116
  if da3_path is not None or sam3_path is not None:
117
  digest = hashlib.sha256()
118
  digest.update(str(da3_path or "").encode())
@@ -120,7 +121,7 @@ def _combined_cache_file(
120
  digest.update(str(sam3_path or "").encode())
121
  label = f"{label}-{digest.hexdigest()[:12]}"
122
  directory = config.CACHE_ROOT / config.MODEL / depth / tracking / label
123
- if label != config.VIDEO_INPUT_SELECTION:
124
  directory = directory / str(frame_count)
125
  return str(directory / f"{scene}.pkl.gz")
126
 
@@ -132,16 +133,16 @@ def cache_or_load(
132
  tracking,
133
  frame_count=config.FRAMES_PER_VIDEO,
134
  rebuild=False,
135
- videos=False,
136
  da3_path=None,
137
  sam3_path=None,
138
  ):
139
  """Return canonical geometry for one specific set of input dimensions."""
140
  depth, input_selection, tracking = _effective_dimensions(
141
- depth, input_selection, tracking, videos
142
  )
143
  path = _combined_cache_file(
144
- scene, depth, input_selection, tracking, frame_count, videos, da3_path, sam3_path
145
  )
146
  if os.path.exists(path) and not rebuild:
147
  with gzip.open(path, "rb") as stream:
@@ -153,7 +154,7 @@ def cache_or_load(
153
  # Legacy combined caches are rebuilt to attach exact source provenance.
154
 
155
  selected_da3_path, selected_sam3_path = _cache_source_paths(
156
- scene, depth, input_selection, tracking, frame_count, videos, da3_path, sam3_path
157
  )
158
  raw_cache = {
159
  "scene": scene,
@@ -178,7 +179,7 @@ def cache_or_load(
178
  "input": input_selection,
179
  "tracking": tracking,
180
  "frames": frame_count,
181
- "videos": bool(videos),
182
  }
183
  )
184
  _verify_source_provenance(geometry[PROVENANCE_KEY])
@@ -197,36 +198,35 @@ def main():
197
  choices=config.INPUT_SELECTIONS,
198
  dest="input_selection",
199
  )
200
- parser.add_argument("--frames", type=int, default=config.FRAMES_PER_VIDEO)
 
 
 
 
 
 
201
  parser.add_argument("--tracking", choices=config.TRACKING_MODES)
202
  parser.add_argument(
203
- "--format",
204
- choices=config.SPATIAL_CODE_FORMATS,
205
- default="explicit",
206
- dest="spatial_code_format",
207
  )
208
  parser.add_argument(
209
- "--videos",
210
- action="store_true",
211
- help="use full-video caches from caches/depth-anything-3/metric/uniform/video and caches/sam3/tracking/uniform/video",
212
  )
213
- parser.add_argument("--da3-path", default=None, help="override the selected DA3 cache path")
214
- parser.add_argument("--sam3-path", default=None, help="override the selected SAM3 cache path")
215
  parser.add_argument("--rebuild", action="store_true")
216
  args = parser.parse_args()
217
- if args.videos:
218
- args.depth = "metric"
 
 
 
 
 
219
  args.input_selection = config.VIDEO_INPUT_SELECTION
220
- args.tracking = "no tracking"
221
- else:
222
- if args.depth is None:
223
- parser.error("--depth is required unless --videos is used")
224
- if args.input_selection is None:
225
- parser.error("--input is required unless --videos is used")
226
- if args.tracking is None:
227
- parser.error("--tracking is required unless --videos is used")
228
- if args.frames < 1:
229
  parser.error("--frames must be positive")
 
230
  from encoder import render
231
 
232
  import cv2
@@ -246,16 +246,16 @@ def main():
246
  args.depth,
247
  args.input_selection,
248
  args.tracking,
249
- args.frames,
250
  args.rebuild,
251
- args.videos,
252
  args.da3_path,
253
  args.sam3_path,
254
  )
255
  count = sum(len(values) for values in geometry["instances"].values())
256
  print(
257
  f"[{args.scene}] depth={args.depth} input={args.input_selection} "
258
- f"frames={args.frames} tracking={args.tracking} videos={args.videos} cache={how} "
259
  f"classes={len(geometry['instances'])} instances={count}"
260
  )
261
  _, _, path = render.write_spatial_code_for(
@@ -263,10 +263,9 @@ def main():
263
  args.depth,
264
  args.input_selection,
265
  args.tracking,
266
- args.frames,
267
  False,
268
- args.spatial_code_format,
269
- args.videos,
270
  args.da3_path,
271
  args.sam3_path,
272
  )
 
29
  PROVENANCE_KEY = "source_provenance"
30
  PROVENANCE_VERSION = 1
31
 
32
+
33
  def _source_record(path):
34
  """Describe one native cache without copying its payload."""
35
  source = Path(path)
 
78
  )
79
 
80
 
81
+ def _video_cache_files(scene, depth, tracking):
82
+ """Return the full-video DA3 + SAM3 cache pair for the selected axes."""
83
  return (
84
+ config.video_da3_cache_file(scene, depth),
85
+ config.video_sam3_cache_file(scene, tracking),
86
  )
87
 
88
 
89
+ def _effective_dimensions(depth, input_selection, tracking, video):
90
+ """Map video input onto its path branch without changing other axes."""
91
+ if video:
92
+ return depth, config.VIDEO_INPUT_SELECTION, tracking
93
  return depth, input_selection, tracking
94
 
95
 
96
  def _cache_source_paths(
97
+ scene, depth, input_selection, tracking, frame_count, video, da3_path, sam3_path
98
  ):
99
  """Resolve the selected DA3/SAM3 source pair without changing adapter semantics."""
100
+ if video:
101
+ default_da3, default_sam3 = _video_cache_files(scene, depth, tracking)
102
  else:
103
  default_da3 = config.da3_cache_file(scene, depth, input_selection, frame_count)
104
  default_sam3 = config.sam3_cache_file(
 
108
 
109
 
110
  def _combined_cache_file(
111
+ scene, depth, input_selection, tracking, frame_count, video, da3_path, sam3_path
112
  ):
113
  """Return a combined-cache path isolated by source cache format and explicit paths."""
114
+ if da3_path is None and sam3_path is None:
115
  return config.cache_file(scene, depth, input_selection, tracking, frame_count)
116
+ label = config.VIDEO_INPUT_SELECTION if video else "custom"
117
  if da3_path is not None or sam3_path is not None:
118
  digest = hashlib.sha256()
119
  digest.update(str(da3_path or "").encode())
 
121
  digest.update(str(sam3_path or "").encode())
122
  label = f"{label}-{digest.hexdigest()[:12]}"
123
  directory = config.CACHE_ROOT / config.MODEL / depth / tracking / label
124
+ if not video:
125
  directory = directory / str(frame_count)
126
  return str(directory / f"{scene}.pkl.gz")
127
 
 
133
  tracking,
134
  frame_count=config.FRAMES_PER_VIDEO,
135
  rebuild=False,
136
+ video=False,
137
  da3_path=None,
138
  sam3_path=None,
139
  ):
140
  """Return canonical geometry for one specific set of input dimensions."""
141
  depth, input_selection, tracking = _effective_dimensions(
142
+ depth, input_selection, tracking, video
143
  )
144
  path = _combined_cache_file(
145
+ scene, depth, input_selection, tracking, frame_count, video, da3_path, sam3_path
146
  )
147
  if os.path.exists(path) and not rebuild:
148
  with gzip.open(path, "rb") as stream:
 
154
  # Legacy combined caches are rebuilt to attach exact source provenance.
155
 
156
  selected_da3_path, selected_sam3_path = _cache_source_paths(
157
+ scene, depth, input_selection, tracking, frame_count, video, da3_path, sam3_path
158
  )
159
  raw_cache = {
160
  "scene": scene,
 
179
  "input": input_selection,
180
  "tracking": tracking,
181
  "frames": frame_count,
182
+ "video": bool(video),
183
  }
184
  )
185
  _verify_source_provenance(geometry[PROVENANCE_KEY])
 
198
  choices=config.INPUT_SELECTIONS,
199
  dest="input_selection",
200
  )
201
+ input_mode = parser.add_mutually_exclusive_group(required=True)
202
+ input_mode.add_argument("--frames", type=int)
203
+ input_mode.add_argument(
204
+ "--video",
205
+ action="store_true",
206
+ help="use full-video DA3 and SAM3 caches",
207
+ )
208
  parser.add_argument("--tracking", choices=config.TRACKING_MODES)
209
  parser.add_argument(
210
+ "--da3-path", default=None, help="override the selected DA3 cache path"
 
 
 
211
  )
212
  parser.add_argument(
213
+ "--sam3-path", default=None, help="override the selected SAM3 cache path"
 
 
214
  )
 
 
215
  parser.add_argument("--rebuild", action="store_true")
216
  args = parser.parse_args()
217
+ if args.depth is None:
218
+ parser.error("--depth is required")
219
+ if args.tracking is None:
220
+ parser.error("--tracking is required")
221
+ if args.video:
222
+ if args.input_selection is not None:
223
+ parser.error("--input cannot be used with --video")
224
  args.input_selection = config.VIDEO_INPUT_SELECTION
225
+ elif args.input_selection is None:
226
+ parser.error("--input is required with --frames")
227
+ if args.frames is not None and args.frames < 1:
 
 
 
 
 
 
228
  parser.error("--frames must be positive")
229
+ frame_count = args.frames
230
  from encoder import render
231
 
232
  import cv2
 
246
  args.depth,
247
  args.input_selection,
248
  args.tracking,
249
+ frame_count,
250
  args.rebuild,
251
+ args.video,
252
  args.da3_path,
253
  args.sam3_path,
254
  )
255
  count = sum(len(values) for values in geometry["instances"].values())
256
  print(
257
  f"[{args.scene}] depth={args.depth} input={args.input_selection} "
258
+ f"frames={args.frames} tracking={args.tracking} video={args.video} cache={how} "
259
  f"classes={len(geometry['instances'])} instances={count}"
260
  )
261
  _, _, path = render.write_spatial_code_for(
 
263
  args.depth,
264
  args.input_selection,
265
  args.tracking,
266
+ frame_count,
267
  False,
268
+ args.video,
 
269
  args.da3_path,
270
  args.sam3_path,
271
  )
harness/A/launch.py CHANGED
@@ -33,6 +33,7 @@ from harness.A import ( # noqa: E402
33
  MAX_NEW_TOKENS,
34
  )
35
  from harness.A import models as vlm_models # noqa: E402
 
36
  from inference.launch import available_cpu_count, visible_gpus # noqa: E402
37
 
38
 
@@ -58,14 +59,13 @@ def _worker(
58
  model,
59
  frame_selection,
60
  frame_count,
 
61
  results_dir,
62
  gpu,
63
  cpu_threads,
64
  extended,
65
  reasoning_budget,
66
  force_budget,
67
- truncated_budget,
68
- thinking,
69
  ):
70
  if gpu is not None:
71
  os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
@@ -79,8 +79,6 @@ def _worker(
79
  load_error = None
80
  try:
81
  adapter = vlm_models.get_adapter(model)
82
- if thinking and not adapter.set_thinking(True):
83
- raise ValueError(f"{model} has no native thinking mode to enable")
84
  adapter.load_model("cuda:0" if gpu is not None else "cpu")
85
  except Exception:
86
  load_error = traceback.format_exc()
@@ -96,14 +94,13 @@ def _worker(
96
  model,
97
  frame_selection=frame_selection,
98
  frame_count=frame_count,
 
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
- raw_budget=truncated_budget,
106
- thinking=thinking,
107
  )
108
  mean_score = (
109
  sum(r["score"] for r in answered) / len(answered) if answered else None
@@ -120,31 +117,23 @@ def launch(
120
  frame_selection,
121
  frame_count,
122
  selected,
 
123
  results_dir=None,
124
  rebuild=False,
125
- extended=False,
126
  reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
127
  force_budget=MAX_NEW_TOKENS,
128
- truncated_budget=None,
129
- thinking=False,
130
  ):
131
- """Answer every question for ``selected`` scenes, sharded across every visible GPU.
132
-
133
- ``truncated_budget`` (mutually exclusive with ``extended``) runs the raw-budget
134
- arm: base-protocol mechanics (single generation, no forced rescue) at this token
135
- cap, under its own "truncated/<budget>" path segment -- see harness.A.run.run."""
136
- if extended and truncated_budget is not None:
137
- raise ValueError("extended and truncated_budget are mutually exclusive")
138
- protocol = (
139
- f"{reasoning_budget}"
140
- if extended
141
- else f"truncated/{truncated_budget}" if truncated_budget is not None else "base"
142
- )
143
- condition = f"{model}/{protocol}/{frame_selection}/{frame_count}"
144
  run = _load_run_module()
145
- root = run.results_dir_for(
146
- model, protocol, frame_selection, frame_count, results_dir
147
- )
148
  pending = []
149
  completed = 0
150
  for scene in selected:
@@ -192,14 +181,13 @@ def launch(
192
  model,
193
  frame_selection,
194
  frame_count,
 
195
  results_dir,
196
  gpu,
197
  cpu_threads,
198
  extended,
199
  reasoning_budget,
200
  force_budget,
201
- truncated_budget,
202
- thinking,
203
  ),
204
  )
205
  for gpu in assignments
@@ -236,36 +224,26 @@ def main():
236
  parser.add_argument("--model", required=True, choices=vlm_models.available_models())
237
  parser.add_argument(
238
  "--frame-selection",
239
- default=DEFAULT_FRAME_SELECTION,
240
  choices=FRAME_SELECTIONS,
241
  dest="frame_selection",
242
  )
243
- parser.add_argument("--frames", type=int, default=FRAMES_PER_VIDEO)
 
 
244
  parser.add_argument("--results-dir", default=None)
245
  parser.add_argument("--rebuild", action="store_true")
246
  parser.add_argument(
247
- "--extended",
248
- action="store_true",
249
- help=(
250
- f"use a {EXTENDED_MAX_NEW_TOKENS}-token reasoning budget instead of the fixed "
251
- f"{MAX_NEW_TOKENS}-token VSI-Bench protocol, with a short forced second call "
252
- "only if the model doesn't conclude within it"
253
- ),
254
- )
255
- parser.add_argument(
256
- "--thinking",
257
- action="store_true",
258
- help="enable the model's native thinking mode where supported; errors on models without the switch",
259
  )
260
- parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
261
- parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
262
  parser.add_argument(
263
- "--truncated-budget",
264
  type=int,
265
  default=None,
266
- help="raw-budget arm: base-protocol mechanics (single generation, no forced "
267
- "rescue) at this token cap, under its own truncated/<budget> path segment "
268
- "(mutually exclusive with --extended)",
269
  )
270
  args = parser.parse_args()
271
  if args.scene and args.scenes:
@@ -277,28 +255,26 @@ def main():
277
  selected = list(dict.fromkeys(selected))
278
  else:
279
  selected = [args.scene] if args.scene else scenes()
280
- if args.frames < 1:
281
- parser.error("--frames must be positive")
282
- if args.reasoning_budget < 1:
283
- parser.error("--reasoning-budget must be positive")
284
- if args.force_budget < 1:
285
- parser.error("--force-budget must be positive")
286
- if args.truncated_budget is not None and args.truncated_budget < 1:
287
- parser.error("--truncated-budget must be positive")
288
- if args.extended and args.truncated_budget is not None:
289
- parser.error("--extended and --truncated-budget are mutually exclusive")
290
  launch(
291
  args.model,
292
  args.frame_selection,
293
  args.frames,
294
  selected,
 
295
  results_dir=args.results_dir,
296
  rebuild=args.rebuild,
297
- extended=args.extended,
298
- thinking=args.thinking,
299
  reasoning_budget=args.reasoning_budget,
300
  force_budget=args.force_budget,
301
- truncated_budget=args.truncated_budget,
302
  )
303
 
304
 
 
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
 
 
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)
 
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()
 
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
 
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:
 
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
 
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:
 
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
 
harness/A/sweep.py CHANGED
@@ -22,6 +22,7 @@ if str(WORKSPACE_ROOT) not in sys.path:
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
 
26
 
27
  def _parse_csv_choice(value, valid, flag):
@@ -72,23 +73,23 @@ def sweep(
72
  frame_selections,
73
  frame_counts,
74
  selected_scenes,
 
75
  results_dir=None,
76
  rebuild=False,
77
- thinking=False,
78
- extended=False,
79
  reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
80
- truncated_budget=None,
81
  ):
82
  """Run every (model, frame_selection, frame_count) triple across all visible GPUs."""
83
- plan = build_plan(models, frame_selections, frame_counts)
84
- protocol = (
85
- f"{reasoning_budget}"
86
- if extended
87
- else f"truncated/{truncated_budget}" if truncated_budget is not None else "base"
88
  )
89
  for index, (model, frame_selection, frame_count) in enumerate(plan, start=1):
90
  print(
91
- f"=== sweep {index}/{len(plan)}: {model}/{protocol}/{frame_selection}/{frame_count} ===",
 
 
92
  flush=True,
93
  )
94
  harness_launch.launch(
@@ -96,12 +97,11 @@ def sweep(
96
  frame_selection,
97
  frame_count,
98
  selected_scenes,
 
99
  results_dir=results_dir,
100
  rebuild=rebuild,
101
- thinking=thinking,
102
  extended=extended,
103
  reasoning_budget=reasoning_budget,
104
- truncated_budget=truncated_budget,
105
  )
106
 
107
 
@@ -119,57 +119,46 @@ def main():
119
  )
120
  parser.add_argument(
121
  "--frame-selections",
122
- required=True,
123
  dest="frame_selections",
124
  help=f"comma-separated selections (or 'all'); one of {FRAME_SELECTIONS}",
125
  )
126
- parser.add_argument(
127
- "--frames",
128
- required=True,
129
- help="comma-separated frame counts, e.g. 16,32,64",
130
  )
 
131
  parser.add_argument("--results-dir", default=None)
132
  parser.add_argument("--rebuild", action="store_true")
133
- parser.add_argument(
134
- "--extended",
135
- action="store_true",
136
- help="run the whole sweep under the extended protocol instead of the fixed "
137
- "16-token VSI-Bench protocol (the same flag harness.A.run/launch take)",
138
- )
139
- parser.add_argument(
140
- "--thinking",
141
- action="store_true",
142
- help="enable the model's native thinking mode where supported; errors on models without the switch",
143
- )
144
  parser.add_argument(
145
  "--reasoning-budget",
146
  type=int,
147
- default=EXTENDED_MAX_NEW_TOKENS,
148
  dest="reasoning_budget",
149
- help="extended-protocol first-pass budget (the calibrated value from "
150
  "analysis/preregistration.md, e.g. 512)",
151
  )
152
- parser.add_argument(
153
- "--truncated-budget",
154
- type=int,
155
- default=None,
156
- help="raw-budget arm: base-protocol mechanics (single generation, no forced "
157
- "rescue) at this token cap (mutually exclusive with --extended)",
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.extended and args.truncated_budget is not None:
163
- parser.error("--extended and --truncated-budget are mutually exclusive")
164
 
165
  try:
166
  models = _parse_csv_choice(
167
  args.models, vlm_models.available_models(), "--models"
168
  )
169
- frame_selections = _parse_csv_choice(
170
- args.frame_selections, FRAME_SELECTIONS, "--frame-selections"
171
- )
172
- frame_counts = _parse_frame_counts(args.frames)
 
 
 
 
 
 
 
 
173
  except ValueError as exc:
174
  parser.error(str(exc))
175
 
@@ -186,12 +175,11 @@ def main():
186
  frame_selections,
187
  frame_counts,
188
  selected,
 
189
  results_dir=args.results_dir,
190
  rebuild=args.rebuild,
191
- thinking=args.thinking,
192
- extended=args.extended,
193
  reasoning_budget=args.reasoning_budget,
194
- truncated_budget=args.truncated_budget,
195
  )
196
 
197
 
 
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):
 
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(
 
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
 
 
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
 
 
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
 
harness/B/__init__.py CHANGED
@@ -1,4 +1,4 @@
1
- """Harness B: route a scene's on-disk spatial code (explicit or compact) -- as TEXT,
2
  no video frames -- to all three models, for every VSI-Bench question.
3
 
4
  Reuses harness.A's model registry/adapters and fixed generation protocol exactly; only
@@ -24,8 +24,8 @@ from harness.A import (
24
  WORKSPACE_ROOT,
25
  )
26
 
27
- # Same two on-disk spatial-code schemas encoder/geometric.py can build.
28
- SPATIAL_CODE_FORMATS = ("explicit", "compact")
29
  DEFAULT_SPATIAL_CODE_FORMAT = "explicit"
30
 
31
  # Same vocabulary as inference.SAM3_FRAME_SELECTIONS / harness.A.FRAME_SELECTIONS --
 
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
 
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 --
harness/B/launch.py CHANGED
@@ -25,6 +25,7 @@ if str(WORKSPACE_ROOT) not in sys.path:
25
 
26
  from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402
27
  from harness.A import models as vlm_models # noqa: E402
 
28
  from harness.A.launch import scenes # noqa: E402
29
  from harness.B import ( # noqa: E402
30
  DEFAULT_DEPTH,
@@ -34,7 +35,6 @@ from harness.B import ( # noqa: E402
34
  DEPTH_VARIANTS,
35
  FRAMES_PER_VIDEO,
36
  INPUT_SELECTIONS,
37
- SPATIAL_CODE_FORMATS,
38
  TRACKING_MODES,
39
  )
40
  from inference.launch import available_cpu_count, visible_gpus # noqa: E402
@@ -55,6 +55,7 @@ def _worker(
55
  spatial_code_format,
56
  input_selection,
57
  frame_count,
 
58
  depth,
59
  tracking,
60
  results_dir,
@@ -64,8 +65,6 @@ def _worker(
64
  reasoning_budget,
65
  force_budget,
66
  question_ids,
67
- thinking,
68
- raw_budget,
69
  ):
70
  if gpu is not None:
71
  os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
@@ -76,8 +75,6 @@ def _worker(
76
  load_error = None
77
  try:
78
  adapter = vlm_models.get_adapter(model)
79
- if thinking and not adapter.set_thinking(True):
80
- raise ValueError(f"{model} has no native thinking mode to enable")
81
  adapter.load_model("cuda:0" if gpu is not None else "cpu")
82
  except Exception:
83
  load_error = traceback.format_exc()
@@ -94,6 +91,7 @@ def _worker(
94
  spatial_code_format=spatial_code_format,
95
  input_selection=input_selection,
96
  frame_count=frame_count,
 
97
  depth=depth,
98
  tracking=tracking,
99
  scene=scene,
@@ -103,7 +101,6 @@ def _worker(
103
  reasoning_budget=reasoning_budget,
104
  force_budget=force_budget,
105
  question_ids=question_ids,
106
- raw_budget=raw_budget,
107
  )
108
  # thinking is applied on the adapter above, not passed to run() -- the
109
  # worker owns the adapter, run() must not re-toggle it.
@@ -123,6 +120,7 @@ def launch(
123
  input_selection,
124
  frame_count,
125
  selected,
 
126
  depth=DEFAULT_DEPTH,
127
  tracking=DEFAULT_TRACKING,
128
  results_dir=None,
@@ -131,31 +129,20 @@ def launch(
131
  reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
132
  force_budget=MAX_NEW_TOKENS,
133
  question_ids=None,
134
- thinking=False,
135
- raw_budget=None,
136
  ):
137
  """Answer every question for ``selected`` scenes, sharded across every visible GPU.
138
- ``question_ids``, when given, restricts every scene to that question subset (the
139
- calibration pilot's per-category sample) -- the skip check honors the same subset.
140
-
141
- ``raw_budget`` (mutually exclusive with ``extended``) runs the raw-budget arm:
142
- base-protocol mechanics at this token cap, under its own truncated/<budget> path
143
- segment -- see harness.B.run.run."""
144
- if extended and raw_budget is not None:
145
- raise ValueError("extended and raw_budget are mutually exclusive")
146
- protocol = (
147
- f"{reasoning_budget}"
148
- if extended
149
- else f"truncated/{raw_budget}" if raw_budget is not None else "base"
150
- )
151
- condition = (
152
- f"{model}/{protocol}/{spatial_code_format}/{depth}/{tracking}"
153
- f"/{input_selection}/{frame_count}"
154
- )
155
  run = _load_run_module()
156
  root = run.results_dir_for(
157
  model,
158
- protocol,
159
  spatial_code_format,
160
  depth,
161
  tracking,
@@ -213,6 +200,7 @@ def launch(
213
  spatial_code_format,
214
  input_selection,
215
  frame_count,
 
216
  depth,
217
  tracking,
218
  results_dir,
@@ -222,8 +210,6 @@ def launch(
222
  reasoning_budget,
223
  force_budget,
224
  question_ids,
225
- thinking,
226
- raw_budget,
227
  ),
228
  )
229
  for gpu in assignments
@@ -258,43 +244,30 @@ def main():
258
  help="comma-separated scenes (cannot be combined with positional scene)",
259
  )
260
  parser.add_argument("--model", required=True, choices=vlm_models.available_models())
261
- parser.add_argument(
262
- "--spatial-code-format",
263
- default=DEFAULT_SPATIAL_CODE_FORMAT,
264
- choices=SPATIAL_CODE_FORMATS,
265
- dest="spatial_code_format",
266
- )
267
  parser.add_argument(
268
  "--input-selection",
269
- default=DEFAULT_INPUT_SELECTION,
270
  choices=INPUT_SELECTIONS,
271
  dest="input_selection",
272
  )
273
- parser.add_argument("--frames", type=int, default=FRAMES_PER_VIDEO)
 
 
274
  parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS)
275
  parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES)
276
  parser.add_argument("--results-dir", default=None)
277
  parser.add_argument("--rebuild", action="store_true")
278
  parser.add_argument(
279
- "--base-protocol",
280
- action="store_true",
281
- help="run harness.A's exact fixed 16-token protocol instead of the extended default",
282
- )
283
- parser.add_argument(
284
- "--thinking",
285
- action="store_true",
286
- help="enable native thinking mode (Qwen only; pair with an explicit "
287
- "--results-dir)",
288
  )
289
- parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
290
- parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
291
  parser.add_argument(
292
- "--truncated-budget",
293
  type=int,
294
  default=None,
295
- help="raw-budget arm: base-protocol mechanics (single generation, no forced "
296
- "rescue) at this token cap instead of the hardcoded 16 (mutually exclusive "
297
- "with --base-protocol)",
298
  )
299
  args = parser.parse_args()
300
  if args.scene and args.scenes:
@@ -306,31 +279,29 @@ def main():
306
  selected = list(dict.fromkeys(selected))
307
  else:
308
  selected = [args.scene] if args.scene else scenes()
309
- if args.frames < 1:
310
- parser.error("--frames must be positive")
311
- if args.reasoning_budget < 1:
312
- parser.error("--reasoning-budget must be positive")
313
- if args.force_budget < 1:
314
- parser.error("--force-budget must be positive")
315
- if args.truncated_budget is not None and args.truncated_budget < 1:
316
- parser.error("--truncated-budget must be positive")
317
- if args.base_protocol and args.truncated_budget is not None:
318
- parser.error("--base-protocol and --truncated-budget are mutually exclusive")
319
  launch(
320
  args.model,
321
- args.spatial_code_format,
322
  args.input_selection,
323
  args.frames,
324
  selected,
 
325
  depth=args.depth,
326
  tracking=args.tracking,
327
  results_dir=args.results_dir,
328
  rebuild=args.rebuild,
329
- extended=not args.base_protocol and args.truncated_budget is None,
330
- raw_budget=args.truncated_budget,
331
  reasoning_budget=args.reasoning_budget,
332
  force_budget=args.force_budget,
333
- thinking=args.thinking,
334
  )
335
 
336
 
 
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,
 
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
 
55
  spatial_code_format,
56
  input_selection,
57
  frame_count,
58
+ video,
59
  depth,
60
  tracking,
61
  results_dir,
 
65
  reasoning_budget,
66
  force_budget,
67
  question_ids,
 
 
68
  ):
69
  if gpu is not None:
70
  os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
 
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()
 
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,
 
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.
 
120
  input_selection,
121
  frame_count,
122
  selected,
123
+ video=False,
124
  depth=DEFAULT_DEPTH,
125
  tracking=DEFAULT_TRACKING,
126
  results_dir=None,
 
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,
 
200
  spatial_code_format,
201
  input_selection,
202
  frame_count,
203
+ video,
204
  depth,
205
  tracking,
206
  results_dir,
 
210
  reasoning_budget,
211
  force_budget,
212
  question_ids,
 
 
213
  ),
214
  )
215
  for gpu in assignments
 
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:
 
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
 
harness/B/run.py CHANGED
@@ -21,6 +21,11 @@ if str(WORKSPACE_ROOT) not in sys.path:
21
 
22
  from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402
23
  from harness.A import models as vlm_models # noqa: E402
 
 
 
 
 
24
  from harness.A.run import _scalar_score, load_questions, vsi_official_eval # noqa: E402
25
  from harness.B import ( # noqa: E402
26
  DEFAULT_DEPTH,
@@ -31,7 +36,6 @@ from harness.B import ( # noqa: E402
31
  FRAMES_PER_VIDEO,
32
  INPUT_SELECTIONS,
33
  RESULTS_DIR,
34
- SPATIAL_CODE_FORMATS,
35
  TRACKING_MODES,
36
  )
37
  from harness.B import prompts as code_prompts # noqa: E402
@@ -48,23 +52,17 @@ def results_dir_for(
48
  frame_count,
49
  results_dir=None,
50
  ):
51
- """Return the result root isolated by model + protocol + spatial-code-format +
52
  depth + tracking + input + frames. ``protocol`` is "base" (16-token) or
53
  "extended-<reasoning budget>" (e.g. "extended-512") -- a real path segment, so
54
  records from different protocols OR different reasoning budgets can never collide
55
  on disk."""
56
  if results_dir is not None:
57
  return Path(results_dir)
58
- return (
59
- RESULTS_DIR
60
- / model
61
- / protocol
62
- / spatial_code_format
63
- / depth
64
- / tracking
65
- / input_selection
66
- / str(frame_count)
67
- )
68
 
69
 
70
  def _build_record(
@@ -80,9 +78,14 @@ def _build_record(
80
  "condition": (
81
  f"{code_info['protocol']}:{code_info['spatial_code_format']}:"
82
  f"{code_info['depth']}:{code_info['tracking']}:"
83
- f"{code_info['input_selection']}:{code_info['frame_count']}"
 
 
 
 
84
  ),
85
  "protocol": code_info["protocol"],
 
86
  "spatial_code_format": code_info["spatial_code_format"],
87
  "input_selection": code_info["input_selection"],
88
  "frame_count": code_info["frame_count"],
@@ -158,6 +161,7 @@ def run(
158
  spatial_code_format=DEFAULT_SPATIAL_CODE_FORMAT,
159
  input_selection=DEFAULT_INPUT_SELECTION,
160
  frame_count=FRAMES_PER_VIDEO,
 
161
  depth=DEFAULT_DEPTH,
162
  tracking=DEFAULT_TRACKING,
163
  scene=None,
@@ -172,8 +176,6 @@ def run(
172
  reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
173
  force_budget=MAX_NEW_TOKENS,
174
  question_ids=None,
175
- thinking=False,
176
- raw_budget=None,
177
  ):
178
  """Answer every matching question with one model, given its scene's spatial code as
179
  text (no video frames). Each question's full record is written to its own JSON file
@@ -187,17 +189,15 @@ def run(
187
  (plain ``adapter.answer``), so the protocol x representation grid can be measured
188
  with the identical generation mechanism in every cell.
189
 
190
- ``raw_budget`` (mutually exclusive with ``extended``) runs the raw-budget arm
191
- (analysis/preregistration.md): base-protocol mechanics (single generation, no
192
- forced rescue) at this token cap instead of the hardcoded 16, under its own
193
- "truncated/<budget>" path segment.
194
-
195
  Pass a pre-loaded ``adapter`` (as harness.B.launch's persistent per-GPU workers do)
196
  to reuse one already-loaded model across many calls; the caller then owns unloading
197
  it. Without one, ``run`` loads and unloads its own adapter, same as harness.A.
198
  """
199
- if extended and raw_budget is not None:
200
- raise ValueError("extended and raw_budget are mutually exclusive")
 
 
 
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]
@@ -206,13 +206,12 @@ def run(
206
  owns_adapter = adapter is None
207
  if owns_adapter:
208
  adapter = vlm_models.get_adapter(model)
209
- if thinking and not adapter.set_thinking(True):
210
- raise ValueError(f"{model} has no native thinking mode to enable")
211
  adapter.load_model(device)
212
  code_cache = {}
213
  results = []
214
  try:
215
  for row in rows:
 
216
  scene_id = row["scene_name"]
217
  if scene_id not in code_cache:
218
  code, path = spatial_codes.load_spatial_code(
@@ -238,8 +237,8 @@ def run(
238
  reasoning_budget=reasoning_budget,
239
  force_budget=force_budget,
240
  )
241
- if extended
242
- else adapter.answer([], prompt, max_new_tokens=raw_budget)
243
  )
244
  doc = {
245
  "question_type": row["question_type"],
@@ -250,11 +249,7 @@ def run(
250
  )["vsibench_score"]
251
  metric_name, score = _scalar_score(row["question_type"], score_doc)
252
  code_info = {
253
- "protocol": (
254
- f"{reasoning_budget}"
255
- if extended
256
- else f"truncated/{raw_budget}" if raw_budget is not None else "base"
257
- ),
258
  "spatial_code_format": spatial_code_format,
259
  "input_selection": input_selection,
260
  "frame_count": frame_count,
@@ -298,19 +293,15 @@ def main():
298
  parser = argparse.ArgumentParser()
299
  parser.add_argument("--model", required=True, choices=vlm_models.available_models())
300
  parser.add_argument("--scene", default=None, help="restrict to one VSI-Bench scene")
301
- parser.add_argument(
302
- "--spatial-code-format",
303
- default=DEFAULT_SPATIAL_CODE_FORMAT,
304
- choices=SPATIAL_CODE_FORMATS,
305
- dest="spatial_code_format",
306
- )
307
  parser.add_argument(
308
  "--input-selection",
309
- default=DEFAULT_INPUT_SELECTION,
310
  choices=INPUT_SELECTIONS,
311
  dest="input_selection",
312
  )
313
- parser.add_argument("--frames", type=int, default=FRAMES_PER_VIDEO)
 
 
314
  parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS)
315
  parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES)
316
  parser.add_argument(
@@ -320,8 +311,8 @@ def main():
320
  parser.add_argument(
321
  "--results-dir",
322
  default=None,
323
- help="override the default results/B/<model>/<protocol>/<format>/"
324
- "<depth>/<tracking>/<input>/<frames> root",
325
  )
326
  parser.add_argument(
327
  "--no-write",
@@ -329,44 +320,33 @@ def main():
329
  help="skip writing per-question JSON files; print/score only",
330
  )
331
  parser.add_argument(
332
- "--thinking",
333
- action="store_true",
334
- help="enable the model's native thinking mode (Qwen only; errors on models "
335
- "without the switch; pair with an explicit --results-dir)",
336
- )
337
- parser.add_argument(
338
- "--base-protocol",
339
- action="store_true",
340
- help="run harness.A's exact fixed 16-token protocol (plain answer()) instead of "
341
- "the extended 2048-token default",
342
  )
343
- parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
344
- parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
345
  parser.add_argument(
346
- "--truncated-budget",
347
  type=int,
348
  default=None,
349
- help="raw-budget arm: base-protocol mechanics (single generation, no forced "
350
- "rescue) at this token cap instead of the hardcoded 16 (mutually exclusive "
351
- "with --base-protocol)",
352
  )
353
  args = parser.parse_args()
354
- if args.frames < 1:
355
- parser.error("--frames must be positive")
356
- if args.reasoning_budget < 1:
357
- parser.error("--reasoning-budget must be positive")
358
- if args.force_budget < 1:
359
- parser.error("--force-budget must be positive")
360
- if args.truncated_budget is not None and args.truncated_budget < 1:
361
- parser.error("--truncated-budget must be positive")
362
- if args.base_protocol and args.truncated_budget is not None:
363
- parser.error("--base-protocol and --truncated-budget are mutually exclusive")
364
-
365
  results = run(
366
  args.model,
367
- spatial_code_format=args.spatial_code_format,
368
  input_selection=args.input_selection,
369
  frame_count=args.frames,
 
370
  depth=args.depth,
371
  tracking=args.tracking,
372
  scene=args.scene,
@@ -374,9 +354,7 @@ def main():
374
  device=args.device,
375
  results_dir=args.results_dir,
376
  write_results=not args.no_write,
377
- extended=not args.base_protocol and args.truncated_budget is None,
378
- raw_budget=args.truncated_budget,
379
- thinking=args.thinking,
380
  reasoning_budget=args.reasoning_budget,
381
  force_budget=args.force_budget,
382
  )
 
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,
 
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
 
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(
 
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"],
 
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,
 
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
 
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]
 
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(
 
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"],
 
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,
 
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(
 
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",
 
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,
 
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
  )
harness/B/spatial_codes.py CHANGED
@@ -1,4 +1,4 @@
1
- """Load one scene's on-disk spatial code (explicit or compact) as plain JSON.
2
 
3
  No solver-side adaptation (symbolic.adapters.adapt_spatial_code): the model is shown
4
  literally the same file encoder/geometric.py wrote to disk -- schema legend included --
 
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 --
harness/B/sweep.py CHANGED
@@ -1,4 +1,4 @@
1
- """Sweep any set of models x spatial-code-formats x depths x trackings x
2
  input-selections x frame-counts.
3
 
4
  Every (model, spatial_code_format, depth, tracking, input_selection, frame_count)
@@ -22,14 +22,15 @@ 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 EXTENDED_MAX_NEW_TOKENS # noqa: E402
26
  from harness.A.sweep import _parse_csv_choice, _parse_frame_counts # noqa: E402
27
  from harness.B import ( # noqa: E402
28
  DEFAULT_DEPTH,
 
29
  DEFAULT_TRACKING,
30
  DEPTH_VARIANTS,
31
  INPUT_SELECTIONS,
32
- SPATIAL_CODE_FORMATS,
33
  TRACKING_MODES,
34
  )
35
  from harness.B import launch as harness_launch # noqa: E402
@@ -58,24 +59,18 @@ def sweep(
58
  input_selections,
59
  frame_counts,
60
  selected_scenes,
 
61
  depths=(DEFAULT_DEPTH,),
62
  trackings=(DEFAULT_TRACKING,),
63
  results_dir=None,
64
  rebuild=False,
65
- thinking=False,
66
  extended=True,
67
  reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
68
- raw_budget=None,
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
- protocol = (
75
- f"{reasoning_budget}"
76
- if extended
77
- else f"truncated/{raw_budget}" if raw_budget is not None else "base"
78
- )
79
  for index, (
80
  model,
81
  spatial_code_format,
@@ -85,8 +80,10 @@ def sweep(
85
  frame_count,
86
  ) in enumerate(plan, start=1):
87
  print(
88
- f"=== sweep {index}/{len(plan)}: {model}/{protocol}/"
89
- f"{spatial_code_format}/{depth}/{tracking}/{input_selection}/{frame_count} ===",
 
 
90
  flush=True,
91
  )
92
  harness_launch.launch(
@@ -95,14 +92,13 @@ def sweep(
95
  input_selection,
96
  frame_count,
97
  selected_scenes,
 
98
  depth=depth,
99
  tracking=tracking,
100
  results_dir=results_dir,
101
  rebuild=rebuild,
102
- thinking=thinking,
103
  extended=extended,
104
  reasoning_budget=reasoning_budget,
105
- raw_budget=raw_budget,
106
  )
107
 
108
 
@@ -118,21 +114,17 @@ def main():
118
  required=True,
119
  help=f"comma-separated models (or 'all'); one of {vlm_models.available_models()}",
120
  )
121
- parser.add_argument(
122
- "--spatial-code-formats",
123
- required=True,
124
- dest="spatial_code_formats",
125
- help=f"comma-separated formats (or 'all'); one of {SPATIAL_CODE_FORMATS}",
126
- )
127
  parser.add_argument(
128
  "--input-selections",
129
- required=True,
130
  dest="input_selections",
131
  help=f"comma-separated selections (or 'all'); one of {INPUT_SELECTIONS}",
132
  )
133
- parser.add_argument(
134
- "--frames", required=True, help="comma-separated frame counts, e.g. 16,32,64"
 
135
  )
 
136
  parser.add_argument(
137
  "--depths",
138
  default=DEFAULT_DEPTH,
@@ -145,51 +137,38 @@ def main():
145
  )
146
  parser.add_argument("--results-dir", default=None)
147
  parser.add_argument("--rebuild", action="store_true")
148
- parser.add_argument(
149
- "--base-protocol",
150
- action="store_true",
151
- help="run the whole sweep under harness.A's exact fixed 16-token protocol "
152
- "instead of the extended default",
153
- )
154
- parser.add_argument(
155
- "--thinking",
156
- action="store_true",
157
- help="enable the model's native thinking mode where supported; errors on models without the switch",
158
- )
159
  parser.add_argument(
160
  "--reasoning-budget",
161
  type=int,
162
- default=EXTENDED_MAX_NEW_TOKENS,
163
  dest="reasoning_budget",
164
- help="extended-protocol first-pass budget (the calibrated value from "
165
  "analysis/preregistration.md, e.g. 512)",
166
  )
167
- parser.add_argument(
168
- "--truncated-budget",
169
- type=int,
170
- default=None,
171
- help="raw-budget arm: base-protocol mechanics (single generation, no forced "
172
- "rescue) at this token cap (mutually exclusive with --base-protocol)",
173
- )
174
  args = parser.parse_args()
 
175
  if args.scene and args.scenes:
176
  parser.error("positional scene and --scenes cannot be used together")
177
- if args.base_protocol and args.truncated_budget is not None:
178
- parser.error("--base-protocol and --truncated-budget are mutually exclusive")
179
 
180
  try:
181
  models = _parse_csv_choice(
182
  args.models, vlm_models.available_models(), "--models"
183
  )
184
- spatial_code_formats = _parse_csv_choice(
185
- args.spatial_code_formats, SPATIAL_CODE_FORMATS, "--spatial-code-formats"
186
- )
187
- input_selections = _parse_csv_choice(
188
- args.input_selections, INPUT_SELECTIONS, "--input-selections"
189
- )
 
 
 
 
 
 
 
190
  depths = _parse_csv_choice(args.depths, DEPTH_VARIANTS, "--depths")
191
  trackings = _parse_csv_choice(args.trackings, TRACKING_MODES, "--trackings")
192
- frame_counts = _parse_frame_counts(args.frames)
193
  except ValueError as exc:
194
  parser.error(str(exc))
195
 
@@ -209,14 +188,13 @@ def main():
209
  input_selections,
210
  frame_counts,
211
  selected,
 
212
  depths=depths,
213
  trackings=trackings,
214
  results_dir=args.results_dir,
215
  rebuild=args.rebuild,
216
- thinking=args.thinking,
217
- extended=not args.base_protocol and args.truncated_budget is None,
218
  reasoning_budget=args.reasoning_budget,
219
- raw_budget=args.truncated_budget,
220
  )
221
 
222
 
 
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)
 
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
 
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,
 
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(
 
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
 
 
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,
 
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
 
 
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
 
harness/C/__init__.py CHANGED
@@ -1,5 +1,5 @@
1
  """Harness C: route BOTH a scene's video frames AND its on-disk spatial code (explicit
2
- or compact) 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
@@ -35,7 +35,6 @@ from harness.B import (
35
  DEFAULT_TRACKING,
36
  DEPTH_VARIANTS,
37
  INPUT_SELECTIONS,
38
- SPATIAL_CODE_FORMATS,
39
  TRACKING_MODES,
40
  )
41
 
 
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
 
35
  DEFAULT_TRACKING,
36
  DEPTH_VARIANTS,
37
  INPUT_SELECTIONS,
 
38
  TRACKING_MODES,
39
  )
40
 
harness/C/launch.py CHANGED
@@ -25,6 +25,7 @@ if str(WORKSPACE_ROOT) not in sys.path:
25
 
26
  from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402
27
  from harness.A import models as vlm_models # noqa: E402
 
28
  from harness.A.launch import scenes # noqa: E402
29
  from harness.B import ( # noqa: E402
30
  DEFAULT_DEPTH,
@@ -33,7 +34,6 @@ from harness.B import ( # noqa: E402
33
  DEFAULT_TRACKING,
34
  DEPTH_VARIANTS,
35
  INPUT_SELECTIONS,
36
- SPATIAL_CODE_FORMATS,
37
  TRACKING_MODES,
38
  )
39
  from harness.C import FRAMES_PER_VIDEO # noqa: E402
@@ -55,6 +55,7 @@ def _worker(
55
  spatial_code_format,
56
  input_selection,
57
  frame_count,
 
58
  depth,
59
  tracking,
60
  results_dir,
@@ -63,10 +64,6 @@ def _worker(
63
  extended,
64
  reasoning_budget,
65
  force_budget,
66
- frame_linked,
67
- overlay,
68
- raw_budget,
69
- thinking,
70
  ):
71
  if gpu is not None:
72
  os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
@@ -80,8 +77,6 @@ def _worker(
80
  load_error = None
81
  try:
82
  adapter = vlm_models.get_adapter(model)
83
- if thinking and not adapter.set_thinking(True):
84
- raise ValueError(f"{model} has no native thinking mode to enable")
85
  adapter.load_model("cuda:0" if gpu is not None else "cpu")
86
  except Exception:
87
  load_error = traceback.format_exc()
@@ -98,6 +93,7 @@ def _worker(
98
  spatial_code_format=spatial_code_format,
99
  input_selection=input_selection,
100
  frame_count=frame_count,
 
101
  depth=depth,
102
  tracking=tracking,
103
  scene=scene,
@@ -106,10 +102,6 @@ def _worker(
106
  extended=extended,
107
  reasoning_budget=reasoning_budget,
108
  force_budget=force_budget,
109
- frame_linked=frame_linked,
110
- overlay=overlay,
111
- raw_budget=raw_budget,
112
- thinking=thinking,
113
  )
114
  mean_score = (
115
  sum(r["score"] for r in answered) / len(answered) if answered else None
@@ -127,6 +119,7 @@ def launch(
127
  input_selection,
128
  frame_count,
129
  selected,
 
130
  depth=DEFAULT_DEPTH,
131
  tracking=DEFAULT_TRACKING,
132
  results_dir=None,
@@ -134,38 +127,25 @@ def launch(
134
  extended=True,
135
  reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
136
  force_budget=MAX_NEW_TOKENS,
137
- frame_linked=False,
138
- overlay=False,
139
- raw_budget=None,
140
- thinking=False,
141
  ):
142
- """Answer every question for ``selected`` scenes, sharded across every visible GPU.
143
-
144
- ``raw_budget`` (mutually exclusive with ``extended``) runs the raw-budget arm:
145
- base-protocol mechanics at this token cap, under its own truncated/<budget> path
146
- segment -- see harness.C.run.run."""
147
- if extended and raw_budget is not None:
148
- raise ValueError("extended and raw_budget are mutually exclusive")
149
- protocol = (
150
- f"{reasoning_budget}"
151
- if extended
152
- else f"truncated/{raw_budget}" if raw_budget is not None else "base"
153
- )
154
- condition = (
155
- f"{model}/{protocol}/{spatial_code_format}/{depth}/{tracking}"
156
- f"/{input_selection}/{frame_count}"
157
- )
158
  run = _load_run_module()
159
  root = run.results_dir_for(
160
  model,
161
- protocol,
162
  spatial_code_format,
163
  depth,
164
  tracking,
165
  input_selection,
166
  frame_count,
167
  results_dir,
168
- overlay=overlay,
169
  )
170
  pending = []
171
  completed = 0
@@ -215,6 +195,7 @@ def launch(
215
  spatial_code_format,
216
  input_selection,
217
  frame_count,
 
218
  depth,
219
  tracking,
220
  results_dir,
@@ -223,10 +204,6 @@ def launch(
223
  extended,
224
  reasoning_budget,
225
  force_budget,
226
- frame_linked,
227
- overlay,
228
- raw_budget,
229
- thinking,
230
  ),
231
  )
232
  for gpu in assignments
@@ -261,56 +238,30 @@ def main():
261
  help="comma-separated scenes (cannot be combined with positional scene)",
262
  )
263
  parser.add_argument("--model", required=True, choices=vlm_models.available_models())
264
- parser.add_argument(
265
- "--spatial-code-format",
266
- default=DEFAULT_SPATIAL_CODE_FORMAT,
267
- choices=SPATIAL_CODE_FORMATS,
268
- dest="spatial_code_format",
269
- )
270
  parser.add_argument(
271
  "--input-selection",
272
- default=DEFAULT_INPUT_SELECTION,
273
  choices=INPUT_SELECTIONS,
274
  dest="input_selection",
275
  )
276
- parser.add_argument("--frames", type=int, default=FRAMES_PER_VIDEO)
 
 
277
  parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS)
278
  parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES)
279
  parser.add_argument("--results-dir", default=None)
280
  parser.add_argument("--rebuild", action="store_true")
281
  parser.add_argument(
282
- "--base-protocol",
283
- action="store_true",
284
- help="run harness.A's exact fixed 16-token protocol instead of the extended default",
285
- )
286
- parser.add_argument(
287
- "--overlay-ids",
288
- action="store_true",
289
- dest="overlay",
290
- help="strong correspondence arm: stamp instance ids onto the frames at each "
291
- "instance's projected position and add matching ids to the code",
292
- )
293
- parser.add_argument(
294
- "--frame-linked-code",
295
- action="store_true",
296
- dest="frame_linked",
297
- help="correspondence arm: add per-instance 'first visible in: frame N' pointers "
298
- "(pair with an explicit --results-dir)",
299
- )
300
- parser.add_argument(
301
- "--thinking",
302
- action="store_true",
303
- help="enable the model's native thinking mode where supported; errors on models without the switch",
304
  )
305
- parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
306
- parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
307
  parser.add_argument(
308
- "--truncated-budget",
309
  type=int,
310
  default=None,
311
- help="raw-budget arm: base-protocol mechanics (single generation, no forced "
312
- "rescue) at this token cap instead of the hardcoded 16 (mutually exclusive "
313
- "with --base-protocol)",
314
  )
315
  args = parser.parse_args()
316
  if args.scene and args.scenes:
@@ -322,33 +273,29 @@ def main():
322
  selected = list(dict.fromkeys(selected))
323
  else:
324
  selected = [args.scene] if args.scene else scenes()
325
- if args.frames < 1:
326
- parser.error("--frames must be positive")
327
- if args.reasoning_budget < 1:
328
- parser.error("--reasoning-budget must be positive")
329
- if args.force_budget < 1:
330
- parser.error("--force-budget must be positive")
331
- if args.truncated_budget is not None and args.truncated_budget < 1:
332
- parser.error("--truncated-budget must be positive")
333
- if args.base_protocol and args.truncated_budget is not None:
334
- parser.error("--base-protocol and --truncated-budget are mutually exclusive")
335
  launch(
336
  args.model,
337
- args.spatial_code_format,
338
  args.input_selection,
339
  args.frames,
340
  selected,
 
341
  depth=args.depth,
342
  tracking=args.tracking,
343
  results_dir=args.results_dir,
344
  rebuild=args.rebuild,
345
- extended=not args.base_protocol and args.truncated_budget is None,
346
- raw_budget=args.truncated_budget,
347
- thinking=args.thinking,
348
  reasoning_budget=args.reasoning_budget,
349
  force_budget=args.force_budget,
350
- frame_linked=args.frame_linked,
351
- overlay=args.overlay,
352
  )
353
 
354
 
 
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,
 
34
  DEFAULT_TRACKING,
35
  DEPTH_VARIANTS,
36
  INPUT_SELECTIONS,
 
37
  TRACKING_MODES,
38
  )
39
  from harness.C import FRAMES_PER_VIDEO # noqa: E402
 
55
  spatial_code_format,
56
  input_selection,
57
  frame_count,
58
+ video,
59
  depth,
60
  tracking,
61
  results_dir,
 
64
  extended,
65
  reasoning_budget,
66
  force_budget,
 
 
 
 
67
  ):
68
  if gpu is not None:
69
  os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
 
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()
 
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,
 
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
 
119
  input_selection,
120
  frame_count,
121
  selected,
122
+ video=False,
123
  depth=DEFAULT_DEPTH,
124
  tracking=DEFAULT_TRACKING,
125
  results_dir=None,
 
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
 
195
  spatial_code_format,
196
  input_selection,
197
  frame_count,
198
+ video,
199
  depth,
200
  tracking,
201
  results_dir,
 
204
  extended,
205
  reasoning_budget,
206
  force_budget,
 
 
 
 
207
  ),
208
  )
209
  for gpu in assignments
 
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:
 
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
 
harness/C/prompts.py CHANGED
@@ -5,41 +5,10 @@ from __future__ import annotations
5
  from harness.B import prompts as code_prompts
6
 
7
  FRAMES_NOTE = "These are frames of a video."
8
- OVERLAY_NOTE = (
9
- 'Each object instance in the code has an "instance id", and the same id is marked '
10
- "in red on the frames at that instance's location."
11
- )
12
 
13
 
14
- def frame_linked_code(explicit_code, compact_code, frame_timestamps):
15
- """Add a per-instance nearest-frame pointer for the frame-linked correspondence arm."""
16
- if not frame_timestamps:
17
- raise ValueError("frame_timestamps must be a non-empty sequence")
18
- code = dict(explicit_code)
19
- objects = {}
20
- for class_name, rendered in code.get("objects", {}).items():
21
- compact_instances = compact_code.get("objects", {}).get(class_name, [])
22
- instances = []
23
- for index, instance in enumerate(rendered.get("instances", [])):
24
- instance = dict(instance)
25
- time = (
26
- compact_instances[index].get("first visible time")
27
- if index < len(compact_instances)
28
- else None
29
- )
30
- if time is not None:
31
- nearest = min(
32
- range(len(frame_timestamps)),
33
- key=lambda i: abs(frame_timestamps[i] - float(time)),
34
- )
35
- instance["first visible in"] = f"frame {nearest + 1}"
36
- instances.append(instance)
37
- objects[class_name] = {**rendered, "instances": instances}
38
- code["objects"] = objects
39
- return code
40
-
41
-
42
- def build_prompt(spatial_code, question_type, question, options=None, overlay=False):
43
  """Return the trailing text block for frames + spatial code.
44
 
45
  The actual frame images are prepended separately by harness.A.models. The text uses
@@ -52,7 +21,4 @@ def build_prompt(spatial_code, question_type, question, options=None, overlay=Fa
52
  options,
53
  frames_note=True,
54
  )
55
- prefix = FRAMES_NOTE
56
- if overlay:
57
- prefix += " " + OVERLAY_NOTE
58
- return prefix + "\n" + prompt
 
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
 
21
  options,
22
  frames_note=True,
23
  )
24
+ return (VIDEO_NOTE if video else FRAMES_NOTE) + "\n" + prompt
 
 
 
harness/C/run.py CHANGED
@@ -1,5 +1,5 @@
1
  """Run one VLM over VSI-Bench questions with BOTH video frames and the scene's on-disk
2
- spatial code (explicit or compact), 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
@@ -23,6 +23,11 @@ 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.run import _scalar_score, load_questions, vsi_official_eval # noqa: E402
27
  from harness.B import ( # noqa: E402
28
  DEFAULT_DEPTH,
@@ -31,7 +36,6 @@ from harness.B import ( # noqa: E402
31
  DEFAULT_TRACKING,
32
  DEPTH_VARIANTS,
33
  INPUT_SELECTIONS,
34
- SPATIAL_CODE_FORMATS,
35
  TRACKING_MODES,
36
  )
37
  from harness.B import spatial_codes # noqa: E402
@@ -48,25 +52,17 @@ def results_dir_for(
48
  input_selection,
49
  frame_count,
50
  results_dir=None,
51
- overlay=False,
52
  ):
53
- """Return the result root isolated by model + protocol + spatial-code-format +
54
  depth + tracking + input + frames. ``protocol`` is "base" (16-token) or
55
  "<reasoning budget>" (e.g. "512") -- a real path segment, so records from
56
  different protocols OR different reasoning budgets can never collide on disk."""
57
  if results_dir is not None:
58
  return Path(results_dir)
59
- root = RESULTS_DIR / "overlay" if overlay else RESULTS_DIR
60
- return (
61
- root
62
- / model
63
- / protocol
64
- / spatial_code_format
65
- / depth
66
- / tracking
67
- / input_selection
68
- / str(frame_count)
69
- )
70
 
71
 
72
  def _build_record(
@@ -82,9 +78,14 @@ def _build_record(
82
  "condition": (
83
  f"{source_info['protocol']}:{source_info['spatial_code_format']}:"
84
  f"{source_info['depth']}:{source_info['tracking']}:"
85
- f"{source_info['input_selection']}:{source_info['frame_count']}"
 
 
 
 
86
  ),
87
  "protocol": source_info["protocol"],
 
88
  "spatial_code_format": source_info["spatial_code_format"],
89
  "input_selection": source_info["input_selection"],
90
  "frame_count": source_info["frame_count"],
@@ -149,7 +150,6 @@ def write_question_result(
149
  source_info["input_selection"],
150
  source_info["frame_count"],
151
  results_dir,
152
- overlay=source_info.get("overlay", False),
153
  )
154
  scene_dir = root / record["scene"]
155
  scene_dir.mkdir(parents=True, exist_ok=True)
@@ -164,6 +164,7 @@ def run(
164
  spatial_code_format=DEFAULT_SPATIAL_CODE_FORMAT,
165
  input_selection=DEFAULT_INPUT_SELECTION,
166
  frame_count=FRAMES_PER_VIDEO,
 
167
  depth=DEFAULT_DEPTH,
168
  tracking=DEFAULT_TRACKING,
169
  scene=None,
@@ -174,27 +175,14 @@ def run(
174
  results_dir=None,
175
  write_results=True,
176
  adapter=None,
177
- thinking=False,
178
  extended=True,
179
  reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
180
  force_budget=MAX_NEW_TOKENS,
181
- frame_linked=False,
182
- overlay=False,
183
- raw_budget=None,
184
  ):
185
  """Answer every matching question with one model, given both its scene's video
186
  frames AND its spatial code as text -- both sourced from the same (depth, tracking,
187
  input_selection, frame_count) config, so they never mismatch.
188
 
189
- ``frame_linked=True`` runs the WEAK correspondence arm (analysis/
190
- preregistration.md): each code instance gains a '"first visible in": "frame N"'
191
- pointer into the prompt's numbered frames (see harness.C.prompts.frame_linked_code).
192
- ``overlay=True`` runs the STRONG correspondence arm: every instance gets an
193
- "instance id" in the code AND that id stamped into each frame at its projected
194
- position (see harness.C.overlay; requires the scene's perception caches on disk).
195
- Overlay results default under ``results/C/overlay`` so they cannot mix with the
196
- main C condition. An explicit ``results_dir`` still overrides that default.
197
-
198
  Uses ``adapter.answer_extended`` (a large ``reasoning_budget`` first pass, with a
199
  short forced second call only if the model doesn't conclude within it) as the
200
  standing default protocol, same as harness.B, since C combines the same complex
@@ -207,18 +195,14 @@ def run(
207
  to reuse one already-loaded model across many calls; the caller then owns unloading
208
  it. Without one, ``run`` loads and unloads its own adapter, same as harness.A/B.
209
  """
210
- if extended and raw_budget is not None:
211
- raise ValueError("extended and raw_budget are mutually exclusive")
212
- if (frame_linked or overlay) and spatial_code_format != "explicit":
213
- raise ValueError(
214
- "the correspondence arms are defined for the explicit format only (their "
215
- "transforms annotate explicit-shaped instances)"
216
- )
217
- protocol = (
218
- f"{reasoning_budget}"
219
- if extended
220
- else f"truncated/{raw_budget}" if raw_budget is not None else "base"
221
- )
222
  results_dir = results_dir_for(
223
  model,
224
  protocol,
@@ -228,7 +212,6 @@ def run(
228
  input_selection,
229
  frame_count,
230
  results_dir,
231
- overlay=overlay,
232
  )
233
  rows = load_questions(jsonl_path, scene, scenes, limit)
234
  if not rows:
@@ -236,21 +219,25 @@ def run(
236
  owns_adapter = adapter is None
237
  if owns_adapter:
238
  adapter = vlm_models.get_adapter(model)
239
- if thinking and not adapter.set_thinking(True):
240
- raise ValueError(f"{model} has no native thinking mode to enable")
241
  adapter.load_model(device)
242
  source_cache = {}
243
  results = []
244
  try:
245
  for row in rows:
 
246
  scene_id = row["scene_name"]
247
  if scene_id not in source_cache:
248
  video_path = inference_config.video_path(scene_id, row.get("dataset"))
249
- frame_images, frame_timestamps, frame_indices = (
250
- frame_sampling.sample_frames(
251
- video_path, frame_count, input_selection
 
 
 
 
 
 
252
  )
253
- )
254
  code, code_path = spatial_codes.load_spatial_code(
255
  scene_id,
256
  depth,
@@ -259,33 +246,6 @@ def run(
259
  frame_count,
260
  spatial_code_format,
261
  )
262
- if frame_linked:
263
- compact_code, _ = spatial_codes.load_spatial_code(
264
- scene_id,
265
- depth,
266
- input_selection,
267
- tracking,
268
- frame_count,
269
- "compact",
270
- )
271
- code = combined_prompts.frame_linked_code(
272
- code, compact_code, frame_timestamps
273
- )
274
- if overlay:
275
- from harness.C import overlay as overlay_module
276
-
277
- frame_images, _visible = overlay_module.stamp_frames(
278
- frame_images,
279
- code,
280
- scene_id,
281
- depth,
282
- input_selection,
283
- tracking,
284
- frame_count,
285
- )
286
- code, code_path = overlay_module.load_or_create_overlay_code(
287
- code, scene_id, depth, input_selection, tracking, frame_count
288
- )
289
  source_cache[scene_id] = {
290
  "video_path": video_path,
291
  "frame_images": frame_images,
@@ -300,7 +260,7 @@ def run(
300
  row["question_type"],
301
  row["question"],
302
  row.get("options"),
303
- overlay=overlay,
304
  )
305
  answer = (
306
  adapter.answer_extended(
@@ -309,9 +269,9 @@ def run(
309
  reasoning_budget=reasoning_budget,
310
  force_budget=force_budget,
311
  )
312
- if extended
313
  else adapter.answer(
314
- cached["frame_images"], prompt, max_new_tokens=raw_budget
315
  )
316
  )
317
  doc = {
@@ -333,7 +293,6 @@ def run(
333
  "video_path": cached["video_path"],
334
  "frame_indices": cached["frame_indices"],
335
  "frame_timestamps": cached["frame_timestamps"],
336
- "overlay": overlay,
337
  }
338
  if write_results:
339
  path, record = write_question_result(
@@ -371,19 +330,15 @@ def main():
371
  parser = argparse.ArgumentParser()
372
  parser.add_argument("--model", required=True, choices=vlm_models.available_models())
373
  parser.add_argument("--scene", default=None, help="restrict to one VSI-Bench scene")
374
- parser.add_argument(
375
- "--spatial-code-format",
376
- default=DEFAULT_SPATIAL_CODE_FORMAT,
377
- choices=SPATIAL_CODE_FORMATS,
378
- dest="spatial_code_format",
379
- )
380
  parser.add_argument(
381
  "--input-selection",
382
- default=DEFAULT_INPUT_SELECTION,
383
  choices=INPUT_SELECTIONS,
384
  dest="input_selection",
385
  )
386
- parser.add_argument("--frames", type=int, default=FRAMES_PER_VIDEO)
 
 
387
  parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS)
388
  parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES)
389
  parser.add_argument(
@@ -393,8 +348,8 @@ def main():
393
  parser.add_argument(
394
  "--results-dir",
395
  default=None,
396
- help="override the default results/C/<model>/<protocol>/<format>/"
397
- "<depth>/<tracking>/<input>/<frames> root",
398
  )
399
  parser.add_argument(
400
  "--no-write",
@@ -402,57 +357,33 @@ def main():
402
  help="skip writing per-question JSON files; print/score only",
403
  )
404
  parser.add_argument(
405
- "--base-protocol",
406
- action="store_true",
407
- help="run harness.A's exact fixed 16-token protocol (plain answer()) instead of "
408
- "the extended 2048-token default",
409
- )
410
- parser.add_argument(
411
- "--overlay-ids",
412
- action="store_true",
413
- dest="overlay",
414
- help="strong correspondence arm: stamp instance ids onto the frames at each "
415
- "instance's projected position and add matching ids to the code",
416
- )
417
- parser.add_argument(
418
- "--frame-linked-code",
419
- action="store_true",
420
- dest="frame_linked",
421
- help="correspondence arm: add per-instance 'first visible in: frame N' pointers "
422
- "(pair with an explicit --results-dir)",
423
- )
424
- parser.add_argument(
425
- "--thinking",
426
- action="store_true",
427
- help="enable the model's native thinking mode where supported; errors on models without the switch",
428
  )
429
- parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
430
- parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
431
  parser.add_argument(
432
- "--truncated-budget",
433
  type=int,
434
  default=None,
435
- help="raw-budget arm: base-protocol mechanics (single generation, no forced "
436
- "rescue) at this token cap instead of the hardcoded 16 (mutually exclusive "
437
- "with --base-protocol)",
438
  )
439
  args = parser.parse_args()
440
- if args.frames < 1:
441
- parser.error("--frames must be positive")
442
- if args.reasoning_budget < 1:
443
- parser.error("--reasoning-budget must be positive")
444
- if args.force_budget < 1:
445
- parser.error("--force-budget must be positive")
446
- if args.truncated_budget is not None and args.truncated_budget < 1:
447
- parser.error("--truncated-budget must be positive")
448
- if args.base_protocol and args.truncated_budget is not None:
449
- parser.error("--base-protocol and --truncated-budget are mutually exclusive")
450
-
451
  results = run(
452
  args.model,
453
- spatial_code_format=args.spatial_code_format,
454
  input_selection=args.input_selection,
455
  frame_count=args.frames,
 
456
  depth=args.depth,
457
  tracking=args.tracking,
458
  scene=args.scene,
@@ -460,11 +391,7 @@ def main():
460
  device=args.device,
461
  results_dir=args.results_dir,
462
  write_results=not args.no_write,
463
- extended=not args.base_protocol and args.truncated_budget is None,
464
- raw_budget=args.truncated_budget,
465
- frame_linked=args.frame_linked,
466
- overlay=args.overlay,
467
- thinking=args.thinking,
468
  reasoning_budget=args.reasoning_budget,
469
  force_budget=args.force_budget,
470
  )
 
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
 
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,
 
36
  DEFAULT_TRACKING,
37
  DEPTH_VARIANTS,
38
  INPUT_SELECTIONS,
 
39
  TRACKING_MODES,
40
  )
41
  from harness.B import spatial_codes # noqa: E402
 
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(
 
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"],
 
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)
 
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,
 
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
 
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,
 
212
  input_selection,
213
  frame_count,
214
  results_dir,
 
215
  )
216
  rows = load_questions(jsonl_path, scene, scenes, limit)
217
  if not rows:
 
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,
 
246
  frame_count,
247
  spatial_code_format,
248
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
  source_cache[scene_id] = {
250
  "video_path": video_path,
251
  "frame_images": frame_images,
 
260
  row["question_type"],
261
  row["question"],
262
  row.get("options"),
263
+ video=video,
264
  )
265
  answer = (
266
  adapter.answer_extended(
 
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 = {
 
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(
 
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(
 
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",
 
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,
 
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
  )
harness/C/sweep.py CHANGED
@@ -1,4 +1,4 @@
1
- """Sweep any set of models x spatial-code-formats x depths x trackings x
2
  input-selections x frame-counts.
3
 
4
  Every (model, spatial_code_format, depth, tracking, input_selection, frame_count)
@@ -22,14 +22,15 @@ 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 EXTENDED_MAX_NEW_TOKENS # noqa: E402
26
  from harness.A.sweep import _parse_csv_choice, _parse_frame_counts # noqa: E402
27
  from harness.B import ( # noqa: E402
28
  DEFAULT_DEPTH,
 
29
  DEFAULT_TRACKING,
30
  DEPTH_VARIANTS,
31
  INPUT_SELECTIONS,
32
- SPATIAL_CODE_FORMATS,
33
  TRACKING_MODES,
34
  )
35
  from harness.C import launch as harness_launch # noqa: E402
@@ -58,26 +59,18 @@ def sweep(
58
  input_selections,
59
  frame_counts,
60
  selected_scenes,
 
61
  depths=(DEFAULT_DEPTH,),
62
  trackings=(DEFAULT_TRACKING,),
63
  results_dir=None,
64
  rebuild=False,
65
- thinking=False,
66
  extended=True,
67
  reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
68
- frame_linked=False,
69
- overlay=False,
70
- raw_budget=None,
71
  ):
72
  """Run every sweep combination across all visible GPUs."""
73
  plan = build_plan(
74
  models, spatial_code_formats, input_selections, frame_counts, depths, trackings
75
  )
76
- protocol = (
77
- f"{reasoning_budget}"
78
- if extended
79
- else f"truncated/{raw_budget}" if raw_budget is not None else "base"
80
- )
81
  for index, (
82
  model,
83
  spatial_code_format,
@@ -87,8 +80,10 @@ def sweep(
87
  frame_count,
88
  ) in enumerate(plan, start=1):
89
  print(
90
- f"=== sweep {index}/{len(plan)}: {model}/{protocol}/"
91
- f"{spatial_code_format}/{depth}/{tracking}/{input_selection}/{frame_count} ===",
 
 
92
  flush=True,
93
  )
94
  harness_launch.launch(
@@ -97,16 +92,13 @@ def sweep(
97
  input_selection,
98
  frame_count,
99
  selected_scenes,
 
100
  depth=depth,
101
  tracking=tracking,
102
  results_dir=results_dir,
103
  rebuild=rebuild,
104
- thinking=thinking,
105
  extended=extended,
106
  reasoning_budget=reasoning_budget,
107
- frame_linked=frame_linked,
108
- overlay=overlay,
109
- raw_budget=raw_budget,
110
  )
111
 
112
 
@@ -122,21 +114,17 @@ def main():
122
  required=True,
123
  help=f"comma-separated models (or 'all'); one of {vlm_models.available_models()}",
124
  )
125
- parser.add_argument(
126
- "--spatial-code-formats",
127
- required=True,
128
- dest="spatial_code_formats",
129
- help=f"comma-separated formats (or 'all'); one of {SPATIAL_CODE_FORMATS}",
130
- )
131
  parser.add_argument(
132
  "--input-selections",
133
- required=True,
134
  dest="input_selections",
135
  help=f"comma-separated selections (or 'all'); one of {INPUT_SELECTIONS}",
136
  )
137
- parser.add_argument(
138
- "--frames", required=True, help="comma-separated frame counts, e.g. 16,32,64"
 
139
  )
 
140
  parser.add_argument(
141
  "--depths",
142
  default=DEFAULT_DEPTH,
@@ -149,65 +137,38 @@ def main():
149
  )
150
  parser.add_argument("--results-dir", default=None)
151
  parser.add_argument("--rebuild", action="store_true")
152
- parser.add_argument(
153
- "--base-protocol",
154
- action="store_true",
155
- help="run the whole sweep under harness.A's exact fixed 16-token protocol "
156
- "instead of the extended default",
157
- )
158
- parser.add_argument(
159
- "--thinking",
160
- action="store_true",
161
- help="enable the model's native thinking mode where supported; errors on models without the switch",
162
- )
163
  parser.add_argument(
164
  "--reasoning-budget",
165
  type=int,
166
- default=EXTENDED_MAX_NEW_TOKENS,
167
  dest="reasoning_budget",
168
- help="extended-protocol first-pass budget (the calibrated value from "
169
  "preregistration.md, e.g. 512)",
170
  )
171
- parser.add_argument(
172
- "--overlay-ids",
173
- action="store_true",
174
- dest="overlay",
175
- help="strong correspondence arm: stamp instance ids onto the frames at each "
176
- "instance's projected position and add matching ids to the code",
177
- )
178
- parser.add_argument(
179
- "--frame-linked-code",
180
- action="store_true",
181
- dest="frame_linked",
182
- help="correspondence arm: add per-instance 'first visible in: frame N' pointers "
183
- "(pair with an explicit --results-dir)",
184
- )
185
- parser.add_argument(
186
- "--truncated-budget",
187
- type=int,
188
- default=None,
189
- help="raw-budget arm: base-protocol mechanics (single generation, no forced "
190
- "rescue) at this token cap (mutually exclusive with --base-protocol)",
191
- )
192
  args = parser.parse_args()
 
193
  if args.scene and args.scenes:
194
  parser.error("positional scene and --scenes cannot be used together")
195
- if args.base_protocol and args.truncated_budget is not None:
196
- parser.error("--base-protocol and --truncated-budget are mutually exclusive")
197
 
198
  try:
199
  models = _parse_csv_choice(
200
  args.models, vlm_models.available_models(), "--models"
201
  )
202
- spatial_code_formats = _parse_csv_choice(
203
- args.spatial_code_formats, SPATIAL_CODE_FORMATS, "--spatial-code-formats"
204
- )
205
- input_selections = _parse_csv_choice(
206
- args.input_selections, INPUT_SELECTIONS, "--input-selections"
207
- )
 
 
 
 
 
 
 
208
  depths = _parse_csv_choice(args.depths, DEPTH_VARIANTS, "--depths")
209
  trackings = _parse_csv_choice(args.trackings, TRACKING_MODES, "--trackings")
210
- frame_counts = _parse_frame_counts(args.frames)
211
  except ValueError as exc:
212
  parser.error(str(exc))
213
 
@@ -227,16 +188,13 @@ def main():
227
  input_selections,
228
  frame_counts,
229
  selected,
 
230
  depths=depths,
231
  trackings=trackings,
232
  results_dir=args.results_dir,
233
  rebuild=args.rebuild,
234
- thinking=args.thinking,
235
- extended=not args.base_protocol and args.truncated_budget is None,
236
  reasoning_budget=args.reasoning_budget,
237
- frame_linked=args.frame_linked,
238
- overlay=args.overlay,
239
- raw_budget=args.truncated_budget,
240
  )
241
 
242
 
 
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)
 
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
 
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,
 
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(
 
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
 
 
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,
 
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
 
 
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
 
harness/F/__init__.py CHANGED
@@ -1,8 +1,8 @@
1
- """Harness F: deterministic symbolic reasoning over perceived or ground-truth 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", "ground truth")
8
  DEFAULT_SOURCE = "perceived"
 
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/run.py CHANGED
@@ -26,17 +26,10 @@ def results_dir_for(
26
  ):
27
  if results_dir is not None:
28
  return Path(results_dir)
29
- if source == "ground truth":
30
- return RESULTS_DIR / "ground truth" / spatial_code_format
31
- return (
32
- RESULTS_DIR
33
- / "perceived"
34
- / depth
35
- / tracking
36
- / input_selection
37
- / str(frame_count)
38
- / spatial_code_format
39
- )
40
 
41
 
42
  def select_source(
@@ -49,8 +42,8 @@ def select_source(
49
  ):
50
  if source not in SOURCES:
51
  raise ValueError(f"unknown source {source!r}; expected one of {SOURCES}")
52
- if source == "ground truth":
53
- return symbolic_run.select_ground_truth_spatial_codes(spatial_code_format)
54
  return symbolic_run.select_spatial_codes(
55
  depth, input_selection, tracking, frame_count, spatial_code_format
56
  )
@@ -70,6 +63,7 @@ def run(
70
  tracking="tracking",
71
  input_selection="uniform",
72
  frame_count=32,
 
73
  scene=None,
74
  scenes=None,
75
  results_dir=None,
@@ -78,6 +72,11 @@ def run(
78
  ):
79
  if scene is not None and scenes is not None:
80
  raise ValueError("scene and scenes cannot both be given")
 
 
 
 
 
81
  select_source(
82
  source, spatial_code_format, depth, tracking, input_selection, frame_count
83
  )
@@ -135,12 +134,6 @@ def main():
135
  "--scenes", help="comma-separated scenes; default: every available scene"
136
  )
137
  p.add_argument("--source", choices=SOURCES, default=DEFAULT_SOURCE)
138
- p.add_argument(
139
- "--spatial-code-format",
140
- choices=symbolic_run.SPATIAL_CODE_FORMATS,
141
- default="explicit",
142
- dest="spatial_code_format",
143
- )
144
  p.add_argument("--depth", choices=symbolic_run.DEPTH_VARIANTS, default="metric")
145
  p.add_argument(
146
  "--tracking", choices=symbolic_run.TRACKING_MODES, default="tracking"
@@ -148,18 +141,26 @@ def main():
148
  p.add_argument(
149
  "--input-selection",
150
  choices=symbolic_run.INPUT_SELECTIONS,
151
- default="uniform",
152
  dest="input_selection",
153
  )
154
- p.add_argument("--frames", type=int, default=32)
 
 
155
  p.add_argument("--results-dir", default=None)
156
  p.add_argument("--no-write", action="store_true")
157
  p.add_argument("--verbose", action="store_true")
158
  a = p.parse_args()
159
  if a.scene and a.scenes:
160
  p.error("scene and --scenes cannot be combined")
161
- if a.frames < 1:
162
- p.error("--frames must be positive")
 
 
 
 
 
 
163
  selected = (
164
  None
165
  if not a.scenes
@@ -167,11 +168,12 @@ def main():
167
  )
168
  records = run(
169
  a.source,
170
- a.spatial_code_format,
171
  a.depth,
172
  a.tracking,
173
  a.input_selection,
174
  a.frames,
 
175
  a.scene,
176
  selected,
177
  a.results_dir,
 
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(
 
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
  )
 
63
  tracking="tracking",
64
  input_selection="uniform",
65
  frame_count=32,
66
+ video=False,
67
  scene=None,
68
  scenes=None,
69
  results_dir=None,
 
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
  )
 
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"
 
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
 
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,
harness/F/sweep.py CHANGED
@@ -22,25 +22,34 @@ def _csv(value, valid):
22
  def main():
23
  p = argparse.ArgumentParser()
24
  p.add_argument("--sources", default="all")
25
- p.add_argument("--spatial-code-formats", default="all")
26
  p.add_argument("--depths", default="metric")
27
  p.add_argument("--trackings", default="tracking")
28
- p.add_argument("--input-selections", default="uniform")
29
- p.add_argument("--frames", default="32")
 
 
30
  p.add_argument("--scenes", default=None)
31
  p.add_argument("--results-dir", default=None)
32
  a = p.parse_args()
33
  try:
34
  sources = _csv(a.sources, harness_run.SOURCES)
35
- formats = _csv(a.spatial_code_formats, symbolic_run.SPATIAL_CODE_FORMATS)
36
  depths = _csv(a.depths, symbolic_run.DEPTH_VARIANTS)
37
  trackings = _csv(a.trackings, symbolic_run.TRACKING_MODES)
38
- selections = _csv(a.input_selections, symbolic_run.INPUT_SELECTIONS)
39
- frames = list(
40
- dict.fromkeys(int(x.strip()) for x in a.frames.split(",") if x.strip())
41
- )
42
- if not frames or any(x < 1 for x in frames):
43
- raise ValueError("frames must be positive")
 
 
 
 
 
 
 
 
44
  except ValueError as exc:
45
  p.error(str(exc))
46
  scenes = (
@@ -49,20 +58,17 @@ def main():
49
  else list(dict.fromkeys(x.strip() for x in a.scenes.split(",") if x.strip()))
50
  )
51
  for source, fmt in product(sources, formats):
52
- configs = (
53
- [(None, None, None, None)]
54
- if source == "ground truth"
55
- else product(depths, trackings, selections, frames)
56
- )
57
  for config in configs:
58
  depth, tracking, selection, count = config
59
  records = harness_run.run(
60
  source,
61
  fmt,
62
- depth or "metric",
63
- tracking or "tracking",
64
- selection or "uniform",
65
- count or 32,
 
66
  scenes=scenes,
67
  results_dir=a.results_dir,
68
  )
 
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 = (
 
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
  )
inference/__init__.py CHANGED
@@ -63,7 +63,7 @@ def model_cache_dir(
63
  root = CACHE_ROOT / model
64
  if model == "depth-anything-3":
65
  root /= depth
66
- return str(root / input_selection / str(frame_count))
67
 
68
 
69
  def sam3_cache_dir(tracking, input_selection, frame_count=FRAMES_PER_VIDEO):
@@ -78,7 +78,7 @@ def sam3_cache_dir(tracking, input_selection, frame_count=FRAMES_PER_VIDEO):
78
  )
79
  if frame_count < 1:
80
  raise ValueError("frame count must be positive")
81
- return str(CACHE_ROOT / "sam3" / tracking / input_selection / str(frame_count))
82
 
83
 
84
  def parse_sam3_frame_mode(mode):
 
63
  root = CACHE_ROOT / model
64
  if model == "depth-anything-3":
65
  root /= depth
66
+ return str(root / "frames" / input_selection / str(frame_count))
67
 
68
 
69
  def sam3_cache_dir(tracking, input_selection, frame_count=FRAMES_PER_VIDEO):
 
78
  )
79
  if frame_count < 1:
80
  raise ValueError("frame count must be positive")
81
+ return str(CACHE_ROOT / "sam3" / tracking / "frames" / input_selection / str(frame_count))
82
 
83
 
84
  def parse_sam3_frame_mode(mode):
symbolic/adapters.py CHANGED
@@ -202,8 +202,7 @@ def _adapt_compact(code):
202
  "longest dimension": float(dimensions.max()),
203
  }
204
  )
205
- # None means no ground truth timing is available for this instance (see
206
- # encoder.ground_truth) -- excluded from the min rather than coerced to a
207
  # fabricated time; a class with no timed instance at all falls through to the
208
  # math.inf default below and sorts after every timed class.
209
  if first_time is not None:
 
202
  "longest dimension": float(dimensions.max()),
203
  }
204
  )
205
+ # None means no ground truth timing is available for this instance -- excluded from the min rather than coerced to a
 
206
  # fabricated time; a class with no timed instance at all falls through to the
207
  # math.inf default below and sorts after every timed class.
208
  if first_time is not None:
symbolic/launch.py CHANGED
@@ -444,7 +444,7 @@ def _run_cli(args, requested_scene_ids):
444
  args.input_selection,
445
  args.tracking,
446
  args.frames,
447
- args.spatial_code_format,
448
  )
449
  scene_ids = requested_scene_ids
450
  all_available = scenes_with_spatial_codes()
@@ -514,7 +514,7 @@ def _run_cli(args, requested_scene_ids):
514
  "input": args.input_selection,
515
  "tracking": args.tracking,
516
  "frames": args.frames,
517
- "spatial_code_format": args.spatial_code_format,
518
  "scenes_run": scenes_with_real_questions,
519
  "scenes_skipped_no_questions": [
520
  scene for scene in scene_ids if scene not in per_scene_results
@@ -538,21 +538,20 @@ def _run_cli(args, requested_scene_ids):
538
 
539
  def main():
540
  ap = argparse.ArgumentParser()
541
- ap.add_argument("--depth", required=True, choices=symbolic_run.DEPTH_VARIANTS)
542
  ap.add_argument(
543
  "--input",
544
- required=True,
545
  choices=symbolic_run.INPUT_SELECTIONS,
546
  dest="input_selection",
547
  )
548
- ap.add_argument("--frames", type=int, default=32)
549
- ap.add_argument(
550
- "--format",
551
- choices=symbolic_run.SPATIAL_CODE_FORMATS,
552
- default="explicit",
553
- dest="spatial_code_format",
554
  )
555
- ap.add_argument("--tracking", required=True, choices=symbolic_run.TRACKING_MODES)
556
  ap.add_argument(
557
  "--scenes",
558
  default="",
@@ -572,7 +571,17 @@ def main():
572
  "offenders) in addition to the combined aggregate",
573
  )
574
  a = ap.parse_args()
575
- if a.frames < 1:
 
 
 
 
 
 
 
 
 
 
576
  ap.error("--frames must be positive")
577
  requested_scene_ids = (
578
  [scene.strip() for scene in a.scenes.split(",") if scene.strip()]
 
444
  args.input_selection,
445
  args.tracking,
446
  args.frames,
447
+ "explicit",
448
  )
449
  scene_ids = requested_scene_ids
450
  all_available = scenes_with_spatial_codes()
 
514
  "input": args.input_selection,
515
  "tracking": args.tracking,
516
  "frames": args.frames,
517
+ "spatial_code_format": "explicit",
518
  "scenes_run": scenes_with_real_questions,
519
  "scenes_skipped_no_questions": [
520
  scene for scene in scene_ids if scene not in per_scene_results
 
538
 
539
  def main():
540
  ap = argparse.ArgumentParser()
541
+ ap.add_argument("--depth", choices=symbolic_run.DEPTH_VARIANTS)
542
  ap.add_argument(
543
  "--input",
 
544
  choices=symbolic_run.INPUT_SELECTIONS,
545
  dest="input_selection",
546
  )
547
+ input_mode = ap.add_mutually_exclusive_group(required=True)
548
+ input_mode.add_argument("--frames", type=int)
549
+ input_mode.add_argument(
550
+ "--video",
551
+ action="store_true",
552
+ help="use spatial codes built from full-video DA3 and SAM3 caches",
553
  )
554
+ ap.add_argument("--tracking", choices=symbolic_run.TRACKING_MODES)
555
  ap.add_argument(
556
  "--scenes",
557
  default="",
 
571
  "offenders) in addition to the combined aggregate",
572
  )
573
  a = ap.parse_args()
574
+ if a.depth is None:
575
+ ap.error("--depth is required")
576
+ if a.tracking is None:
577
+ ap.error("--tracking is required")
578
+ if a.video:
579
+ if a.input_selection is not None:
580
+ ap.error("--input cannot be used with --video")
581
+ a.input_selection = symbolic_run.VIDEO_INPUT_SELECTION
582
+ elif a.input_selection is None:
583
+ ap.error("--input is required with --frames")
584
+ if a.frames is not None and a.frames < 1:
585
  ap.error("--frames must be positive")
586
  requested_scene_ids = (
587
  [scene.strip() for scene in a.scenes.split(",") if scene.strip()]
symbolic/run.py CHANGED
@@ -5,7 +5,7 @@ orchestrator (matching encoder/launch.py's single-scene-worker versus
5
  multi-scene-orchestrator split: this file never loops over more than one scene on its own).
6
 
7
  Fetches the spatial code from:
8
- /workspace/data/spatial codes/<MODEL>/<DEPTH>/<TRACKING>/<INPUT>/<FRAMES>/<FORMAT>/<SCENE_ID>.json
9
  (the model- and format-specific on-disk layout). This file does NOT
10
  build spatial codes (that's encoder/render.py's job) and does NOT call any model -- it only
11
  reads an already-built spatial_code.json and answers/scores against it.
@@ -115,6 +115,7 @@ def _default_results_dir():
115
 
116
  DEPTH_VARIANTS = ("relative", "metric")
117
  INPUT_SELECTIONS = ("uniform", "selective")
 
118
  TRACKING_MODES = ("tracking", "no tracking")
119
  SPATIAL_CODE_FORMATS = adapters.SPATIAL_CODE_FORMATS
120
  SPATIAL_CODES_ROOT = os.environ.get(
@@ -133,22 +134,27 @@ def _validate_selection(depth, input_selection, tracking, frame_count):
133
  """Validate the dimensions shared by spatial-code and result paths."""
134
  if depth not in DEPTH_VARIANTS:
135
  raise ValueError(f"unknown depth variant {depth!r}; expected {DEPTH_VARIANTS}")
136
- if input_selection not in INPUT_SELECTIONS:
 
137
  raise ValueError(
138
- f"unknown input selection {input_selection!r}; expected {INPUT_SELECTIONS}"
139
  )
140
  if tracking not in TRACKING_MODES:
141
  raise ValueError(
142
  f"unknown tracking mode {tracking!r}; expected {TRACKING_MODES}"
143
  )
144
- if frame_count < 1:
 
 
145
  raise ValueError("frame count must be positive")
146
 
147
 
148
  def _selection_subdirectory(depth, input_selection, tracking, frame_count):
149
- """Return the shared depth/tracking/input/frame-count hierarchy."""
150
  _validate_selection(depth, input_selection, tracking, frame_count)
151
- return os.path.join(depth, tracking, input_selection, str(frame_count))
 
 
152
 
153
 
154
  def select_spatial_codes(
@@ -182,7 +188,7 @@ def select_spatial_codes(
182
 
183
 
184
  def select_ground_truth_spatial_codes(spatial_code_format="explicit"):
185
- """Select the GROUND-TRUTH spatial codes (encoder.ground_truth's on-disk output,
186
  "data/spatial codes/ground truth/<format>/<scene>.json") instead of a perception-
187
  pipeline selection -- no depth/tracking/input/frame-count axis, since ground truth
188
  is built once per scene straight from dataset annotations. Results written while
@@ -528,8 +534,12 @@ def write_question_result(scene_id, pq, code, results_dir=None):
528
  if ground_truth
529
  else (
530
  f"{SPATIAL_CODES_DEPTH}:{SPATIAL_CODES_TRACKING}:"
531
- f"{SPATIAL_CODES_INPUT}:{SPATIAL_CODES_FRAMES}:"
532
- f"{SPATIAL_CODES_FORMAT}"
 
 
 
 
533
  )
534
  ),
535
  "spatial_code_model": None if ground_truth else SPATIAL_CODES_MODEL,
@@ -590,27 +600,35 @@ def write_scene_results(scene_id, per_question, aggregate, code, results_dir=Non
590
  def main():
591
  parser = argparse.ArgumentParser()
592
  parser.add_argument("scene_id")
593
- parser.add_argument("--depth", required=True, choices=DEPTH_VARIANTS)
594
- parser.add_argument(
595
- "--input", required=True, choices=INPUT_SELECTIONS, dest="input_selection"
596
- )
597
- parser.add_argument("--tracking", required=True, choices=TRACKING_MODES)
598
- parser.add_argument("--frames", type=int, default=32)
599
- parser.add_argument(
600
- "--format",
601
- choices=SPATIAL_CODE_FORMATS,
602
- default="explicit",
603
- dest="spatial_code_format",
604
  )
 
605
  args = parser.parse_args()
606
- if args.frames < 1:
 
 
 
 
 
 
 
 
 
 
607
  parser.error("--frames must be positive")
608
  select_spatial_codes(
609
  args.depth,
610
  args.input_selection,
611
  args.tracking,
612
  args.frames,
613
- args.spatial_code_format,
614
  )
615
  per_question, aggregate = score_scene(args.scene_id)
616
  code = fetch_spatial_code(args.scene_id)
 
5
  multi-scene-orchestrator split: this file never loops over more than one scene on its own).
6
 
7
  Fetches the spatial code from:
8
+ /workspace/data/spatial codes/<MODEL>/<DEPTH>/<TRACKING>/{frames/<INPUT>/<FRAMES>|video}/explicit/<SCENE_ID>.json
9
  (the model- and format-specific on-disk layout). This file does NOT
10
  build spatial codes (that's encoder/render.py's job) and does NOT call any model -- it only
11
  reads an already-built spatial_code.json and answers/scores against it.
 
115
 
116
  DEPTH_VARIANTS = ("relative", "metric")
117
  INPUT_SELECTIONS = ("uniform", "selective")
118
+ VIDEO_INPUT_SELECTION = "video"
119
  TRACKING_MODES = ("tracking", "no tracking")
120
  SPATIAL_CODE_FORMATS = adapters.SPATIAL_CODE_FORMATS
121
  SPATIAL_CODES_ROOT = os.environ.get(
 
134
  """Validate the dimensions shared by spatial-code and result paths."""
135
  if depth not in DEPTH_VARIANTS:
136
  raise ValueError(f"unknown depth variant {depth!r}; expected {DEPTH_VARIANTS}")
137
+ selections = INPUT_SELECTIONS + (VIDEO_INPUT_SELECTION,)
138
+ if input_selection not in selections:
139
  raise ValueError(
140
+ f"unknown input selection {input_selection!r}; expected {selections}"
141
  )
142
  if tracking not in TRACKING_MODES:
143
  raise ValueError(
144
  f"unknown tracking mode {tracking!r}; expected {TRACKING_MODES}"
145
  )
146
+ if input_selection != VIDEO_INPUT_SELECTION and (
147
+ frame_count is None or frame_count < 1
148
+ ):
149
  raise ValueError("frame count must be positive")
150
 
151
 
152
  def _selection_subdirectory(depth, input_selection, tracking, frame_count):
153
+ """Return tracking/{frames/<selection>/<count>|video} for perceived codes."""
154
  _validate_selection(depth, input_selection, tracking, frame_count)
155
+ if input_selection == VIDEO_INPUT_SELECTION:
156
+ return os.path.join(tracking, "video")
157
+ return os.path.join(tracking, "frames", input_selection, str(frame_count))
158
 
159
 
160
  def select_spatial_codes(
 
188
 
189
 
190
  def select_ground_truth_spatial_codes(spatial_code_format="explicit"):
191
+ """Select the GROUND-TRUTH spatial codes (prebuilt on-disk output,
192
  "data/spatial codes/ground truth/<format>/<scene>.json") instead of a perception-
193
  pipeline selection -- no depth/tracking/input/frame-count axis, since ground truth
194
  is built once per scene straight from dataset annotations. Results written while
 
534
  if ground_truth
535
  else (
536
  f"{SPATIAL_CODES_DEPTH}:{SPATIAL_CODES_TRACKING}:"
537
+ + (
538
+ "video"
539
+ if SPATIAL_CODES_INPUT == VIDEO_INPUT_SELECTION
540
+ else f"{SPATIAL_CODES_INPUT}:{SPATIAL_CODES_FRAMES}"
541
+ )
542
+ + f":{SPATIAL_CODES_FORMAT}"
543
  )
544
  ),
545
  "spatial_code_model": None if ground_truth else SPATIAL_CODES_MODEL,
 
600
  def main():
601
  parser = argparse.ArgumentParser()
602
  parser.add_argument("scene_id")
603
+ parser.add_argument("--depth", choices=DEPTH_VARIANTS)
604
+ parser.add_argument("--input", choices=INPUT_SELECTIONS, dest="input_selection")
605
+ input_mode = parser.add_mutually_exclusive_group(required=True)
606
+ input_mode.add_argument("--frames", type=int)
607
+ input_mode.add_argument(
608
+ "--video",
609
+ action="store_true",
610
+ help="use a spatial code built from full-video DA3 and SAM3 caches",
 
 
 
611
  )
612
+ parser.add_argument("--tracking", choices=TRACKING_MODES)
613
  args = parser.parse_args()
614
+ if args.depth is None:
615
+ parser.error("--depth is required")
616
+ if args.tracking is None:
617
+ parser.error("--tracking is required")
618
+ if args.video:
619
+ if args.input_selection is not None:
620
+ parser.error("--input cannot be used with --video")
621
+ args.input_selection = VIDEO_INPUT_SELECTION
622
+ elif args.input_selection is None:
623
+ parser.error("--input is required with --frames")
624
+ if args.frames is not None and args.frames < 1:
625
  parser.error("--frames must be positive")
626
  select_spatial_codes(
627
  args.depth,
628
  args.input_selection,
629
  args.tracking,
630
  args.frames,
631
+ "explicit",
632
  )
633
  per_question, aggregate = score_scene(args.scene_id)
634
  code = fetch_spatial_code(args.scene_id)
tests/test_A/test_A.py CHANGED
@@ -1,10 +1,35 @@
1
  """Tests for harness/A/__init__.py -- shared config constants."""
2
 
 
3
  from pathlib import Path
4
 
 
 
5
  from harness import A
6
 
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  def test_generation_protocol_matches_vsibench_yaml():
9
  # thinking-in-space/lmms_eval/tasks/vsibench/vsibench.yaml generation_kwargs.
10
  assert A.MAX_NEW_TOKENS == 16
@@ -12,7 +37,7 @@ def test_generation_protocol_matches_vsibench_yaml():
12
  assert A.DO_SAMPLE is False
13
 
14
 
15
- def test_extended_generation_protocol():
16
  assert A.EXTENDED_MAX_NEW_TOKENS == 2048
17
  assert A.EXTENDED_MAX_NEW_TOKENS > A.MAX_NEW_TOKENS
18
  assert isinstance(A.FORCE_ANSWER_PROMPT, str) and A.FORCE_ANSWER_PROMPT.strip()
 
1
  """Tests for harness/A/__init__.py -- shared config constants."""
2
 
3
+ from argparse import ArgumentParser, Namespace
4
  from pathlib import Path
5
 
6
+ import pytest
7
+
8
  from harness import A
9
 
10
 
11
+ def test_thinking_mode_resolves_default_budgets():
12
+ args = Namespace(extended=True, reasoning_budget=None, force_budget=None)
13
+ A.resolve_protocol_budgets(ArgumentParser(), args)
14
+ assert args.reasoning_budget == A.EXTENDED_MAX_NEW_TOKENS
15
+ assert args.force_budget == A.MAX_NEW_TOKENS
16
+
17
+
18
+ def test_base_mode_keeps_budgets_unset_without_budget_flags():
19
+ args = Namespace(extended=False, reasoning_budget=None, force_budget=None)
20
+ A.resolve_protocol_budgets(ArgumentParser(), args)
21
+ assert args.reasoning_budget is None
22
+ assert args.force_budget is None
23
+
24
+
25
+ @pytest.mark.parametrize("flag", ["reasoning_budget", "force_budget"])
26
+ def test_base_mode_rejects_thinking_budget_flags(flag):
27
+ args = Namespace(extended=False, reasoning_budget=None, force_budget=None)
28
+ setattr(args, flag, 8)
29
+ with pytest.raises(SystemExit):
30
+ A.resolve_protocol_budgets(ArgumentParser(), args)
31
+
32
+
33
  def test_generation_protocol_matches_vsibench_yaml():
34
  # thinking-in-space/lmms_eval/tasks/vsibench/vsibench.yaml generation_kwargs.
35
  assert A.MAX_NEW_TOKENS == 16
 
37
  assert A.DO_SAMPLE is False
38
 
39
 
40
+ def test_thinking_generation_protocol():
41
  assert A.EXTENDED_MAX_NEW_TOKENS == 2048
42
  assert A.EXTENDED_MAX_NEW_TOKENS > A.MAX_NEW_TOKENS
43
  assert isinstance(A.FORCE_ANSWER_PROMPT, str) and A.FORCE_ANSWER_PROMPT.strip()
tests/test_A/test_init.py CHANGED
@@ -10,7 +10,7 @@ def test_generation_protocol_matches_vsibench_yaml():
10
  assert A.DO_SAMPLE is False
11
 
12
 
13
- def test_extended_generation_protocol():
14
  assert A.EXTENDED_MAX_NEW_TOKENS == 2048
15
  assert A.EXTENDED_MAX_NEW_TOKENS > A.MAX_NEW_TOKENS
16
  assert isinstance(A.FORCE_ANSWER_PROMPT, str) and A.FORCE_ANSWER_PROMPT.strip()
@@ -28,7 +28,10 @@ def test_default_frame_selection_is_a_valid_selection():
28
 
29
  def test_model_paths_cover_every_registered_model():
30
  assert set(A.MODEL_PATHS) == {
31
- "qwen3.5-4b", "qwen3.5-2b", "internvl3.5-4b", "internvl3.5-2b",
 
 
 
32
  }
33
  for path in A.MODEL_PATHS.values():
34
  assert path.parent == A.MODELS_ROOT
@@ -36,3 +39,22 @@ def test_model_paths_cover_every_registered_model():
36
 
37
  def test_results_dir_defaults_under_workspace_results():
38
  assert A.RESULTS_DIR == A.WORKSPACE_ROOT / "results" / "A"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  assert A.DO_SAMPLE is False
11
 
12
 
13
+ def test_thinking_generation_protocol():
14
  assert A.EXTENDED_MAX_NEW_TOKENS == 2048
15
  assert A.EXTENDED_MAX_NEW_TOKENS > A.MAX_NEW_TOKENS
16
  assert isinstance(A.FORCE_ANSWER_PROMPT, str) and A.FORCE_ANSWER_PROMPT.strip()
 
28
 
29
  def test_model_paths_cover_every_registered_model():
30
  assert set(A.MODEL_PATHS) == {
31
+ "qwen3.5-4b",
32
+ "qwen3.5-2b",
33
+ "internvl3.5-4b",
34
+ "internvl3.5-2b",
35
  }
36
  for path in A.MODEL_PATHS.values():
37
  assert path.parent == A.MODELS_ROOT
 
39
 
40
  def test_results_dir_defaults_under_workspace_results():
41
  assert A.RESULTS_DIR == A.WORKSPACE_ROOT / "results" / "A"
42
+
43
+
44
+ def test_question_protocol_policy_is_hardcoded_by_group():
45
+ assert A.question_group("object_counting") == "numerical"
46
+ assert A.protocol_for_question("object_counting") == "base"
47
+ assert A.question_group("route_planning") == "multiple_choice"
48
+ assert A.protocol_for_question("route_planning") == "thinking"
49
+
50
+
51
+ def test_every_known_question_type_has_one_policy_group():
52
+ for question_type in A.NUMERICAL_QUESTION_TYPES:
53
+ assert (
54
+ A.protocol_for_question(question_type) == A.QUESTION_PROTOCOLS["numerical"]
55
+ )
56
+ for question_type in A.MULTIPLE_CHOICE_QUESTION_TYPES:
57
+ assert (
58
+ A.protocol_for_question(question_type)
59
+ == A.QUESTION_PROTOCOLS["multiple_choice"]
60
+ )
tests/test_A/test_models.py CHANGED
@@ -38,12 +38,6 @@ def test_get_adapter_rejects_unknown_model():
38
  vlm_models.get_adapter("not-a-real-model")
39
 
40
 
41
- def test_qwen_adapter_disables_thinking_mode():
42
- # Otherwise Qwen3.5's default template opens an unclosed <think> block that would
43
- # consume the entire 16-token budget before ever emitting an answer.
44
- assert vlm_models.QwenVLAdapter.chat_template_kwargs == {"enable_thinking": False}
45
-
46
-
47
  def test_internvl_adapter_disables_per_frame_tiling():
48
  # Otherwise InternVL's default per-image dynamic tiling (~3300 tokens/frame) blows
49
  # past this checkpoint's 40960-token context window at just 16 frames.
@@ -90,3 +84,11 @@ def test_unload_clears_model_and_processor():
90
  adapter.unload()
91
  assert adapter.model is None
92
  assert adapter.processor is None
 
 
 
 
 
 
 
 
 
38
  vlm_models.get_adapter("not-a-real-model")
39
 
40
 
 
 
 
 
 
 
41
  def test_internvl_adapter_disables_per_frame_tiling():
42
  # Otherwise InternVL's default per-image dynamic tiling (~3300 tokens/frame) blows
43
  # past this checkpoint's 40960-token context window at just 16 frames.
 
84
  adapter.unload()
85
  assert adapter.model is None
86
  assert adapter.processor is None
87
+
88
+
89
+ def test_native_video_content_uses_one_video_item():
90
+ content = vlm_models._numbered_content("/data/scene.mp4", "What is in the room?")
91
+ assert content == [
92
+ {"type": "video", "video": "/data/scene.mp4"},
93
+ {"type": "text", "text": "What is in the room?"},
94
+ ]
tests/test_A/test_prompts.py CHANGED
@@ -48,3 +48,8 @@ def test_every_mca_question_type_builds_with_options(question_type):
48
  prompt = vsi_prompts.build_prompt(question_type, "q?", ["A. x", "B. y"])
49
  assert prompt.startswith(vsi_prompts.PRE_PROMPT)
50
  assert prompt.endswith(vsi_prompts.MCA_POST_PROMPT)
 
 
 
 
 
 
48
  prompt = vsi_prompts.build_prompt(question_type, "q?", ["A. x", "B. y"])
49
  assert prompt.startswith(vsi_prompts.PRE_PROMPT)
50
  assert prompt.endswith(vsi_prompts.MCA_POST_PROMPT)
51
+
52
+
53
+ def test_video_prompt_names_native_video():
54
+ prompt = vsi_prompts.build_prompt("object_counting", "How many chairs?", video=True)
55
+ assert prompt.startswith("This is a video.\n")
tests/test_A/test_run.py CHANGED
@@ -102,13 +102,13 @@ def test_scalar_score_rejects_unknown_question_type():
102
 
103
  def test_results_dir_for_matches_established_dimension_nesting():
104
  root = harness_run.results_dir_for("qwen3.5-4b", "base", "selective", 32)
105
- assert root == A.RESULTS_DIR / "qwen3.5-4b" / "base" / "selective" / "32"
106
 
107
 
108
- def test_results_dir_for_isolates_the_two_protocols():
109
  base = harness_run.results_dir_for("qwen3.5-4b", "base", "selective", 32)
110
- extended = harness_run.results_dir_for("qwen3.5-4b", "extended", "selective", 32)
111
- assert base != extended
112
 
113
 
114
  def test_results_dir_for_honors_explicit_override(tmp_path):
@@ -211,3 +211,19 @@ def test_build_record_carries_reasoning_fields_when_extended():
211
  assert record["reasoning_hit_limit"] is True
212
  assert record["forced"] is True
213
  assert record["forced_input_token_count"] == 2510
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
  def test_results_dir_for_matches_established_dimension_nesting():
104
  root = harness_run.results_dir_for("qwen3.5-4b", "base", "selective", 32)
105
+ assert root == A.RESULTS_DIR / "qwen3.5-4b" / "selective" / "32"
106
 
107
 
108
+ def test_results_dir_for_keeps_protocols_together():
109
  base = harness_run.results_dir_for("qwen3.5-4b", "base", "selective", 32)
110
+ extended = harness_run.results_dir_for("qwen3.5-4b", "thinking", "selective", 32)
111
+ assert base == extended
112
 
113
 
114
  def test_results_dir_for_honors_explicit_override(tmp_path):
 
211
  assert record["reasoning_hit_limit"] is True
212
  assert record["forced"] is True
213
  assert record["forced_input_token_count"] == 2510
214
+
215
+
216
+ def test_video_results_use_video_branch():
217
+ assert (
218
+ harness_run.results_dir_for("qwen3.5-4b", "thinking", "video", None)
219
+ == A.RESULTS_DIR / "qwen3.5-4b" / "video"
220
+ )
221
+
222
+
223
+ def test_video_record_has_no_frame_count_in_condition():
224
+ info = dict(_FAKE_FRAME_INFO, frame_selection="video", frame_count=None)
225
+ record = harness_run._build_record(
226
+ _FAKE_ROW, "prompt", _FAKE_ANSWER, "metric", 1.0, "qwen3.5-4b", "/model", info
227
+ )
228
+ assert record["condition"] == "base:video"
229
+ assert record["frame_count"] is None
tests/test_B/test_B.py CHANGED
@@ -5,8 +5,8 @@ from pathlib import Path
5
  from harness import A, B
6
 
7
 
8
- def test_spatial_code_formats_match_the_two_on_disk_schemas():
9
- assert B.SPATIAL_CODE_FORMATS == ("explicit", "compact")
10
  assert B.DEFAULT_SPATIAL_CODE_FORMAT in B.SPATIAL_CODE_FORMATS
11
 
12
 
 
5
  from harness import A, B
6
 
7
 
8
+ def test_spatial_code_formats_is_explicit_only():
9
+ assert B.SPATIAL_CODE_FORMATS == ("explicit",)
10
  assert B.DEFAULT_SPATIAL_CODE_FORMAT in B.SPATIAL_CODE_FORMATS
11
 
12
 
tests/test_B/test_init.py CHANGED
@@ -3,8 +3,8 @@
3
  from harness import A, B
4
 
5
 
6
- def test_spatial_code_formats_match_the_two_on_disk_schemas():
7
- assert B.SPATIAL_CODE_FORMATS == ("explicit", "compact")
8
  assert B.DEFAULT_SPATIAL_CODE_FORMAT in B.SPATIAL_CODE_FORMATS
9
 
10
 
 
3
  from harness import A, B
4
 
5
 
6
+ def test_spatial_code_formats_is_explicit_only():
7
+ assert B.SPATIAL_CODE_FORMATS == ("explicit",)
8
  assert B.DEFAULT_SPATIAL_CODE_FORMAT in B.SPATIAL_CODE_FORMATS
9
 
10
 
tests/test_B/test_run.py CHANGED
@@ -40,7 +40,7 @@ _FAKE_ROW = {
40
  }
41
 
42
  _FAKE_CODE_INFO = {
43
- "protocol": "extended",
44
  "spatial_code_format": "explicit",
45
  "input_selection": "selective",
46
  "frame_count": 64,
@@ -52,13 +52,12 @@ _FAKE_CODE_INFO = {
52
 
53
  def test_results_dir_for_matches_established_dimension_nesting():
54
  root = harness_run.results_dir_for(
55
- "qwen3.5-4b", "extended", "compact", "metric", "tracking", "uniform", 32
56
  )
57
  assert root == (
58
  B.RESULTS_DIR
59
  / "qwen3.5-4b"
60
- / "extended"
61
- / "compact"
62
  / "metric"
63
  / "tracking"
64
  / "uniform"
@@ -66,14 +65,14 @@ def test_results_dir_for_matches_established_dimension_nesting():
66
  )
67
 
68
 
69
- def test_results_dir_for_isolates_the_two_protocols():
70
  base = harness_run.results_dir_for(
71
- "qwen3.5-4b", "base", "compact", "metric", "tracking", "uniform", 32
72
  )
73
  extended = harness_run.results_dir_for(
74
- "qwen3.5-4b", "extended", "compact", "metric", "tracking", "uniform", 32
75
  )
76
- assert base != extended
77
 
78
 
79
  def test_results_dir_for_honors_explicit_override(tmp_path):
@@ -113,7 +112,7 @@ def test_build_record_preserves_every_field_untruncated():
113
  assert record["tracking"] == "tracking"
114
  assert record["spatial_code_path"] == _FAKE_CODE_INFO["spatial_code_path"]
115
  assert record["condition"] == "extended:explicit:metric:tracking:selective:64"
116
- assert record["protocol"] == "extended"
117
  assert record["vision_input_shapes"] == {"mm_token_type_ids": [1, 2558]}
118
  assert record["generation_config"] == _FAKE_ANSWER["generation_config"]
119
  assert record["metric"] == "MRA:.5:.95:.05"
@@ -212,3 +211,21 @@ def test_run_strip_schema_legend_removes_only_the_legend(monkeypatch):
212
  assert results
213
  assert "spatial code schema" not in seen["prompt"]
214
  assert '"chair"' in seen["prompt"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  }
41
 
42
  _FAKE_CODE_INFO = {
43
+ "protocol": "thinking",
44
  "spatial_code_format": "explicit",
45
  "input_selection": "selective",
46
  "frame_count": 64,
 
52
 
53
  def test_results_dir_for_matches_established_dimension_nesting():
54
  root = harness_run.results_dir_for(
55
+ "qwen3.5-4b", "thinking", "explicit", "metric", "tracking", "uniform", 32
56
  )
57
  assert root == (
58
  B.RESULTS_DIR
59
  / "qwen3.5-4b"
60
+ / "explicit"
 
61
  / "metric"
62
  / "tracking"
63
  / "uniform"
 
65
  )
66
 
67
 
68
+ def test_results_dir_for_keeps_protocols_together():
69
  base = harness_run.results_dir_for(
70
+ "qwen3.5-4b", "base", "explicit", "metric", "tracking", "uniform", 32
71
  )
72
  extended = harness_run.results_dir_for(
73
+ "qwen3.5-4b", "thinking", "explicit", "metric", "tracking", "uniform", 32
74
  )
75
+ assert base == extended
76
 
77
 
78
  def test_results_dir_for_honors_explicit_override(tmp_path):
 
112
  assert record["tracking"] == "tracking"
113
  assert record["spatial_code_path"] == _FAKE_CODE_INFO["spatial_code_path"]
114
  assert record["condition"] == "extended:explicit:metric:tracking:selective:64"
115
+ assert record["protocol"] == "thinking"
116
  assert record["vision_input_shapes"] == {"mm_token_type_ids": [1, 2558]}
117
  assert record["generation_config"] == _FAKE_ANSWER["generation_config"]
118
  assert record["metric"] == "MRA:.5:.95:.05"
 
211
  assert results
212
  assert "spatial code schema" not in seen["prompt"]
213
  assert '"chair"' in seen["prompt"]
214
+
215
+
216
+ def test_video_results_use_video_branch():
217
+ assert (
218
+ harness_run.results_dir_for(
219
+ "qwen3.5-4b", "thinking", "explicit", "metric", "tracking", "video", None
220
+ )
221
+ == B.RESULTS_DIR / "qwen3.5-4b" / "explicit" / "metric" / "tracking" / "video"
222
+ )
223
+
224
+
225
+ def test_video_record_has_no_frame_count_in_condition():
226
+ info = dict(_FAKE_CODE_INFO, input_selection="video", frame_count=None)
227
+ record = harness_run._build_record(
228
+ _FAKE_ROW, "prompt", _FAKE_ANSWER, "metric", 1.0, "qwen3.5-4b", "/model", info
229
+ )
230
+ assert record["condition"] == "thinking:explicit:metric:tracking:video"
231
+ assert record["frame_count"] is None
tests/test_B/test_spatial_codes.py CHANGED
@@ -33,16 +33,16 @@ def test_load_spatial_code_returns_dict_and_path(tmp_path, monkeypatch):
33
  spatial_codes, "spatial_code_path", lambda *a, **k: str(fixture)
34
  )
35
  code, path = spatial_codes.load_spatial_code(
36
- "13c3e046d7", "metric", "selective", "tracking", 64, "compact"
37
  )
38
  assert code == {"objects": {}, "room": {}}
39
  assert path == str(fixture)
40
 
41
 
42
- def test_spatial_code_path_includes_every_cache_axis():
43
  path = spatial_codes.spatial_code_path(
44
  "scene-a", "metric", "selective", "tracking", 64, "explicit"
45
  )
46
  assert path.endswith(
47
- "data/spatial codes/sam3+depth-anything-3/metric/tracking/selective/64/explicit/scene-a.json"
48
  )
 
33
  spatial_codes, "spatial_code_path", lambda *a, **k: str(fixture)
34
  )
35
  code, path = spatial_codes.load_spatial_code(
36
+ "13c3e046d7", "metric", "selective", "tracking", 64, "explicit"
37
  )
38
  assert code == {"objects": {}, "room": {}}
39
  assert path == str(fixture)
40
 
41
 
42
+ def test_spatial_code_path_uses_tracking_frames_hierarchy():
43
  path = spatial_codes.spatial_code_path(
44
  "scene-a", "metric", "selective", "tracking", 64, "explicit"
45
  )
46
  assert path.endswith(
47
+ "data/spatial codes/sam3+depth-anything-3/tracking/frames/selective/64/explicit/scene-a.json"
48
  )
tests/test_B/test_sweep.py CHANGED
@@ -9,15 +9,15 @@ from harness.B import sweep
9
  def test_build_plan_covers_every_combination():
10
  plan = sweep.build_plan(
11
  ["qwen3.5-2b", "qwen3.5-4b"],
12
- ["explicit", "compact"],
13
  ["uniform", "selective"],
14
  [16, 32],
15
  ["metric"],
16
  ["tracking"],
17
  )
18
- assert len(plan) == 2 * 2 * 2 * 2
19
  assert ("qwen3.5-2b", "explicit", "metric", "tracking", "uniform", 16) in plan
20
- assert ("qwen3.5-4b", "compact", "metric", "tracking", "selective", 32) in plan
21
 
22
 
23
  def test_build_plan_sweeps_depth_and_tracking_too():
@@ -57,13 +57,6 @@ def test_build_plan_with_all_registered_models():
57
  assert len(plan) == len(vlm_models.available_models())
58
 
59
 
60
- def test_sweep_parser_rejects_unknown_spatial_code_format():
61
- with pytest.raises(ValueError):
62
- sweep._parse_csv_choice(
63
- "bogus", ("explicit", "compact"), "--spatial-code-formats"
64
- )
65
-
66
-
67
  def test_sweep_parser_rejects_unknown_depth():
68
  with pytest.raises(ValueError):
69
  sweep._parse_csv_choice("bogus", sweep.DEPTH_VARIANTS, "--depths")
 
9
  def test_build_plan_covers_every_combination():
10
  plan = sweep.build_plan(
11
  ["qwen3.5-2b", "qwen3.5-4b"],
12
+ ["explicit"],
13
  ["uniform", "selective"],
14
  [16, 32],
15
  ["metric"],
16
  ["tracking"],
17
  )
18
+ assert len(plan) == 2 * 1 * 2 * 2
19
  assert ("qwen3.5-2b", "explicit", "metric", "tracking", "uniform", 16) in plan
20
+ assert ("qwen3.5-4b", "explicit", "metric", "tracking", "selective", 32) in plan
21
 
22
 
23
  def test_build_plan_sweeps_depth_and_tracking_too():
 
57
  assert len(plan) == len(vlm_models.available_models())
58
 
59
 
 
 
 
 
 
 
 
60
  def test_sweep_parser_rejects_unknown_depth():
61
  with pytest.raises(ValueError):
62
  sweep._parse_csv_choice("bogus", sweep.DEPTH_VARIANTS, "--depths")
tests/test_C/test_launch.py CHANGED
@@ -37,39 +37,6 @@ def test_launch_skips_scene_already_fully_answered(tmp_path, capsys, monkeypatch
37
  assert "DONE: 1 ok, 0 failed" in output
38
 
39
 
40
- def test_launch_routes_overlay_to_overlay_result_tree(monkeypatch, capsys, tmp_path):
41
- captured = {}
42
-
43
- root = tmp_path / "unused-results"
44
- scene_dir = root / "scene"
45
- scene_dir.mkdir(parents=True, exist_ok=True)
46
- (scene_dir / "1.json").write_text("{}")
47
-
48
- class FakeRun:
49
-
50
- def results_dir_for(*args, **kwargs):
51
- captured["overlay"] = kwargs.get("overlay")
52
- return root
53
-
54
- def load_questions(scene=None):
55
- return [{"id": 1}]
56
-
57
- monkeypatch.setattr(launch, "_load_run_module", lambda: FakeRun)
58
-
59
- launch.launch(
60
- "qwen3.5-2b",
61
- "explicit",
62
- "uniform",
63
- 32,
64
- ["scene"],
65
- overlay=True,
66
- strip_schema_legend=True,
67
- )
68
-
69
- assert captured["overlay"] is True
70
- assert "DONE: 1 ok, 0 failed" in capsys.readouterr().out
71
-
72
-
73
  def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch):
74
  scene = "scene-c"
75
  monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun)
 
37
  assert "DONE: 1 ok, 0 failed" in output
38
 
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch):
41
  scene = "scene-c"
42
  monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun)
tests/test_C/test_prompts.py CHANGED
@@ -57,3 +57,10 @@ def test_every_na_question_type_builds(question_type):
57
  def test_every_mca_question_type_builds(question_type):
58
  prompt = combined_prompts.build_prompt(_CODE, question_type, "q?", ["A. x", "B. y"])
59
  assert prompt.startswith(combined_prompts.PRE_PROMPT)
 
 
 
 
 
 
 
 
57
  def test_every_mca_question_type_builds(question_type):
58
  prompt = combined_prompts.build_prompt(_CODE, question_type, "q?", ["A. x", "B. y"])
59
  assert prompt.startswith(combined_prompts.PRE_PROMPT)
60
+
61
+
62
+ def test_video_prompt_names_native_video():
63
+ prompt = combined_prompts.build_prompt(
64
+ _CODE, "object_counting", "How many chairs?", video=True
65
+ )
66
+ assert prompt.startswith("This is a video.\n")
tests/test_C/test_run.py CHANGED
@@ -40,7 +40,7 @@ _FAKE_ROW = {
40
  }
41
 
42
  _FAKE_SOURCE_INFO = {
43
- "protocol": "extended",
44
  "spatial_code_format": "explicit",
45
  "input_selection": "selective",
46
  "frame_count": 64,
@@ -55,13 +55,12 @@ _FAKE_SOURCE_INFO = {
55
 
56
  def test_results_dir_for_matches_established_dimension_nesting():
57
  root = harness_run.results_dir_for(
58
- "qwen3.5-4b", "extended", "compact", "metric", "tracking", "uniform", 32
59
  )
60
  assert root == (
61
  C.RESULTS_DIR
62
  / "qwen3.5-4b"
63
- / "extended"
64
- / "compact"
65
  / "metric"
66
  / "tracking"
67
  / "uniform"
@@ -83,30 +82,6 @@ def test_results_dir_for_honors_explicit_override(tmp_path):
83
  assert root == tmp_path
84
 
85
 
86
- def test_results_dir_for_places_overlay_under_C_results():
87
- root = harness_run.results_dir_for(
88
- "qwen3.5-4b",
89
- "extended",
90
- "explicit",
91
- "metric",
92
- "tracking",
93
- "uniform",
94
- 32,
95
- overlay=True,
96
- )
97
- assert root == (
98
- C.RESULTS_DIR
99
- / "overlay"
100
- / "qwen3.5-4b"
101
- / "extended"
102
- / "explicit"
103
- / "metric"
104
- / "tracking"
105
- / "uniform"
106
- / "32"
107
- )
108
-
109
-
110
  def test_build_record_carries_both_frame_and_spatial_code_provenance():
111
  record = harness_run._build_record(
112
  _FAKE_ROW,
@@ -134,7 +109,7 @@ def test_build_record_carries_both_frame_and_spatial_code_provenance():
134
  assert record["answer_given"] == "4"
135
  assert record["vision_input_shapes"] == _FAKE_ANSWER["vision_input_shapes"]
136
  assert record["condition"] == "extended:explicit:metric:tracking:selective:64"
137
- assert record["protocol"] == "extended"
138
  assert record["score"] == 1.0
139
 
140
 
@@ -155,36 +130,6 @@ def test_write_question_result_writes_one_json_file_per_question(tmp_path):
155
  assert on_disk == record
156
 
157
 
158
- def test_write_question_result_routes_overlay_default_to_overlay_tree(
159
- tmp_path, monkeypatch
160
- ):
161
- monkeypatch.setattr(harness_run, "RESULTS_DIR", tmp_path)
162
- source_info = {**_FAKE_SOURCE_INFO, "overlay": True}
163
- path, _record = harness_run.write_question_result(
164
- _FAKE_ROW,
165
- "full prompt text",
166
- _FAKE_ANSWER,
167
- "MRA:.5:.95:.05",
168
- 1.0,
169
- "qwen3.5-4b",
170
- "/root/models/qwen3.5-4b",
171
- source_info,
172
- )
173
- assert path == (
174
- tmp_path
175
- / "overlay"
176
- / "qwen3.5-4b"
177
- / "extended"
178
- / "explicit"
179
- / "metric"
180
- / "tracking"
181
- / "selective"
182
- / "64"
183
- / "scene0001_00"
184
- / "7.json"
185
- )
186
-
187
-
188
  def test_build_record_carries_reasoning_fields_when_forced():
189
  extended_answer = {
190
  **_FAKE_ANSWER,
@@ -211,3 +156,21 @@ def test_build_record_carries_reasoning_fields_when_forced():
211
  )
212
  assert record["forced"] is True
213
  assert record["forced_input_token_count"] == 22300
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  }
41
 
42
  _FAKE_SOURCE_INFO = {
43
+ "protocol": "thinking",
44
  "spatial_code_format": "explicit",
45
  "input_selection": "selective",
46
  "frame_count": 64,
 
55
 
56
  def test_results_dir_for_matches_established_dimension_nesting():
57
  root = harness_run.results_dir_for(
58
+ "qwen3.5-4b", "thinking", "explicit", "metric", "tracking", "uniform", 32
59
  )
60
  assert root == (
61
  C.RESULTS_DIR
62
  / "qwen3.5-4b"
63
+ / "explicit"
 
64
  / "metric"
65
  / "tracking"
66
  / "uniform"
 
82
  assert root == tmp_path
83
 
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  def test_build_record_carries_both_frame_and_spatial_code_provenance():
86
  record = harness_run._build_record(
87
  _FAKE_ROW,
 
109
  assert record["answer_given"] == "4"
110
  assert record["vision_input_shapes"] == _FAKE_ANSWER["vision_input_shapes"]
111
  assert record["condition"] == "extended:explicit:metric:tracking:selective:64"
112
+ assert record["protocol"] == "thinking"
113
  assert record["score"] == 1.0
114
 
115
 
 
130
  assert on_disk == record
131
 
132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  def test_build_record_carries_reasoning_fields_when_forced():
134
  extended_answer = {
135
  **_FAKE_ANSWER,
 
156
  )
157
  assert record["forced"] is True
158
  assert record["forced_input_token_count"] == 22300
159
+
160
+
161
+ def test_video_results_use_video_branch():
162
+ assert (
163
+ harness_run.results_dir_for(
164
+ "qwen3.5-4b", "thinking", "explicit", "metric", "tracking", "video", None
165
+ )
166
+ == C.RESULTS_DIR / "qwen3.5-4b" / "explicit" / "metric" / "tracking" / "video"
167
+ )
168
+
169
+
170
+ def test_video_record_has_no_frame_count_in_condition():
171
+ info = dict(_FAKE_SOURCE_INFO, input_selection="video", frame_count=None)
172
+ record = harness_run._build_record(
173
+ _FAKE_ROW, "prompt", _FAKE_ANSWER, "metric", 1.0, "qwen3.5-4b", "/model", info
174
+ )
175
+ assert record["condition"] == "thinking:explicit:metric:tracking:video"
176
+ assert record["frame_count"] is None
tests/test_C/test_sweep.py CHANGED
@@ -9,15 +9,15 @@ from harness.C import sweep
9
  def test_build_plan_covers_every_combination():
10
  plan = sweep.build_plan(
11
  ["qwen3.5-2b", "qwen3.5-4b"],
12
- ["explicit", "compact"],
13
  ["uniform", "selective"],
14
  [16, 32],
15
  ["metric"],
16
  ["tracking"],
17
  )
18
- assert len(plan) == 2 * 2 * 2 * 2
19
  assert ("qwen3.5-2b", "explicit", "metric", "tracking", "uniform", 16) in plan
20
- assert ("qwen3.5-4b", "compact", "metric", "tracking", "selective", 32) in plan
21
 
22
 
23
  def test_build_plan_sweeps_depth_and_tracking_too():
@@ -57,34 +57,6 @@ def test_build_plan_with_all_registered_models():
57
  assert len(plan) == len(vlm_models.available_models())
58
 
59
 
60
- def test_sweep_forwards_overlay_to_each_launch(monkeypatch):
61
- calls = []
62
- monkeypatch.setattr(
63
- sweep.harness_launch, "launch", lambda *args, **kwargs: calls.append(kwargs)
64
- )
65
-
66
- sweep.sweep(
67
- ["qwen3.5-2b"],
68
- ["explicit"],
69
- ["uniform"],
70
- [32],
71
- ["scene"],
72
- overlay=True,
73
- strip_schema_legend=True,
74
- )
75
-
76
- assert len(calls) == 1
77
- assert calls[0]["overlay"] is True
78
- assert calls[0]["results_dir"] is None
79
-
80
-
81
- def test_sweep_parser_rejects_unknown_spatial_code_format():
82
- with pytest.raises(ValueError):
83
- sweep._parse_csv_choice(
84
- "bogus", ("explicit", "compact"), "--spatial-code-formats"
85
- )
86
-
87
-
88
  def test_sweep_parser_rejects_unknown_depth():
89
  with pytest.raises(ValueError):
90
  sweep._parse_csv_choice("bogus", sweep.DEPTH_VARIANTS, "--depths")
 
9
  def test_build_plan_covers_every_combination():
10
  plan = sweep.build_plan(
11
  ["qwen3.5-2b", "qwen3.5-4b"],
12
+ ["explicit"],
13
  ["uniform", "selective"],
14
  [16, 32],
15
  ["metric"],
16
  ["tracking"],
17
  )
18
+ assert len(plan) == 2 * 1 * 2 * 2
19
  assert ("qwen3.5-2b", "explicit", "metric", "tracking", "uniform", 16) in plan
20
+ assert ("qwen3.5-4b", "explicit", "metric", "tracking", "selective", 32) in plan
21
 
22
 
23
  def test_build_plan_sweeps_depth_and_tracking_too():
 
57
  assert len(plan) == len(vlm_models.available_models())
58
 
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  def test_sweep_parser_rejects_unknown_depth():
61
  with pytest.raises(ValueError):
62
  sweep._parse_csv_choice("bogus", sweep.DEPTH_VARIANTS, "--depths")
tests/test_F/test_sweep.py CHANGED
@@ -12,38 +12,3 @@ def test_csv_expands_all_dedups_and_rejects_unknowns():
12
  sweep._csv("c", ("a", "b"))
13
 
14
 
15
- def test_main_routes_ground_truth_without_perception_axes(monkeypatch, capsys):
16
- calls = []
17
- monkeypatch.setattr(sweep.harness_run, "SOURCES", ("ground truth",))
18
- monkeypatch.setattr(
19
- sweep.symbolic_run, "SPATIAL_CODE_FORMATS", ("compact", "explicit")
20
- )
21
- monkeypatch.setattr(sweep.symbolic_run, "DEPTH_VARIANTS", ("metric",))
22
- monkeypatch.setattr(sweep.symbolic_run, "TRACKING_MODES", ("tracking",))
23
- monkeypatch.setattr(sweep.symbolic_run, "INPUT_SELECTIONS", ("uniform",))
24
- monkeypatch.setattr(
25
- sweep.harness_run,
26
- "run",
27
- lambda *args, **kwargs: calls.append((args, kwargs)) or [{"score": 1.0}],
28
- )
29
- monkeypatch.setattr(
30
- "sys.argv",
31
- [
32
- "sweep",
33
- "--sources",
34
- "ground truth",
35
- "--spatial-code-formats",
36
- "all",
37
- "--scenes",
38
- "s1,s1,s2",
39
- ],
40
- )
41
-
42
- sweep.main()
43
-
44
- assert [call[0][:6] for call in calls] == [
45
- ("ground truth", "compact", "metric", "tracking", "uniform", 32),
46
- ("ground truth", "explicit", "metric", "tracking", "uniform", 32),
47
- ]
48
- assert all(call[1]["scenes"] == ["s1", "s2"] for call in calls)
49
- assert "ground truth compact" in capsys.readouterr().out
 
12
  sweep._csv("c", ("a", "b"))
13
 
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_analysis/conftest.py CHANGED
@@ -37,8 +37,6 @@ def vlm(letter, qid=1, score=1.0, protocol="base", model="m", frames=32):
37
  depth="metric",
38
  tracking="tracking",
39
  )
40
- elif letter == "D":
41
- r["spatial_code_format"] = "explicit"
42
  return r
43
 
44
 
 
37
  depth="metric",
38
  tracking="tracking",
39
  )
 
 
40
  return r
41
 
42
 
tests/test_analysis/test_letters_reports.py CHANGED
@@ -13,20 +13,6 @@ class TestLettersReports(ReportTestCase):
13
  {"A_report.json", "C_report.json", "AC_report.json"},
14
  )
15
 
16
- def test_DF_and_BF_semantic_alignment(self):
17
- d = self.directory("D", [vlm("D")])
18
- f = self.ground_truth_symbolic()
19
- result = letters_reports.generate(
20
- {"D": d, "F": f}, ["base"], output_dir=self.root / "df"
21
- )
22
- self.assertEqual(len(result["combined_report"]["cross_harness_comparisons"]), 1)
23
- b = self.directory("B", [vlm("B")])
24
- perceived = self.symbolic(False)
25
- result = letters_reports.generate(
26
- {"B": b, "F": perceived}, ["base"], output_dir=self.root / "bf"
27
- )
28
- self.assertEqual(len(result["combined_report"]["cross_harness_comparisons"]), 1)
29
-
30
  def test_folded_statistical_and_solver_helpers(self):
31
  self.assertEqual(
32
  letters_reports.holm_bonferroni({"a": 0.01, "b": 0.04, "c": 0.03}),
 
13
  {"A_report.json", "C_report.json", "AC_report.json"},
14
  )
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  def test_folded_statistical_and_solver_helpers(self):
17
  self.assertEqual(
18
  letters_reports.holm_bonferroni({"a": 0.01, "b": 0.04, "c": 0.03}),
tests/test_encoder/test_run.py CHANGED
@@ -5,3 +5,20 @@ from encoder import run
5
 
6
  def test_cache_or_load_exposes_explicit_dimensions():
7
  assert "frame_count" in run.cache_or_load.__code__.co_varnames
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  def test_cache_or_load_exposes_explicit_dimensions():
7
  assert "frame_count" in run.cache_or_load.__code__.co_varnames
8
+
9
+
10
+ def test_video_mode_preserves_depth_and_tracking():
11
+ assert run._effective_dimensions("relative", None, "tracking", True) == (
12
+ "relative",
13
+ "video",
14
+ "tracking",
15
+ )
16
+
17
+
18
+ def test_video_mode_selects_caches_for_requested_axes(tmp_path, monkeypatch):
19
+ monkeypatch.setattr(run.config, "CACHE_ROOT", tmp_path)
20
+ da3_path, sam3_path = run._cache_source_paths(
21
+ "scene", "relative", "video", "tracking", 32, True, None, None
22
+ )
23
+ assert da3_path.endswith("depth-anything-3/relative/video/scene.npz")
24
+ assert sam3_path.endswith("sam3/tracking/video/scene.pkl.gz")