Commit ·
f6d5531
1
Parent(s): 6009856
Restore repository before accidental workspace replacement
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- README.md +7 -7
- analysis/D_reports.py +34 -0
- analysis/letters_reports.py.orig +574 -0
- data/.vsi-environment.sh +17 -0
- data/caches/depth-anything-3.tar.zst +3 -0
- data/caches/depth-anything-3/depth-anything-3-metric-frames.zip +3 -0
- data/caches/depth-anything-3/depth-anything-3-metric-video.zip +3 -0
- data/caches/depth-anything-3/depth-anything-3-relative-frames.zip +3 -0
- data/caches/overlay-frames.tar.zst +3 -0
- data/caches/sam3/.gitkeep +1 -0
- data/caches/sam3/sam3-no-tracking-video.zip +3 -0
- data/caches/sam3/sam3-tracking-frames.zip +3 -0
- data/caches/segvggt.tar.zst +3 -0
- data/caches/selected-frames.tar.zst +3 -0
- data/spatial-codes.tar.zst +3 -0
- encoder/ground_truth.py +280 -0
- harness/C/__init__.py +14 -4
- harness/C/launch.py +1 -40
- harness/C/overlay.py +391 -0
- harness/C/overlay_launch.py +202 -0
- harness/C/run.py +10 -53
- harness/C/sweep.py +116 -85
- harness/D/__init__.py +42 -0
- harness/D/launch.py +340 -0
- harness/D/prompts.py +9 -0
- harness/D/run.py +457 -0
- harness/D/spatial_codes.py +32 -0
- harness/D/sweep.py +204 -0
- harness/D/symbolic_eval.py +152 -0
- harness/E/__init__.py +31 -0
- harness/E/launch.py +234 -0
- harness/E/prompts.py +36 -0
- harness/E/run.py +262 -0
- harness/E/sweep.py +115 -0
- tests/test_C/test_overlay.py +209 -0
- tests/test_C/test_overlay_launch.py +144 -0
- tests/test_D/__init__.py +0 -0
- tests/test_D/conftest.py +45 -0
- tests/test_D/test_D.py +21 -0
- tests/test_D/test_init.py +19 -0
- tests/test_D/test_launch.py +67 -0
- tests/test_D/test_prompts.py +55 -0
- tests/test_D/test_run.py +246 -0
- tests/test_D/test_spatial_codes.py +33 -0
- tests/test_D/test_sweep.py +28 -0
- tests/test_D/test_symbolic_eval.py +116 -0
- tests/test_E/__init__.py +0 -0
- tests/test_E/conftest.py +12 -0
- tests/test_E/test_E.py +20 -0
- tests/test_E/test_launch.py +66 -0
README.md
CHANGED
|
@@ -256,12 +256,12 @@ Files:
|
|
| 256 |
### Harness C: Frames Plus Spatial Code
|
| 257 |
|
| 258 |
```bash
|
| 259 |
-
python -m harness.C.run --model qwen3.5-4b --depth metric --tracking tracking --input-selection uniform --frames 32 --
|
| 260 |
-
python -m harness.C.launch --model qwen3.5-4b --depth metric --tracking tracking --input-selection uniform --frames 32
|
| 261 |
-
python -m harness.C.sweep --models all --depths metric --trackings tracking --input-selections uniform --frames 32
|
| 262 |
-
python -m harness.C.run --model qwen3.5-4b --depth metric --tracking tracking --
|
| 263 |
-
python -m harness.C.launch --model qwen3.5-4b --depth metric --tracking tracking --
|
| 264 |
-
python -m harness.C.sweep --models all --depths metric --trackings tracking --
|
| 265 |
```
|
| 266 |
|
| 267 |
Files:
|
|
@@ -270,7 +270,7 @@ Files:
|
|
| 270 |
- `harness/C/prompts.py`: combined frames + code prompt construction
|
| 271 |
- `harness/C/run.py`: one model/config/scene
|
| 272 |
- `harness/C/launch.py`: persistent GPU workers for one config
|
| 273 |
-
- `harness/C/sweep.py`: grid over
|
| 274 |
|
| 275 |
### Harness F: Symbolic Solver As A Harness
|
| 276 |
|
|
|
|
| 256 |
### Harness C: Frames Plus Spatial Code
|
| 257 |
|
| 258 |
```bash
|
| 259 |
+
python -m harness.C.run --model qwen3.5-4b --depth metric --tracking tracking --input-selection uniform --frames 32 --scene SCENE
|
| 260 |
+
python -m harness.C.launch --model qwen3.5-4b --depth metric --tracking tracking --input-selection uniform --frames 32
|
| 261 |
+
python -m harness.C.sweep --models all --depths metric --trackings tracking --input-selections uniform --frames 32
|
| 262 |
+
python -m harness.C.run --model qwen3.5-4b --depth metric --tracking tracking --video --scene SCENE
|
| 263 |
+
python -m harness.C.launch --model qwen3.5-4b --depth metric --tracking tracking --video
|
| 264 |
+
python -m harness.C.sweep --models all --depths metric --trackings tracking --video
|
| 265 |
```
|
| 266 |
|
| 267 |
Files:
|
|
|
|
| 270 |
- `harness/C/prompts.py`: combined frames + code prompt construction
|
| 271 |
- `harness/C/run.py`: one model/config/scene
|
| 272 |
- `harness/C/launch.py`: persistent GPU workers for one config
|
| 273 |
+
- `harness/C/sweep.py`: grid over model/depth/tracking/input/frame axes
|
| 274 |
|
| 275 |
### Harness F: Symbolic Solver As A Harness
|
| 276 |
|
analysis/D_reports.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generate the high-level within-D report."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from analysis.letters_reports import generate_letter
|
| 6 |
+
|
| 7 |
+
LETTER = "D"
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def generate(
|
| 11 |
+
results_dir,
|
| 12 |
+
protocols=(),
|
| 13 |
+
output_dir=None,
|
| 14 |
+
spatial_codes_dir=None,
|
| 15 |
+
profile_path=None,
|
| 16 |
+
):
|
| 17 |
+
return generate_letter(
|
| 18 |
+
LETTER, results_dir, protocols, output_dir, spatial_codes_dir, profile_path
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def main():
|
| 23 |
+
p = argparse.ArgumentParser(description="Generate the high-level within-D report.")
|
| 24 |
+
p.add_argument("--results-dir", default="/root/results/D")
|
| 25 |
+
p.add_argument("--protocol", action="append", default=[])
|
| 26 |
+
p.add_argument("--output-dir", default="/workspace/reports")
|
| 27 |
+
p.add_argument("--spatial-codes-dir", default=None)
|
| 28 |
+
a = p.parse_args()
|
| 29 |
+
result = generate(a.results_dir, a.protocol, a.output_dir, a.spatial_codes_dir)
|
| 30 |
+
print(f"wrote {result['path']}")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if __name__ == "__main__":
|
| 34 |
+
main()
|
analysis/letters_reports.py.orig
ADDED
|
@@ -0,0 +1,574 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Comprehensive, matched A/B/C result analysis.
|
| 2 |
+
|
| 3 |
+
Reports coverage, score, question-type and dataset breakdowns, response/prompt/token
|
| 4 |
+
lengths, latency, limit/forced rates, spatial-code size for B/C, score relationships,
|
| 5 |
+
and pairwise deltas on exact question intersections. Stored per-question scores are
|
| 6 |
+
used directly; ``mean_score`` is not the category-weighted official VSI overall.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
import math
|
| 13 |
+
import statistics
|
| 14 |
+
import random
|
| 15 |
+
from collections import Counter, defaultdict
|
| 16 |
+
from itertools import combinations
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 20 |
+
DEFAULT_DIRS = {h: ROOT / "results" / h for h in "ABC"}
|
| 21 |
+
NUMERIC_FIELDS = (
|
| 22 |
+
"input_token_count", "output_token_count", "reasoning_token_count",
|
| 23 |
+
"generation_seconds", "forced_input_token_count",
|
| 24 |
+
)
|
| 25 |
+
TEXT_FIELDS = (
|
| 26 |
+
"answer_given", "answer_raw", "reasoning_text", "full_prompt", "rendered_prompt",
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def iter_records(directory):
|
| 31 |
+
root = Path(directory)
|
| 32 |
+
if not root.is_dir():
|
| 33 |
+
return
|
| 34 |
+
for path in sorted(root.rglob("*.json")):
|
| 35 |
+
try:
|
| 36 |
+
with path.open(encoding="utf-8") as stream:
|
| 37 |
+
record = json.load(stream)
|
| 38 |
+
except (OSError, json.JSONDecodeError):
|
| 39 |
+
continue
|
| 40 |
+
if isinstance(record, dict) and "question_id" in record and "condition" in record:
|
| 41 |
+
yield record
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def protocol_selected(protocol, selectors):
|
| 45 |
+
if protocol is None:
|
| 46 |
+
return not selectors
|
| 47 |
+
return not selectors or any(
|
| 48 |
+
protocol == item or ("/" not in item and protocol.startswith(item + "/"))
|
| 49 |
+
for item in selectors
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def cell_identity(harness, record):
|
| 54 |
+
protocol = record.get("protocol") or record["condition"].split(":", 1)[0]
|
| 55 |
+
selection = record.get("frame_selection", record.get("input_selection"))
|
| 56 |
+
common = {
|
| 57 |
+
"harness": harness, "model": record.get("model"), "protocol": protocol,
|
| 58 |
+
"selection": selection, "frames": str(record.get("frame_count")),
|
| 59 |
+
}
|
| 60 |
+
if harness in ("B", "C"):
|
| 61 |
+
common.update({
|
| 62 |
+
"format": record.get("spatial_code_format"), "depth": record.get("depth"),
|
| 63 |
+
"tracking": record.get("tracking"),
|
| 64 |
+
})
|
| 65 |
+
return tuple(sorted(common.items()))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def identity_dict(identity):
|
| 69 |
+
return dict(identity)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def cell_label(identity):
|
| 73 |
+
d = identity_dict(identity)
|
| 74 |
+
parts = [d["harness"], d.get("model"), d.get("protocol"), d.get("selection"), d.get("frames")]
|
| 75 |
+
if d["harness"] in ("B", "C"):
|
| 76 |
+
parts += [d.get("format"), d.get("depth"), d.get("tracking")]
|
| 77 |
+
return "/".join("?" if value is None else str(value) for value in parts)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def comparison_key(identity):
|
| 81 |
+
d = identity_dict(identity)
|
| 82 |
+
return d.get("model"), d.get("protocol"), d.get("selection"), d.get("frames")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _numbers(records, getter):
|
| 86 |
+
out = []
|
| 87 |
+
for record in records:
|
| 88 |
+
value = getter(record)
|
| 89 |
+
if isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value):
|
| 90 |
+
out.append(float(value))
|
| 91 |
+
return out
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def numeric_summary(values):
|
| 95 |
+
values = sorted(values)
|
| 96 |
+
if not values:
|
| 97 |
+
return None
|
| 98 |
+
def percentile(p):
|
| 99 |
+
position = (len(values) - 1) * p
|
| 100 |
+
low, high = math.floor(position), math.ceil(position)
|
| 101 |
+
if low == high:
|
| 102 |
+
return values[low]
|
| 103 |
+
return values[low] + (values[high] - values[low]) * (position - low)
|
| 104 |
+
return {
|
| 105 |
+
"n": len(values), "mean": statistics.mean(values), "median": statistics.median(values),
|
| 106 |
+
"min": values[0], "p25": percentile(.25), "p75": percentile(.75), "max": values[-1],
|
| 107 |
+
"stdev": statistics.stdev(values) if len(values) > 1 else 0.0,
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def pearson(xs, ys):
|
| 112 |
+
pairs = [(float(x), float(y)) for x, y in zip(xs, ys)
|
| 113 |
+
if isinstance(x, (int, float)) and isinstance(y, (int, float))
|
| 114 |
+
and not isinstance(x, bool) and not isinstance(y, bool)
|
| 115 |
+
and math.isfinite(x) and math.isfinite(y)]
|
| 116 |
+
if len(pairs) < 2:
|
| 117 |
+
return None
|
| 118 |
+
x, y = zip(*pairs); mx, my = statistics.mean(x), statistics.mean(y)
|
| 119 |
+
dx, dy = [v - mx for v in x], [v - my for v in y]
|
| 120 |
+
denom = math.sqrt(sum(v*v for v in dx) * sum(v*v for v in dy))
|
| 121 |
+
return sum(a*b for a, b in zip(dx, dy)) / denom if denom else None
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def spatial_code_bytes(record, cache):
|
| 125 |
+
path = record.get("spatial_code_path")
|
| 126 |
+
if not path:
|
| 127 |
+
return None
|
| 128 |
+
if path not in cache:
|
| 129 |
+
try:
|
| 130 |
+
cache[path] = Path(path).stat().st_size
|
| 131 |
+
except OSError:
|
| 132 |
+
cache[path] = None
|
| 133 |
+
return cache[path]
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def breakdown(records, field):
|
| 137 |
+
groups = defaultdict(list)
|
| 138 |
+
for record in records:
|
| 139 |
+
groups[str(record.get(field) or "<missing>")].append(record)
|
| 140 |
+
return {
|
| 141 |
+
name: {
|
| 142 |
+
"count": len(group),
|
| 143 |
+
"mean_score": numeric_summary(_numbers(group, lambda r: r.get("score")))["mean"]
|
| 144 |
+
if _numbers(group, lambda r: r.get("score")) else None,
|
| 145 |
+
"scenes": len({r.get("scene") for r in group}),
|
| 146 |
+
}
|
| 147 |
+
for name, group in sorted(groups.items())
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def summarize_cell(records, code_cache):
|
| 152 |
+
scores = _numbers(records, lambda r: r.get("score"))
|
| 153 |
+
numeric = {field: numeric_summary(_numbers(records, lambda r, f=field: r.get(f)))
|
| 154 |
+
for field in NUMERIC_FIELDS}
|
| 155 |
+
text = {field + "_chars": numeric_summary(_numbers(
|
| 156 |
+
records, lambda r, f=field: len(r[f]) if isinstance(r.get(f), str) else None
|
| 157 |
+
)) for field in TEXT_FIELDS}
|
| 158 |
+
code_sizes = _numbers(records, lambda r: spatial_code_bytes(r, code_cache))
|
| 159 |
+
relationships = {}
|
| 160 |
+
measures = {
|
| 161 |
+
**{field: lambda r, f=field: r.get(f) for field in NUMERIC_FIELDS},
|
| 162 |
+
**{field + "_chars": lambda r, f=field: len(r[f]) if isinstance(r.get(f), str) else None
|
| 163 |
+
for field in TEXT_FIELDS},
|
| 164 |
+
"spatial_code_bytes": lambda r: spatial_code_bytes(r, code_cache),
|
| 165 |
+
}
|
| 166 |
+
for name, getter in measures.items():
|
| 167 |
+
pairs = [(r.get("score"), getter(r)) for r in records]
|
| 168 |
+
relationships["score_vs_" + name] = pearson(
|
| 169 |
+
[p[1] for p in pairs], [p[0] for p in pairs]
|
| 170 |
+
)
|
| 171 |
+
return {
|
| 172 |
+
"questions": len(records), "unique_question_ids": len({r["question_id"] for r in records}),
|
| 173 |
+
"scenes": len({r.get("scene") for r in records}),
|
| 174 |
+
"mean_score": statistics.mean(scores) if scores else None,
|
| 175 |
+
"score_distribution": numeric_summary(scores),
|
| 176 |
+
"question_types": breakdown(records, "question_type"),
|
| 177 |
+
"datasets": breakdown(records, "dataset"),
|
| 178 |
+
"numeric": numeric, "text_lengths": text,
|
| 179 |
+
"rates": {
|
| 180 |
+
"hit_token_limit": statistics.mean(bool(r.get("hit_token_limit")) for r in records) if records else None,
|
| 181 |
+
"reasoning_hit_limit": statistics.mean(bool(r.get("reasoning_hit_limit")) for r in records) if records else None,
|
| 182 |
+
"forced": statistics.mean(bool(r.get("forced")) for r in records) if records else None,
|
| 183 |
+
"scored": len(scores) / len(records) if records else None,
|
| 184 |
+
},
|
| 185 |
+
"spatial_codes": {
|
| 186 |
+
"records_with_path": sum(bool(r.get("spatial_code_path")) for r in records),
|
| 187 |
+
"unique_paths": len({r.get("spatial_code_path") for r in records if r.get("spatial_code_path")}),
|
| 188 |
+
"readable_file_bytes": numeric_summary(code_sizes),
|
| 189 |
+
},
|
| 190 |
+
"relationships": relationships,
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def paired_breakdown(x, y, common, field):
|
| 195 |
+
groups = defaultdict(list)
|
| 196 |
+
for qid in common:
|
| 197 |
+
name = str(x[qid].get(field) or y[qid].get(field) or "<missing>")
|
| 198 |
+
groups[name].append(y[qid].get("score") - x[qid].get("score"))
|
| 199 |
+
return {name: {"count": len(vals), "mean_delta": statistics.mean(vals)}
|
| 200 |
+
for name, vals in sorted(groups.items()) if vals}
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def _scene_bootstrap(x, y, common, iterations=1000, seed=0):
|
| 204 |
+
by_scene=defaultdict(list)
|
| 205 |
+
for qid in common:
|
| 206 |
+
by_scene[str(x[qid].get("scene") or y[qid].get("scene") or "<missing>")].append(
|
| 207 |
+
y[qid]["score"]-x[qid]["score"]
|
| 208 |
+
)
|
| 209 |
+
if not by_scene:
|
| 210 |
+
return {"scenes":0,"iterations":iterations,"ci_low":None,"ci_high":None,"p_value":None}
|
| 211 |
+
scenes=sorted(by_scene); rng=random.Random(seed); draws=[]
|
| 212 |
+
for _ in range(iterations):
|
| 213 |
+
values=[]
|
| 214 |
+
for _ in scenes: values.extend(by_scene[rng.choice(scenes)])
|
| 215 |
+
draws.append(statistics.mean(values))
|
| 216 |
+
draws.sort(); low=int(.025*iterations); high=min(iterations-1,int(.975*iterations))
|
| 217 |
+
below=sum(v<=0 for v in draws)/iterations; above=sum(v>=0 for v in draws)/iterations
|
| 218 |
+
return {"scenes":len(scenes),"iterations":iterations,"seed":seed,"confidence":.95,
|
| 219 |
+
"ci_low":draws[low],"ci_high":draws[high],
|
| 220 |
+
"p_value":max(1/iterations,min(1.0,2*min(below,above)))}
|
| 221 |
+
|
| 222 |
+
def paired_report(x_records, y_records):
|
| 223 |
+
x = {r["question_id"]: r for r in x_records if isinstance(r.get("score"), (int, float))}
|
| 224 |
+
y = {r["question_id"]: r for r in y_records if isinstance(r.get("score"), (int, float))}
|
| 225 |
+
common = sorted(set(x) & set(y))
|
| 226 |
+
deltas = [y[q]["score"] - x[q]["score"] for q in common]
|
| 227 |
+
solved_x={q for q in common if x[q]["score"]>=1.0}; solved_y={q for q in common if y[q]["score"]>=1.0}
|
| 228 |
+
union=solved_x|solved_y
|
| 229 |
+
telemetry = {}
|
| 230 |
+
for field in NUMERIC_FIELDS:
|
| 231 |
+
vals = [y[q].get(field) - x[q].get(field) for q in common
|
| 232 |
+
if isinstance(x[q].get(field), (int, float)) and isinstance(y[q].get(field), (int, float))]
|
| 233 |
+
telemetry[field + "_delta"] = numeric_summary(vals)
|
| 234 |
+
return {
|
| 235 |
+
"common_questions": len(common), "x_full_questions": len(x), "y_full_questions": len(y),
|
| 236 |
+
"mean_score_delta_y_minus_x": statistics.mean(deltas) if deltas else None,
|
| 237 |
+
"score_delta_distribution": numeric_summary(deltas),
|
| 238 |
+
"wins_y": sum(d > 0 for d in deltas), "ties": sum(d == 0 for d in deltas),
|
| 239 |
+
"wins_x": sum(d < 0 for d in deltas),
|
| 240 |
+
"scene_clustered_bootstrap": _scene_bootstrap(x,y,common),
|
| 241 |
+
"solved_overlap": {"x":len(solved_x),"y":len(solved_y),"both":len(solved_x&solved_y),
|
| 242 |
+
"only_x":len(solved_x-solved_y),"only_y":len(solved_y-solved_x),
|
| 243 |
+
"jaccard":len(solved_x&solved_y)/len(union) if union else None},
|
| 244 |
+
"by_question_type": paired_breakdown(x, y, common, "question_type"),
|
| 245 |
+
"by_dataset": paired_breakdown(x, y, common, "dataset"),
|
| 246 |
+
"telemetry_deltas": telemetry,
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def analyze(directories=None, protocols=()):
|
| 251 |
+
directories = directories or DEFAULT_DIRS
|
| 252 |
+
cells = defaultdict(list)
|
| 253 |
+
for harness, directory in directories.items():
|
| 254 |
+
for record in iter_records(directory):
|
| 255 |
+
protocol = record.get("protocol") or record["condition"].split(":", 1)[0]
|
| 256 |
+
if protocol_selected(protocol, protocols):
|
| 257 |
+
cells[cell_identity(harness, record)].append(record)
|
| 258 |
+
code_cache = {}
|
| 259 |
+
report = {"cells": {}, "comparison_groups": {}}
|
| 260 |
+
for identity, records in cells.items():
|
| 261 |
+
report["cells"][cell_label(identity)] = {
|
| 262 |
+
"identity": identity_dict(identity), "summary": summarize_cell(records, code_cache)
|
| 263 |
+
}
|
| 264 |
+
grouped = defaultdict(list)
|
| 265 |
+
for identity in cells:
|
| 266 |
+
grouped[comparison_key(identity)].append(identity)
|
| 267 |
+
for key, identities in grouped.items():
|
| 268 |
+
name = "/".join("?" if v is None else str(v) for v in key)
|
| 269 |
+
pairs = {}
|
| 270 |
+
for first, second in combinations(sorted(identities, key=cell_label), 2):
|
| 271 |
+
pairs[cell_label(first) + " -> " + cell_label(second)] = paired_report(cells[first], cells[second])
|
| 272 |
+
id_sets = [{r["question_id"] for r in cells[i]} for i in identities]
|
| 273 |
+
report["comparison_groups"][name] = {
|
| 274 |
+
"cells": [cell_label(i) for i in identities],
|
| 275 |
+
"all_cell_common_questions": len(set.intersection(*id_sets)) if id_sets else 0,
|
| 276 |
+
"pairwise": pairs,
|
| 277 |
+
}
|
| 278 |
+
return report
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def main():
|
| 282 |
+
parser = argparse.ArgumentParser()
|
| 283 |
+
for harness in "abc":
|
| 284 |
+
parser.add_argument(f"--{harness}-results-dir", default=None)
|
| 285 |
+
parser.add_argument("--protocol", action="append", default=[],
|
| 286 |
+
help="repeatable; family 'truncated' includes truncated/<budget>")
|
| 287 |
+
parser.add_argument(
|
| 288 |
+
"--output-dir", default=str(ROOT / "reports"),
|
| 289 |
+
help="report directory (default: workspace/reports)",
|
| 290 |
+
)
|
| 291 |
+
parser.add_argument(
|
| 292 |
+
"--json-out", default=None,
|
| 293 |
+
help="override the JSON report path (default: <output-dir>/comprehensive.json)",
|
| 294 |
+
)
|
| 295 |
+
args = parser.parse_args()
|
| 296 |
+
dirs = {h.upper(): Path(getattr(args, f"{h}_results_dir") or DEFAULT_DIRS[h.upper()]) for h in "abc"}
|
| 297 |
+
report = analyze(dirs, args.protocol)
|
| 298 |
+
text = json.dumps(report, indent=1)
|
| 299 |
+
output_path = Path(args.json_out) if args.json_out else Path(args.output_dir) / "comprehensive.json"
|
| 300 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 301 |
+
output_path.write_text(text + "\n", encoding="utf-8")
|
| 302 |
+
print(f"wrote {output_path}")
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
# --- Modular profile-driven interface (v2) ---
|
| 307 |
+
from datetime import datetime, timezone
|
| 308 |
+
|
| 309 |
+
# Built-in, versioned harness profiles.
|
| 310 |
+
PROFILE_VERSION = 1
|
| 311 |
+
BUILTINS = {
|
| 312 |
+
"A":{"letter":"A","kind":"vlm","input_source":"frames","axes":["model","protocol","selection","frames"],"capabilities":["tokens","latency","reasoning","frames"]},
|
| 313 |
+
"B":{"letter":"B","kind":"vlm","input_source":"perceived","axes":["model","protocol","format","depth","tracking","selection","frames"],"capabilities":["tokens","latency","reasoning","spatial_code"]},
|
| 314 |
+
"C":{"letter":"C","kind":"vlm","input_source":"frames_perceived","axes":["model","protocol","format","depth","tracking","selection","frames"],"capabilities":["tokens","latency","reasoning","frames","spatial_code"]},
|
| 315 |
+
"D":{"letter":"D","kind":"vlm","input_source":"ground_truth","axes":["model","protocol","format"],"capabilities":["tokens","latency","reasoning","spatial_code"]},
|
| 316 |
+
"F":{"letter":"F","kind":"solver","input_source":"dynamic","axes":["source","depth","tracking","selection","frames","format","spatial_code_model"],"capabilities":["spatial_code","solver"]},
|
| 317 |
+
}
|
| 318 |
+
def validate_profile(profile):
|
| 319 |
+
p=dict(profile); letter=str(p.get("letter","")).upper()
|
| 320 |
+
if len(letter)!=1 or not letter.isalpha(): raise ValueError("profile letter must be one alphabetic character")
|
| 321 |
+
if letter=="E": raise ValueError("E is explicitly excluded")
|
| 322 |
+
p["letter"]=letter; p.setdefault("kind","generic"); p.setdefault("input_source","unknown"); p.setdefault("axes",["model","protocol"]); p.setdefault("capabilities",[]); p["profile_version"]=PROFILE_VERSION
|
| 323 |
+
return p
|
| 324 |
+
def load_profile(letter,path=None):
|
| 325 |
+
letter=letter.upper()
|
| 326 |
+
if letter=="E": raise ValueError("E is explicitly excluded")
|
| 327 |
+
if path:
|
| 328 |
+
p=json.loads(Path(path).read_text()); p.setdefault("letter",letter)
|
| 329 |
+
if p["letter"].upper()!=letter: raise ValueError(f"profile letter mismatch for {letter}")
|
| 330 |
+
return validate_profile(p)
|
| 331 |
+
return validate_profile(BUILTINS.get(letter,{"letter":letter,"kind":"generic","input_source":"unknown","axes":["model","protocol","format","depth","tracking","selection","frames"]}))
|
| 332 |
+
|
| 333 |
+
ANALYSIS_VERSION = 2
|
| 334 |
+
|
| 335 |
+
def discover_records(letter, directory, profile, protocols=(), spatial_codes_dir=None):
|
| 336 |
+
root=Path(directory); records=[]; warnings=[]
|
| 337 |
+
if not root.is_dir(): return records,[{"code":"missing_directory","path":str(root)}]
|
| 338 |
+
for path in sorted(root.rglob("*.json")):
|
| 339 |
+
if path.name.startswith("_"): continue
|
| 340 |
+
try: record=json.loads(path.read_text(encoding="utf-8"))
|
| 341 |
+
except (OSError,json.JSONDecodeError) as exc:
|
| 342 |
+
warnings.append({"code":"unreadable_json","path":str(path),"detail":str(exc)}); continue
|
| 343 |
+
if not isinstance(record,dict) or record.get("question_id") is None or record.get("score") is None:
|
| 344 |
+
warnings.append({"code":"not_question_record","path":str(path)}); continue
|
| 345 |
+
record=dict(record); record["_result_path"]=str(path); record["_relative_path"]=path.relative_to(root).parts
|
| 346 |
+
record=_normalize_record(letter,record,profile)
|
| 347 |
+
code_path=record.get("spatial_code_path")
|
| 348 |
+
if code_path and not Path(code_path).is_file() and spatial_codes_dir:
|
| 349 |
+
marker="spatial codes/"
|
| 350 |
+
suffix=str(code_path).split(marker,1)[-1] if marker in str(code_path) else None
|
| 351 |
+
candidate=Path(spatial_codes_dir)/suffix if suffix else None
|
| 352 |
+
if candidate and candidate.is_file(): record["spatial_code_path"]=str(candidate)
|
| 353 |
+
else: warnings.append({"code":"unresolved_spatial_code_path","path":str(path),"recorded_path":str(code_path)})
|
| 354 |
+
if letter!="F" and not protocol_selected(record.get("protocol"),protocols): continue
|
| 355 |
+
records.append(record)
|
| 356 |
+
return records,warnings
|
| 357 |
+
|
| 358 |
+
def _normalize_record(letter,r,profile):
|
| 359 |
+
r["format"]=r.get("spatial_code_format") or r.get("format")
|
| 360 |
+
r["selection"]=r.get("frame_selection") or r.get("input_selection") or r.get("input")
|
| 361 |
+
r["frames"]=r.get("frame_count") or r.get("number_of_frames")
|
| 362 |
+
if not r.get("protocol") and r.get("condition") and letter!="F": r["protocol"]=r["condition"].split(":",1)[0]
|
| 363 |
+
if letter=="F":
|
| 364 |
+
parts=list(r.get("_relative_path",()))
|
| 365 |
+
top=parts[0].lower() if parts else ""
|
| 366 |
+
if top in ("ground truth","ground_truth"):
|
| 367 |
+
r.update(source="ground_truth",depth=None,tracking=None,selection=None,frames=None)
|
| 368 |
+
r["format"]=r.get("format") or (parts[1] if len(parts)>1 else None)
|
| 369 |
+
else:
|
| 370 |
+
r["source"]="perceived"
|
| 371 |
+
offset=1
|
| 372 |
+
if top=="perceived": r["depth"]=r.get("depth") or (parts[1] if len(parts)>1 else None); offset=2
|
| 373 |
+
elif top in ("metric","relative"): r["depth"]=r.get("depth") or top
|
| 374 |
+
r["tracking"]=r.get("tracking") or (parts[offset] if len(parts)>offset else None)
|
| 375 |
+
r["selection"]=r.get("selection") or (parts[offset+1] if len(parts)>offset+1 else None)
|
| 376 |
+
r["frames"]=r.get("frames") or (parts[offset+2] if len(parts)>offset+2 else None)
|
| 377 |
+
candidate=parts[offset+3] if len(parts)>offset+3 else None
|
| 378 |
+
if candidate and not candidate.startswith("scene") and len(candidate)!=10: r["format"]=r.get("format") or candidate
|
| 379 |
+
r["spatial_code_model"]=r.get("spatial_code_model")
|
| 380 |
+
r["protocol"]=None
|
| 381 |
+
return r
|
| 382 |
+
|
| 383 |
+
def modular_identity(letter,record,profile):
|
| 384 |
+
values={"harness":letter}
|
| 385 |
+
for axis in profile["axes"]: values[axis]=str(record.get(axis)) if record.get(axis) is not None else None
|
| 386 |
+
return tuple(sorted(values.items()))
|
| 387 |
+
|
| 388 |
+
def modular_label(identity):
|
| 389 |
+
d=dict(identity); return "/".join([d.pop("harness")]+[f"{k}={v or '?'}" for k,v in sorted(d.items())])
|
| 390 |
+
|
| 391 |
+
def _controlled(first,second,profile):
|
| 392 |
+
a,b=dict(first),dict(second); diffs=[axis for axis in profile["axes"] if a.get(axis)!=b.get(axis)]
|
| 393 |
+
return len(diffs)==1,diffs
|
| 394 |
+
|
| 395 |
+
def _compatible(a,b,profiles):
|
| 396 |
+
x,y=dict(a),dict(b); lx,ly=x["harness"],y["harness"]
|
| 397 |
+
warnings=[]
|
| 398 |
+
if lx==ly: return False,[],["same_harness"]
|
| 399 |
+
# F source semantics.
|
| 400 |
+
f=x if lx=="F" else y if ly=="F" else None; other=y if lx=="F" else x
|
| 401 |
+
if f:
|
| 402 |
+
expected="ground_truth" if other["harness"]=="D" else "perceived" if other["harness"] in ("B","C") else None
|
| 403 |
+
if expected and f.get("source")!=expected: return False,[],["incompatible_F_source"]
|
| 404 |
+
shared=[]
|
| 405 |
+
for axis in ("model","format","depth","tracking","selection","frames"):
|
| 406 |
+
av,bv=x.get(axis),y.get(axis)
|
| 407 |
+
if axis=="model" and f: continue
|
| 408 |
+
if av is not None and bv is not None:
|
| 409 |
+
if av!=bv: return False,[],[f"conflicting_{axis}"]
|
| 410 |
+
shared.append(axis)
|
| 411 |
+
else: warnings.append(f"unmatched_{axis}")
|
| 412 |
+
if not f and x.get("protocol") is not None and y.get("protocol") is not None:
|
| 413 |
+
if x["protocol"]!=y["protocol"]: return False,[],["conflicting_protocol"]
|
| 414 |
+
shared.append("protocol")
|
| 415 |
+
return True,shared,warnings
|
| 416 |
+
|
| 417 |
+
def analyze_modular(cells, profiles, protocols=(), requested_pairs=(), spatial_codes_dir=None):
|
| 418 |
+
all_cells=defaultdict(list); warnings={}; sources={}
|
| 419 |
+
for letter,directory in cells.items():
|
| 420 |
+
recs,warns=discover_records(letter,directory,profiles[letter],protocols,spatial_codes_dir); warnings[letter]=warns; sources[letter]=str(directory)
|
| 421 |
+
for r in recs: all_cells[modular_identity(letter,r,profiles[letter])].append(r)
|
| 422 |
+
cache={}; per={letter:{"manifest":{"analysis_version":ANALYSIS_VERSION,"profile_version":PROFILE_VERSION,"generated_at":datetime.now(timezone.utc).isoformat(),"letter":letter,"profile":profiles[letter],"source":sources[letter],"protocols":list(protocols)},"cells":{},"within_harness_comparisons":{},"integrity_warnings":warnings[letter]} for letter in cells}
|
| 423 |
+
for ident,recs in all_cells.items(): per[dict(ident)["harness"]]["cells"][modular_label(ident)]={"identity":dict(ident),"summary":summarize_cell(recs,cache)}
|
| 424 |
+
for letter in cells:
|
| 425 |
+
ids=[i for i in all_cells if dict(i)["harness"]==letter]
|
| 426 |
+
for a,b in combinations(ids,2):
|
| 427 |
+
ok,diffs=_controlled(a,b,profiles[letter])
|
| 428 |
+
if ok: per[letter]["within_harness_comparisons"][modular_label(a)+" -> "+modular_label(b)]={"varied_axis":diffs[0],**paired_report(all_cells[a],all_cells[b])}
|
| 429 |
+
allowed={tuple(sorted(p)) for p in requested_pairs}
|
| 430 |
+
cross={}
|
| 431 |
+
ids=list(all_cells)
|
| 432 |
+
for a,b in combinations(ids,2):
|
| 433 |
+
letters=tuple(sorted((dict(a)["harness"],dict(b)["harness"])))
|
| 434 |
+
if letters[0]==letters[1] or (allowed and letters not in allowed): continue
|
| 435 |
+
ok,shared,warns=_compatible(a,b,profiles)
|
| 436 |
+
if ok: cross[modular_label(a)+" -> "+modular_label(b)]={"letters":letters,"shared_axes":shared,"alignment_warnings":warns,**paired_report(all_cells[a],all_cells[b])}
|
| 437 |
+
manifest={"analysis_version":ANALYSIS_VERSION,"profile_version":PROFILE_VERSION,"generated_at":datetime.now(timezone.utc).isoformat(),"letters":sorted(cells),"sources":sources,"protocols":list(protocols),"requested_pairs":[":".join(p) for p in requested_pairs]}
|
| 438 |
+
return per,{"manifest":manifest,"cross_harness_comparisons":cross,"harness_summaries":{l:{"cell_count":len(per[l]["cells"]),"warning_count":len(per[l]["integrity_warnings"])} for l in per}}
|
| 439 |
+
|
| 440 |
+
def parse_assignment(value,option):
|
| 441 |
+
if "=" not in value: raise argparse.ArgumentTypeError(f"{option} must be LETTER=PATH")
|
| 442 |
+
letter,path=value.split("=",1); letter=letter.upper()
|
| 443 |
+
if len(letter)!=1 or not letter.isalpha() or letter=="E": raise argparse.ArgumentTypeError("letter must be one alphabetic character other than E")
|
| 444 |
+
return letter,path
|
| 445 |
+
|
| 446 |
+
def export_reports(per,combined,output_dir):
|
| 447 |
+
out=Path(output_dir); out.mkdir(parents=True,exist_ok=True); paths=[]
|
| 448 |
+
for letter,report in sorted(per.items()):
|
| 449 |
+
path=out/f"{letter}_report.json"; path.write_text(json.dumps(report,indent=1)+"\n"); paths.append(path)
|
| 450 |
+
if len(per) > 1:
|
| 451 |
+
name="".join(sorted(per))+"_report.json"
|
| 452 |
+
path=out/name
|
| 453 |
+
path.write_text(json.dumps(combined,indent=1)+"\n")
|
| 454 |
+
paths.append(path)
|
| 455 |
+
return paths
|
| 456 |
+
|
| 457 |
+
def main():
|
| 458 |
+
parser=argparse.ArgumentParser()
|
| 459 |
+
parser.add_argument("--cell",action="append",default=[],help="repeatable LETTER=PATH; E is excluded")
|
| 460 |
+
parser.add_argument("--profile",action="append",default=[],help="optional LETTER=profile.json")
|
| 461 |
+
parser.add_argument("--compare",action="append",default=[],help="optional pair restriction, e.g. A:B")
|
| 462 |
+
parser.add_argument("--protocol",action="append",default=[],help="repeatable; truncated includes truncated/<budget>")
|
| 463 |
+
parser.add_argument("--output-dir",default=str(ROOT/"reports"))
|
| 464 |
+
parser.add_argument("--spatial-codes-dir",default=None,help="optional local root used to rebase stale recorded code paths")
|
| 465 |
+
for h in "abc": parser.add_argument(f"--{h}-results-dir",default=None,help=argparse.SUPPRESS)
|
| 466 |
+
args=parser.parse_args(); cells=dict(parse_assignment(v,"--cell") for v in args.cell)
|
| 467 |
+
for h in "abc":
|
| 468 |
+
value=getattr(args,f"{h}_results_dir")
|
| 469 |
+
if value: cells[h.upper()]=value
|
| 470 |
+
if not cells: parser.error("provide at least one --cell LETTER=PATH")
|
| 471 |
+
profile_paths=dict(parse_assignment(v,"--profile") for v in args.profile)
|
| 472 |
+
profiles={letter:load_profile(letter,profile_paths.get(letter)) for letter in cells}
|
| 473 |
+
pairs=[]
|
| 474 |
+
for value in args.compare:
|
| 475 |
+
bits=[x.upper() for x in value.split(":")]
|
| 476 |
+
if len(bits)!=2 or any(x not in cells for x in bits): parser.error(f"invalid --compare {value}")
|
| 477 |
+
pairs.append(tuple(bits))
|
| 478 |
+
per,combined=analyze_modular(cells,profiles,args.protocol,pairs,args.spatial_codes_dir)
|
| 479 |
+
for path in export_reports(per,combined,args.output_dir): print(f"wrote {path}")
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
# Consolidated analysis helpers formerly split across stats/solvability/sufficiency/audits.
|
| 483 |
+
def _official_scores(records):
|
| 484 |
+
records=list(records)
|
| 485 |
+
try:
|
| 486 |
+
import importlib.util, os
|
| 487 |
+
path=os.environ.get("HARNESS_OFFICIAL_EVAL","/root/data/thinking-in-space/lmms_eval/tasks/vsibench/utils.py")
|
| 488 |
+
spec=importlib.util.spec_from_file_location("analysis_vsi_official_eval",path)
|
| 489 |
+
module=importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
|
| 490 |
+
docs=[{"question_type":r["question_type"],"ground_truth":r.get("answer_expected"),r["metric"]:r["score"]} for r in records]
|
| 491 |
+
return module.vsibench_aggregate_results(docs)
|
| 492 |
+
except (OSError,ImportError,AttributeError,TypeError):
|
| 493 |
+
scores=[r.get("score") for r in records if isinstance(r.get("score"),(int,float))]
|
| 494 |
+
return {"overall":statistics.mean(scores)*100 if scores else None,"scoring_mode":"stored_per_question_mean_fallback"}
|
| 495 |
+
|
| 496 |
+
def holm_bonferroni(p_values):
|
| 497 |
+
ordered=sorted(p_values.items(),key=lambda item:item[1]); total=len(ordered); out={}; running=0.0
|
| 498 |
+
for rank,(name,p) in enumerate(ordered):
|
| 499 |
+
running=max(running,min(1.0,(total-rank)*p)); out[name]=running
|
| 500 |
+
return out
|
| 501 |
+
|
| 502 |
+
def solved_set_overlap(cells,threshold=1.0):
|
| 503 |
+
maps={name:{r["question_id"]:r.get("score") for r in records} for name,records in cells.items()}
|
| 504 |
+
common=set.intersection(*(set(m) for m in maps.values())) if maps else set(); solved={n:{q for q in common if v[q] is not None and v[q]>=threshold} for n,v in maps.items()}
|
| 505 |
+
pairs={}
|
| 506 |
+
for a,b in combinations(sorted(solved),2):
|
| 507 |
+
union=solved[a]|solved[b]; pairs[f"{a}|{b}"]={"jaccard":len(solved[a]&solved[b])/len(union) if union else None,"both":len(solved[a]&solved[b]),f"only_{a}":len(solved[a]-solved[b]),f"only_{b}":len(solved[b]-solved[a])}
|
| 508 |
+
return {"questions":len(common),"solved":{n:len(v) for n,v in solved.items()},"pairs":pairs}
|
| 509 |
+
|
| 510 |
+
def sufficiency_decomposition(vlm_records,solver_records,threshold=1.0,exclude=()):
|
| 511 |
+
cert={r["question_id"]:r.get("score") is not None and r["score"]>=threshold for r in solver_records}; buckets={"certified":[],"uncertified":[]}
|
| 512 |
+
for r in vlm_records:
|
| 513 |
+
if r.get("question_type") in set(exclude) or r.get("question_id") not in cert: continue
|
| 514 |
+
buckets["certified" if cert[r["question_id"]] else "uncertified"].append(r.get("score"))
|
| 515 |
+
def summary(vals):
|
| 516 |
+
valid=[v for v in vals if isinstance(v,(int,float))]; correct=sum(v>=threshold for v in valid)
|
| 517 |
+
return {"count":len(vals),"mean_score":statistics.mean(valid) if valid else None,"vlm_correct":correct,"vlm_wrong":len(vals)-correct}
|
| 518 |
+
return {name:summary(vals) for name,vals in buckets.items()}
|
| 519 |
+
|
| 520 |
+
def solver_depth_table(records):
|
| 521 |
+
try: from symbolic import adapters,solver
|
| 522 |
+
except ImportError: return {"status":"unavailable","reason":"symbolic solver imports unavailable"}
|
| 523 |
+
cache={}; buckets=defaultdict(list)
|
| 524 |
+
for r in records:
|
| 525 |
+
path=r.get("spatial_code_path")
|
| 526 |
+
if not path: continue
|
| 527 |
+
try:
|
| 528 |
+
if path not in cache: cache[path]=adapters.adapt_spatial_code(json.loads(Path(path).read_text()))
|
| 529 |
+
solver.answer(r["question_type"],r["question"],r.get("options"),cache[path]); depth=solver.LAST_ANSWER_OPS.get("total")
|
| 530 |
+
except (OSError,KeyError,ValueError): continue
|
| 531 |
+
if depth is not None and isinstance(r.get("score"),(int,float)): buckets["0-2" if depth<=2 else "3-8" if depth<=8 else "9-20" if depth<=20 else "21-inf"].append((depth,r["score"]))
|
| 532 |
+
return {k:{"count":len(v),"mean_depth":statistics.mean(x for x,_ in v),"mean_score":statistics.mean(y for _,y in v)} for k,v in buckets.items()}
|
| 533 |
+
|
| 534 |
+
_NUMBER_RE=__import__('re').compile(r"[-+]?\d+(?:\.\d+)?")
|
| 535 |
+
def deterministic_cot_audit(records,tolerance=.01):
|
| 536 |
+
def nums(value): return [float(x) for x in _NUMBER_RE.findall(str(value or ''))]
|
| 537 |
+
audits=[]; cache={}
|
| 538 |
+
for r in records:
|
| 539 |
+
reasoning=r.get("reasoning_text"); path=r.get("spatial_code_path")
|
| 540 |
+
if not reasoning or not path: continue
|
| 541 |
+
try:
|
| 542 |
+
if path not in cache: cache[path]=nums(Path(path).read_text())
|
| 543 |
+
except OSError: continue
|
| 544 |
+
sources=cache[path]+nums(r.get("question"))+sum((nums(x) for x in r.get("options") or []),[]); cited=nums(reasoning)
|
| 545 |
+
fabricated=[v for v in cited if not (abs(v)<=12 and v.is_integer()) and not any(abs(v-x)<=tolerance*max(1,abs(x)) for x in sources)]
|
| 546 |
+
audits.append({"question_id":r["question_id"],"score":r.get("score"),"cited":len(cited),"fabricated":len(fabricated)})
|
| 547 |
+
wrong=[a for a in audits if a["score"] is not None and a["score"]<1]; bad=[a for a in wrong if a["fabricated"]]
|
| 548 |
+
return {"audited":len(audits),"wrong":len(wrong),"wrong_with_fabrication":len(bad),"fabrication_share_of_wrong":len(bad)/len(wrong) if wrong else None}
|
| 549 |
+
|
| 550 |
+
def generate_letter(letter,results_dir,protocols=(),output_dir=None,spatial_codes_dir=None,profile_path=None):
|
| 551 |
+
letter=letter.upper(); profile=load_profile(letter,profile_path)
|
| 552 |
+
per,combined=analyze_modular({letter:Path(results_dir)},{letter:profile},protocols,(),spatial_codes_dir)
|
| 553 |
+
paths=export_reports(per,combined,output_dir or ROOT/'reports')
|
| 554 |
+
return {"report":per[letter],"path":paths[0]}
|
| 555 |
+
|
| 556 |
+
def generate(cells,protocols=(),comparisons=(),output_dir=None,profile_paths=None,spatial_codes_dir=None):
|
| 557 |
+
normalized={str(k).upper():Path(v) for k,v in cells.items()}
|
| 558 |
+
if 'E' in normalized: raise ValueError('E is explicitly excluded')
|
| 559 |
+
profile_paths={str(k).upper():v for k,v in (profile_paths or {}).items()}; profiles={l:load_profile(l,profile_paths.get(l)) for l in normalized}; pairs=[]
|
| 560 |
+
for pair in comparisons:
|
| 561 |
+
pair=tuple(x.upper() for x in (pair.split(':') if isinstance(pair,str) else pair))
|
| 562 |
+
if len(pair)!=2 or any(x not in normalized for x in pair): raise ValueError(f'invalid comparison {pair}')
|
| 563 |
+
pairs.append(pair)
|
| 564 |
+
per,combined=analyze_modular(normalized,profiles,protocols,pairs,spatial_codes_dir); paths=export_reports(per,combined,output_dir or ROOT/'reports')
|
| 565 |
+
return {"letter_reports":per,"combined_report":combined,"paths":paths}
|
| 566 |
+
|
| 567 |
+
def main():
|
| 568 |
+
parser=argparse.ArgumentParser(description='Generate arbitrary mixed letter reports; E is excluded.')
|
| 569 |
+
parser.add_argument('--cell',action='append',required=True); parser.add_argument('--profile',action='append',default=[]); parser.add_argument('--compare',action='append',default=[]); parser.add_argument('--protocol',action='append',default=[]); parser.add_argument('--output-dir',default=str(ROOT/'reports')); parser.add_argument('--spatial-codes-dir',default=None)
|
| 570 |
+
args=parser.parse_args(); cells=dict(parse_assignment(v,'--cell') for v in args.cell); profiles=dict(parse_assignment(v,'--profile') for v in args.profile)
|
| 571 |
+
try: result=generate(cells,args.protocol,args.compare,args.output_dir,profiles,args.spatial_codes_dir)
|
| 572 |
+
except ValueError as exc: parser.error(str(exc))
|
| 573 |
+
for path in result['paths']: print(f'wrote {path}')
|
| 574 |
+
if __name__=='__main__': main()
|
data/.vsi-environment.sh
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Generated by setup.sh.
|
| 2 |
+
# Source this before running inference or the encoder.
|
| 3 |
+
export VSI_WORKSPACE_ROOT=/workspace
|
| 4 |
+
export VSI_DATA_ROOT=/root/data
|
| 5 |
+
export VSI_ROOT=/root/data/VSI-Bench
|
| 6 |
+
export VSI_CACHE_ROOT=/root/data/caches
|
| 7 |
+
export VSI_CODES=/workspace/data/spatial\ codes
|
| 8 |
+
export VSI_MODELS_ROOT=/root/models
|
| 9 |
+
export VSI_THINKING_IN_SPACE_ROOT=/root/data/thinking-in-space
|
| 10 |
+
export VSI_SELECTED_FRAMES_CACHE=/root/data/caches/selected\ frames
|
| 11 |
+
export VSI_DA3_ROOT=/root/models/depth-anything-3
|
| 12 |
+
export VSI_DA3_METRIC_CHECKPOINT=/root/models/depth-anything-3/checkpoints/DA3NESTED-GIANT-LARGE-1.1
|
| 13 |
+
export VSI_SAM3_ROOT=/root/models/sam3
|
| 14 |
+
export VSI_SEGVGGT_ROOT=/root/models/SegVGGT
|
| 15 |
+
export VIRTUAL_ENV=/root/.venv
|
| 16 |
+
export PATH=/root/.venv/bin:$PATH
|
| 17 |
+
export PYTHONPATH=/workspace${PYTHONPATH:+:$PYTHONPATH}
|
data/caches/depth-anything-3.tar.zst
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7e7cb06cb9cc25f35e30cf03dc1a2d975fd1cdb657d83cee375377acefe182ce
|
| 3 |
+
size 58480215103
|
data/caches/depth-anything-3/depth-anything-3-metric-frames.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d369f754a9349d54cbeb19c20d665f18651902d337fec8e844a5decbc2d4085b
|
| 3 |
+
size 54026425128
|
data/caches/depth-anything-3/depth-anything-3-metric-video.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8bdfc1ef085232e1644c3535b6e5f8117abe53648f97b12db9b6cafa439ada11
|
| 3 |
+
size 60332885871
|
data/caches/depth-anything-3/depth-anything-3-relative-frames.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7399a487380320f863c9f331588aa37845f1b0d00f08674dedf930d0a4919baa
|
| 3 |
+
size 4828585754
|
data/caches/overlay-frames.tar.zst
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5b25b608bc8b7c85e5d10ade1514932e7ef6d9ef9b16a4cd7522cd55b91af1d9
|
| 3 |
+
size 560766155
|
data/caches/sam3/.gitkeep
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
data/caches/sam3/sam3-no-tracking-video.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fc17d884ef1ef1e456a84444d9d0e9cccb8c94d99afc338ecde9b9f653b4be30
|
| 3 |
+
size 326509595
|
data/caches/sam3/sam3-tracking-frames.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a6138e6115d1723365f7bbd44295b966d1b006ef7b78684a59634d238730c7bb
|
| 3 |
+
size 27961117522
|
data/caches/segvggt.tar.zst
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5f1eb474058433186ba10f5b8c756ca21635a7cd4eb567bd88fe404378d4d520
|
| 3 |
+
size 40228959795
|
data/caches/selected-frames.tar.zst
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8036112e912a68325ad6447d5d3aadf40d0308fb2cdbe7d005986f1268b4d371
|
| 3 |
+
size 169891
|
data/spatial-codes.tar.zst
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b3c1a6e3613c2c6525d7220c32738d18f1ecdaad52174b476382fc4e0fee8046
|
| 3 |
+
size 7774580
|
encoder/ground_truth.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Ground-truth spatial codes: the same compact/explicit schemas encoder/geometric.py
|
| 2 |
+
produces from the perception pipeline (SAM3 + Depth Anything 3), but built directly from
|
| 3 |
+
the dataset's own annotated 3D object boxes and room size instead -- perfect geometry,
|
| 4 |
+
zero perception error, for isolating "does the VLM's spatial reasoning improve when the
|
| 5 |
+
input geometry is exactly right" from "is the encoder's perception good enough."
|
| 6 |
+
|
| 7 |
+
Sourced from thinking-in-space's meta_info (the same ground truth thinking-in-space's own
|
| 8 |
+
official VSI-Bench scorer trains/evaluates against): per-scene `object_bbox` (each
|
| 9 |
+
instance's centroid/axesLengths/normalizedAxes -- a full 3D oriented box) and `room_size`
|
| 10 |
+
(the room's true floor area). Two things meta_info does NOT carry, because they are
|
| 11 |
+
properties of a specific camera walkthrough rather than of the scene's static geometry:
|
| 12 |
+
|
| 13 |
+
- Room SHAPE (only the scalar area is annotated): represented as a single axis-aligned
|
| 14 |
+
square floor polygon of exactly that area, centered at the scene's own `room_center` --
|
| 15 |
+
the honest floor-shape representation the data supports, matching real area exactly
|
| 16 |
+
under the same shoelace derivation compact/explicit already use, without inventing a
|
| 17 |
+
boundary the annotations don't contain.
|
| 18 |
+
- Per-object "first visible time" (when a class first appears on camera -- inherently a
|
| 19 |
+
property of the video, not the 3D scan): there is no such ground truth for the average
|
| 20 |
+
object, but VSI-Bench's own `obj_appearance_order` questions DO carry genuine human
|
| 21 |
+
ground truth ordering for the specific classes they ask about. Every appearance-order
|
| 22 |
+
question for a scene contributes a same-scene ordering constraint (see
|
| 23 |
+
_appearance_order_ranks); classes never covered by any such question for that scene
|
| 24 |
+
get "first visible time": null (no fabricated number) and sort after every timed class
|
| 25 |
+
in "appearance order".
|
| 26 |
+
|
| 27 |
+
Coordinate convention: thinking-in-space's meta_info coordinates are already gravity-
|
| 28 |
+
aligned per-scene (z is up; verified empirically -- `room_center` z is tightly clustered
|
| 29 |
+
near a small non-negative range across every scannet scene, unlike x/y, and ARKitScenes'
|
| 30 |
+
axis-locked object boxes carry an exact [0, 0, 1] orientation row), so -- unlike the real
|
| 31 |
+
encoder pipeline, which must estimate gravity from a noisy reconstructed point cloud --
|
| 32 |
+
ground truth's own x, y, z pass straight through as the compact schema's own (x, y,
|
| 33 |
+
height above floor) room frame; only a floor reference (z of the annotations' own lowest
|
| 34 |
+
point) needs to be established.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
from __future__ import annotations
|
| 38 |
+
|
| 39 |
+
import json
|
| 40 |
+
from functools import lru_cache
|
| 41 |
+
from pathlib import Path
|
| 42 |
+
|
| 43 |
+
import numpy as np
|
| 44 |
+
|
| 45 |
+
from encoder import config
|
| 46 |
+
from encoder.geometric import (
|
| 47 |
+
COMPACT_SPATIAL_CODE_SCHEMA,
|
| 48 |
+
_compact_room_floor_area,
|
| 49 |
+
_explicit_from_compact,
|
| 50 |
+
_rounded_list,
|
| 51 |
+
dump_spatial_code,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
META_INFO_DIR = Path(config.DATA_ROOT) / "thinking-in-space" / "data" / "meta_info"
|
| 55 |
+
META_INFO_DATASETS = ("scannet", "arkitscenes", "scannetpp")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@lru_cache(maxsize=1)
|
| 59 |
+
def load_meta_info():
|
| 60 |
+
"""Return {scene: record} merged across every dataset's meta_info file, each record
|
| 61 |
+
carrying its own "dataset" key (scannet / arkitscenes / scannetpp)."""
|
| 62 |
+
merged = {}
|
| 63 |
+
for dataset in META_INFO_DATASETS:
|
| 64 |
+
path = META_INFO_DIR / f"{dataset}_meta_info_val.json"
|
| 65 |
+
with open(path, encoding="utf-8") as stream:
|
| 66 |
+
records = json.load(stream)
|
| 67 |
+
for scene, record in records.items():
|
| 68 |
+
merged[str(scene)] = {**record, "dataset": dataset}
|
| 69 |
+
return merged
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@lru_cache(maxsize=1)
|
| 73 |
+
def _appearance_order_ranks_by_scene():
|
| 74 |
+
"""Return {scene: {class_name: rank}} decoded from every real
|
| 75 |
+
``obj_appearance_order`` question's ground_truth answer in test.jsonl -- a DAG of
|
| 76 |
+
"class X appears no later than class Y" edges per scene, topologically ranked (DFS,
|
| 77 |
+
back-edges from any inconsistent question ignored rather than raising, since a rank
|
| 78 |
+
is still useful even if two annotators' four-item orderings can't be perfectly
|
| 79 |
+
reconciled). Classes never named by any appearance-order question for that scene are
|
| 80 |
+
simply absent from the returned mapping.
|
| 81 |
+
"""
|
| 82 |
+
edges_by_scene = {}
|
| 83 |
+
with open(config.JSONL, encoding="utf-8") as stream:
|
| 84 |
+
for line in stream:
|
| 85 |
+
question = json.loads(line)
|
| 86 |
+
if question.get("question_type") != "obj_appearance_order":
|
| 87 |
+
continue
|
| 88 |
+
scene = str(question["scene_name"])
|
| 89 |
+
index = ord(question["ground_truth"]) - ord("A")
|
| 90 |
+
option = question["options"][index]
|
| 91 |
+
classes = [name.strip() for name in option.split(".", 1)[1].split(",")]
|
| 92 |
+
edges = edges_by_scene.setdefault(scene, {})
|
| 93 |
+
for earlier, later in zip(classes, classes[1:]):
|
| 94 |
+
edges.setdefault(earlier, set()).add(later)
|
| 95 |
+
|
| 96 |
+
ranks_by_scene = {}
|
| 97 |
+
for scene, edges in edges_by_scene.items():
|
| 98 |
+
nodes = set(edges) | {
|
| 99 |
+
node for successors in edges.values() for node in successors
|
| 100 |
+
}
|
| 101 |
+
order = []
|
| 102 |
+
visited, in_progress = set(), set()
|
| 103 |
+
|
| 104 |
+
def visit(node):
|
| 105 |
+
if node in visited or node in in_progress:
|
| 106 |
+
return
|
| 107 |
+
in_progress.add(node)
|
| 108 |
+
for successor in sorted(edges.get(node, ())):
|
| 109 |
+
visit(successor)
|
| 110 |
+
in_progress.discard(node)
|
| 111 |
+
visited.add(node)
|
| 112 |
+
order.append(node)
|
| 113 |
+
|
| 114 |
+
for node in sorted(nodes):
|
| 115 |
+
visit(node)
|
| 116 |
+
order.reverse()
|
| 117 |
+
ranks_by_scene[scene] = {name: rank for rank, name in enumerate(order)}
|
| 118 |
+
return ranks_by_scene
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _floor_level(object_bbox):
|
| 122 |
+
"""Return the lowest z any annotated object's oriented box reaches: the support of
|
| 123 |
+
each box along -z, i.e. centroid_z minus the box's half-extent projected onto z
|
| 124 |
+
(sum of half-dimension * |axis . z| across all three axes -- the true lowest corner
|
| 125 |
+
of a tilted box, not just its centroid)."""
|
| 126 |
+
lowest = []
|
| 127 |
+
for instances in object_bbox.values():
|
| 128 |
+
for instance in instances:
|
| 129 |
+
centroid_z = float(instance["centroid"][2])
|
| 130 |
+
dims = np.asarray(instance["axesLengths"], np.float64)
|
| 131 |
+
axes = np.asarray(instance["normalizedAxes"], np.float64).reshape(3, 3)
|
| 132 |
+
axes = axes / np.linalg.norm(axes, axis=1, keepdims=True)
|
| 133 |
+
half_extent_z = float(np.sum(dims / 2 * np.abs(axes[:, 2])))
|
| 134 |
+
lowest.append(centroid_z - half_extent_z)
|
| 135 |
+
return min(lowest) if lowest else 0.0
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _gt_oriented_box(instance, floor_level):
|
| 139 |
+
"""Return one compact "3D oriented bounding box" dict straight from a meta_info
|
| 140 |
+
object_bbox instance -- centroid/axesLengths/normalizedAxes pass through as this
|
| 141 |
+
dataset's own gravity-aligned x, y, z (see module docstring), only re-based so the
|
| 142 |
+
third component is height above this scene's own floor reference."""
|
| 143 |
+
centroid = np.asarray(instance["centroid"], np.float64)
|
| 144 |
+
dims = np.asarray(instance["axesLengths"], np.float64)
|
| 145 |
+
axes = np.asarray(instance["normalizedAxes"], np.float64).reshape(3, 3)
|
| 146 |
+
axes = axes / np.linalg.norm(axes, axis=1, keepdims=True)
|
| 147 |
+
center = [float(centroid[0]), float(centroid[1]), float(centroid[2]) - floor_level]
|
| 148 |
+
return {
|
| 149 |
+
"3D oriented bounding box center coordinates": _rounded_list(center),
|
| 150 |
+
"3D oriented bounding box dimensions": _rounded_list(dims.tolist()),
|
| 151 |
+
"3D oriented bounding box orientation unit vectors": [
|
| 152 |
+
_rounded_list(row.tolist()) for row in axes
|
| 153 |
+
],
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _gt_floor_boundary_polygons(room_size, room_center):
|
| 158 |
+
"""A single axis-aligned square of exactly area ``room_size`` centered at
|
| 159 |
+
``room_center``'s (x, y) -- the floor-SHAPE stand-in the annotations actually
|
| 160 |
+
support (see module docstring); no holes, since meta_info carries no boundary
|
| 161 |
+
detail to place one from."""
|
| 162 |
+
half_side = float(np.sqrt(max(room_size, 0.0))) / 2
|
| 163 |
+
cx, cy = float(room_center[0]), float(room_center[1])
|
| 164 |
+
corners = [
|
| 165 |
+
[cx - half_side, cy - half_side],
|
| 166 |
+
[cx + half_side, cy - half_side],
|
| 167 |
+
[cx + half_side, cy + half_side],
|
| 168 |
+
[cx - half_side, cy + half_side],
|
| 169 |
+
]
|
| 170 |
+
return [
|
| 171 |
+
{
|
| 172 |
+
"outer boundary coordinates": [_rounded_list(corner) for corner in corners],
|
| 173 |
+
"interior hole boundary coordinates": [],
|
| 174 |
+
}
|
| 175 |
+
]
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def build_compact_ground_truth_spatial_code(scene):
|
| 179 |
+
"""Build the compact spatial code for ``scene`` directly from its dataset annotation
|
| 180 |
+
(meta_info), in the exact COMPACT_SPATIAL_CODE_SCHEMA shape/legend build_compact_
|
| 181 |
+
spatial_code() produces from the perception pipeline."""
|
| 182 |
+
meta = load_meta_info()
|
| 183 |
+
if scene not in meta:
|
| 184 |
+
raise KeyError(f"no meta_info ground truth for scene {scene!r}")
|
| 185 |
+
record = meta[scene]
|
| 186 |
+
object_bbox = record["object_bbox"]
|
| 187 |
+
floor_level = _floor_level(object_bbox)
|
| 188 |
+
ranks = _appearance_order_ranks_by_scene().get(scene, {})
|
| 189 |
+
|
| 190 |
+
objects = {}
|
| 191 |
+
for class_name, instances in object_bbox.items():
|
| 192 |
+
rank = ranks.get(class_name)
|
| 193 |
+
objects[class_name] = [
|
| 194 |
+
{
|
| 195 |
+
"3D oriented bounding box": _gt_oriented_box(instance, floor_level),
|
| 196 |
+
"first visible time": float(rank) if rank is not None else None,
|
| 197 |
+
}
|
| 198 |
+
for instance in instances
|
| 199 |
+
]
|
| 200 |
+
|
| 201 |
+
return {
|
| 202 |
+
"objects": objects,
|
| 203 |
+
"room": {
|
| 204 |
+
"floor boundary polygons": _gt_floor_boundary_polygons(
|
| 205 |
+
record["room_size"], record["room_center"]
|
| 206 |
+
)
|
| 207 |
+
},
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def build_explicit_ground_truth_spatial_code(scene):
|
| 212 |
+
"""Build the explicit spatial code for ``scene`` as the exact same strict derivation
|
| 213 |
+
of a compact code that build_explicit_spatial_code() uses for encoder-built codes,
|
| 214 |
+
applied to build_compact_ground_truth_spatial_code()'s output instead."""
|
| 215 |
+
compact_code = build_compact_ground_truth_spatial_code(scene)
|
| 216 |
+
code, _floor_area = _explicit_from_compact(compact_code)
|
| 217 |
+
return code
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def build_ground_truth_spatial_code(scene, spatial_code_format="explicit"):
|
| 221 |
+
"""Dispatch to the compact or explicit ground-truth builder, mirroring
|
| 222 |
+
encoder.geometric.build_spatial_code's format switch."""
|
| 223 |
+
if spatial_code_format == "compact":
|
| 224 |
+
return build_compact_ground_truth_spatial_code(scene)
|
| 225 |
+
if spatial_code_format == "explicit":
|
| 226 |
+
return build_explicit_ground_truth_spatial_code(scene)
|
| 227 |
+
raise ValueError(
|
| 228 |
+
f"unknown spatial-code format {spatial_code_format!r}; expected 'compact' or 'explicit'"
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def build_and_write(scene, spatial_code_format="explicit"):
|
| 233 |
+
"""Build one scene's ground-truth spatial code and write it to its on-disk path
|
| 234 |
+
(encoder.config.ground_truth_spatial_code_path), creating parent directories as
|
| 235 |
+
needed. Returns the path written."""
|
| 236 |
+
code = build_ground_truth_spatial_code(scene, spatial_code_format)
|
| 237 |
+
path = config.ground_truth_spatial_code_path(scene, spatial_code_format)
|
| 238 |
+
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
| 239 |
+
dump_spatial_code(code, path)
|
| 240 |
+
return path
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def scenes():
|
| 244 |
+
"""Every scene meta_info has ground truth for (a superset of every scene any
|
| 245 |
+
perception-built spatial code could ever cover, since this needs no SAM3/DA3 cache).
|
| 246 |
+
"""
|
| 247 |
+
return sorted(load_meta_info())
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def build_all(spatial_code_formats=("explicit", "compact"), scene_list=None):
|
| 251 |
+
"""Build and write ground-truth spatial codes for every scene (or ``scene_list``)
|
| 252 |
+
in both formats by default. Returns the list of paths written."""
|
| 253 |
+
written = []
|
| 254 |
+
for scene in scene_list if scene_list is not None else scenes():
|
| 255 |
+
for spatial_code_format in spatial_code_formats:
|
| 256 |
+
written.append(build_and_write(scene, spatial_code_format))
|
| 257 |
+
return written
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
if __name__ == "__main__":
|
| 261 |
+
import argparse
|
| 262 |
+
|
| 263 |
+
parser = argparse.ArgumentParser()
|
| 264 |
+
parser.add_argument(
|
| 265 |
+
"--scenes", help="comma-separated scenes (default: every scene)"
|
| 266 |
+
)
|
| 267 |
+
parser.add_argument(
|
| 268 |
+
"--formats",
|
| 269 |
+
default="explicit,compact",
|
| 270 |
+
help="comma-separated spatial-code formats",
|
| 271 |
+
)
|
| 272 |
+
args = parser.parse_args()
|
| 273 |
+
scene_list = (
|
| 274 |
+
[scene.strip() for scene in args.scenes.split(",") if scene.strip()]
|
| 275 |
+
if args.scenes
|
| 276 |
+
else None
|
| 277 |
+
)
|
| 278 |
+
formats = tuple(fmt.strip() for fmt in args.formats.split(",") if fmt.strip())
|
| 279 |
+
paths = build_all(formats, scene_list)
|
| 280 |
+
print(f"wrote {len(paths)} ground-truth spatial codes")
|
harness/C/__init__.py
CHANGED
|
@@ -1,7 +1,17 @@
|
|
| 1 |
-
"""Harness C
|
|
|
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
"""
|
| 6 |
|
| 7 |
from __future__ import annotations
|
|
@@ -33,5 +43,5 @@ assert INPUT_SELECTIONS == FRAME_SELECTIONS # one shared vocabulary drives both
|
|
| 33 |
FRAMES_PER_VIDEO = int(os.environ.get("VSI_HARNESS_C_FRAMES_PER_VIDEO", "32"))
|
| 34 |
|
| 35 |
# One JSON per question, matching harness.A/B's layout:
|
| 36 |
-
# results/C/<model>/
|
| 37 |
RESULTS_DIR = Path(os.environ.get("VSI_HARNESS_C_RESULTS_DIR", "/root/results/C"))
|
|
|
|
| 1 |
+
"""Harness C: route BOTH a scene's video frames AND its on-disk spatial code (explicit
|
| 2 |
+
explicit) to all three models, for every VSI-Bench question.
|
| 3 |
|
| 4 |
+
Frames and spatial code are sourced from the exact same (depth, tracking,
|
| 5 |
+
input_selection, frame_count) config -- the same parameters drive both
|
| 6 |
+
harness.A.frames.sample_frames() and harness.B.spatial_codes.load_spatial_code(), so the
|
| 7 |
+
spatial code shown to the model is guaranteed to have been built from sampling the same
|
| 8 |
+
video the same way the frames themselves are sampled here; they can never mismatch.
|
| 9 |
+
|
| 10 |
+
Reuses harness.A's model registry/adapters and fixed generation protocol exactly, and
|
| 11 |
+
harness.B's spatial-code loading and format/input-selection vocabulary. Results are
|
| 12 |
+
written in the identical per-question JSON shape harness.A and harness.B use, with both
|
| 13 |
+
harnesses' provenance fields present (frame provenance from A, spatial-code provenance
|
| 14 |
+
from B) since C uses both kinds of input.
|
| 15 |
"""
|
| 16 |
|
| 17 |
from __future__ import annotations
|
|
|
|
| 43 |
FRAMES_PER_VIDEO = int(os.environ.get("VSI_HARNESS_C_FRAMES_PER_VIDEO", "32"))
|
| 44 |
|
| 45 |
# One JSON per question, matching harness.A/B's layout:
|
| 46 |
+
# results/C/<model>/<spatial_code_format>/<depth>/<tracking>/<input_selection>/<frame_count>/<scene>/<question_id>.json
|
| 47 |
RESULTS_DIR = Path(os.environ.get("VSI_HARNESS_C_RESULTS_DIR", "/root/results/C"))
|
harness/C/launch.py
CHANGED
|
@@ -56,9 +56,6 @@ def _worker(
|
|
| 56 |
input_selection,
|
| 57 |
frame_count,
|
| 58 |
video,
|
| 59 |
-
spatial_code_source,
|
| 60 |
-
spatial_code_input_selection,
|
| 61 |
-
spatial_code_frame_count,
|
| 62 |
depth,
|
| 63 |
tracking,
|
| 64 |
results_dir,
|
|
@@ -97,9 +94,6 @@ def _worker(
|
|
| 97 |
input_selection=input_selection,
|
| 98 |
frame_count=frame_count,
|
| 99 |
video=video,
|
| 100 |
-
spatial_code_source=spatial_code_source,
|
| 101 |
-
spatial_code_input_selection=spatial_code_input_selection,
|
| 102 |
-
spatial_code_frame_count=spatial_code_frame_count,
|
| 103 |
depth=depth,
|
| 104 |
tracking=tracking,
|
| 105 |
scene=scene,
|
|
@@ -126,9 +120,6 @@ def launch(
|
|
| 126 |
frame_count,
|
| 127 |
selected,
|
| 128 |
video=False,
|
| 129 |
-
spatial_code_source="frames",
|
| 130 |
-
spatial_code_input_selection=DEFAULT_INPUT_SELECTION,
|
| 131 |
-
spatial_code_frame_count=FRAMES_PER_VIDEO,
|
| 132 |
depth=DEFAULT_DEPTH,
|
| 133 |
tracking=DEFAULT_TRACKING,
|
| 134 |
results_dir=None,
|
|
@@ -144,17 +135,7 @@ def launch(
|
|
| 144 |
elif frame_count is None or frame_count < 1:
|
| 145 |
raise ValueError("frame_count must be positive in frames mode")
|
| 146 |
mode = "video" if video else f"{input_selection}/{frame_count}"
|
| 147 |
-
|
| 148 |
-
code_input_selection, code_frame_count, code_mode = "video", None, "video"
|
| 149 |
-
elif spatial_code_source == "frames":
|
| 150 |
-
if spatial_code_frame_count is None or spatial_code_frame_count < 1:
|
| 151 |
-
raise ValueError("spatial_code_frame_count must be positive")
|
| 152 |
-
code_input_selection = spatial_code_input_selection
|
| 153 |
-
code_frame_count = spatial_code_frame_count
|
| 154 |
-
code_mode = f"{code_input_selection}/{code_frame_count}"
|
| 155 |
-
else:
|
| 156 |
-
raise ValueError("spatial_code_source must be frames or video")
|
| 157 |
-
condition = f"{model}/{spatial_code_format}/{depth}/{tracking}/code-{code_mode}/visual-{mode}"
|
| 158 |
run = _load_run_module()
|
| 159 |
root = run.results_dir_for(
|
| 160 |
model,
|
|
@@ -164,9 +145,6 @@ def launch(
|
|
| 164 |
tracking,
|
| 165 |
input_selection,
|
| 166 |
frame_count,
|
| 167 |
-
spatial_code_source,
|
| 168 |
-
code_input_selection,
|
| 169 |
-
code_frame_count,
|
| 170 |
results_dir,
|
| 171 |
)
|
| 172 |
pending = []
|
|
@@ -218,9 +196,6 @@ def launch(
|
|
| 218 |
input_selection,
|
| 219 |
frame_count,
|
| 220 |
video,
|
| 221 |
-
spatial_code_source,
|
| 222 |
-
code_input_selection,
|
| 223 |
-
code_frame_count,
|
| 224 |
depth,
|
| 225 |
tracking,
|
| 226 |
results_dir,
|
|
@@ -272,9 +247,6 @@ def main():
|
|
| 272 |
input_mode = parser.add_mutually_exclusive_group(required=True)
|
| 273 |
input_mode.add_argument("--frames", type=int)
|
| 274 |
input_mode.add_argument("--video", action="store_true")
|
| 275 |
-
parser.add_argument("--spatial-code-source", required=True, choices=("frames", "video"))
|
| 276 |
-
parser.add_argument("--spatial-code-input-selection", choices=INPUT_SELECTIONS)
|
| 277 |
-
parser.add_argument("--spatial-code-frames", type=int)
|
| 278 |
parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS)
|
| 279 |
parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES)
|
| 280 |
parser.add_argument("--results-dir", default=None)
|
|
@@ -309,14 +281,6 @@ def main():
|
|
| 309 |
parser.error("--input-selection is required with --frames")
|
| 310 |
if args.frames < 1:
|
| 311 |
parser.error("--frames must be positive")
|
| 312 |
-
if args.spatial_code_source == "video":
|
| 313 |
-
if args.spatial_code_input_selection is not None or args.spatial_code_frames is not None:
|
| 314 |
-
parser.error("spatial-code frame flags cannot be used with --spatial-code-source video")
|
| 315 |
-
else:
|
| 316 |
-
if args.spatial_code_input_selection is None or args.spatial_code_frames is None:
|
| 317 |
-
parser.error("--spatial-code-input-selection and --spatial-code-frames are required with --spatial-code-source frames")
|
| 318 |
-
if args.spatial_code_frames < 1:
|
| 319 |
-
parser.error("--spatial-code-frames must be positive")
|
| 320 |
resolve_protocol_budgets(parser, args)
|
| 321 |
launch(
|
| 322 |
args.model,
|
|
@@ -325,9 +289,6 @@ def main():
|
|
| 325 |
args.frames,
|
| 326 |
selected,
|
| 327 |
video=args.video,
|
| 328 |
-
spatial_code_source=args.spatial_code_source,
|
| 329 |
-
spatial_code_input_selection=args.spatial_code_input_selection,
|
| 330 |
-
spatial_code_frame_count=args.spatial_code_frames,
|
| 331 |
depth=args.depth,
|
| 332 |
tracking=args.tracking,
|
| 333 |
results_dir=args.results_dir,
|
|
|
|
| 56 |
input_selection,
|
| 57 |
frame_count,
|
| 58 |
video,
|
|
|
|
|
|
|
|
|
|
| 59 |
depth,
|
| 60 |
tracking,
|
| 61 |
results_dir,
|
|
|
|
| 94 |
input_selection=input_selection,
|
| 95 |
frame_count=frame_count,
|
| 96 |
video=video,
|
|
|
|
|
|
|
|
|
|
| 97 |
depth=depth,
|
| 98 |
tracking=tracking,
|
| 99 |
scene=scene,
|
|
|
|
| 120 |
frame_count,
|
| 121 |
selected,
|
| 122 |
video=False,
|
|
|
|
|
|
|
|
|
|
| 123 |
depth=DEFAULT_DEPTH,
|
| 124 |
tracking=DEFAULT_TRACKING,
|
| 125 |
results_dir=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,
|
|
|
|
| 145 |
tracking,
|
| 146 |
input_selection,
|
| 147 |
frame_count,
|
|
|
|
|
|
|
|
|
|
| 148 |
results_dir,
|
| 149 |
)
|
| 150 |
pending = []
|
|
|
|
| 196 |
input_selection,
|
| 197 |
frame_count,
|
| 198 |
video,
|
|
|
|
|
|
|
|
|
|
| 199 |
depth,
|
| 200 |
tracking,
|
| 201 |
results_dir,
|
|
|
|
| 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)
|
|
|
|
| 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,
|
|
|
|
| 289 |
args.frames,
|
| 290 |
selected,
|
| 291 |
video=args.video,
|
|
|
|
|
|
|
|
|
|
| 292 |
depth=args.depth,
|
| 293 |
tracking=args.tracking,
|
| 294 |
results_dir=args.results_dir,
|
harness/C/overlay.py
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Set-of-Marks overlay for the strong correspondence arm (harness C) -- sourced
|
| 2 |
+
PURELY from SAM3's own raw per-frame output. No 3D math anywhere in this module.
|
| 3 |
+
|
| 4 |
+
Gives frames and spatial code a SHARED instance namespace with 1:1 correspondence
|
| 5 |
+
guaranteed BY CONSTRUCTION: every explicit-code instance gets an id ("bed 1",
|
| 6 |
+
"chair 2", ...), and that id is stamped in EXACTLY the frames SAM3's own tracker
|
| 7 |
+
reported that instance's masklet(s) present in, at EXACTLY the bounding box SAM3's
|
| 8 |
+
own tracker reported for it there. There is no camera projection, no floor-basis
|
| 9 |
+
inversion, no depth buffer, no occlusion heuristic anywhere in this pipeline -- an
|
| 10 |
+
instance is drawn iff SAM3's raw cache says it's in this frame, at the box SAM3's
|
| 11 |
+
raw cache says it's at. Any placement error, missing detection, or wrong-frame
|
| 12 |
+
presence is therefore attributable to SAM3 (or the SAM3->code consolidation
|
| 13 |
+
encoder.geometric already performs, verified separately), never to this module's
|
| 14 |
+
own math, since this module doesn't do any.
|
| 15 |
+
|
| 16 |
+
Provenance (which raw SAM3 masklet id(s) a final code instance came from) is
|
| 17 |
+
recovered via encoder.geometric.instance_source_track_ids(), which exposes the
|
| 18 |
+
"oids" field build_compact_spatial_code()'s own consolidation pipeline threads
|
| 19 |
+
through internally but never emits in the on-disk schema (adding it there would
|
| 20 |
+
change every harness's prompt -- this module is the only consumer).
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import json
|
| 26 |
+
import sys
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 30 |
+
|
| 31 |
+
# Markers are drawn on a layer rendered at _SUPERSAMPLE x the frame's own resolution,
|
| 32 |
+
# then downsampled with LANCZOS before compositing -- this is what makes the box
|
| 33 |
+
# edges and glyph strokes look crisp/anti-aliased rather than jagged, WITHOUT the
|
| 34 |
+
# marker's rendered footprint on the final frame growing (that footprint is set by
|
| 35 |
+
# _FONT_SIZE below, sized for the frame's OWN resolution).
|
| 36 |
+
_SUPERSAMPLE = 3
|
| 37 |
+
_FONT_SIZE = 15
|
| 38 |
+
_MARKER_RADIUS = 5
|
| 39 |
+
_MAX_NUDGES = 12
|
| 40 |
+
|
| 41 |
+
# A scalable font, not PIL's tiny fixed-size default bitmap font -- labels need to be
|
| 42 |
+
# legible to a human reviewer (and to the model) at typical VSI-Bench frame resolution.
|
| 43 |
+
# DejaVuSans-Bold ships inside every Pillow install (PIL/fonts/), so this never depends
|
| 44 |
+
# on the host having a system font installed.
|
| 45 |
+
try:
|
| 46 |
+
_LABEL_FONT = ImageFont.truetype(
|
| 47 |
+
str(Path(ImageFont.__file__).parent / "fonts" / "DejaVuSans-Bold.ttf"),
|
| 48 |
+
_FONT_SIZE * _SUPERSAMPLE,
|
| 49 |
+
)
|
| 50 |
+
except OSError:
|
| 51 |
+
_LABEL_FONT = ImageFont.load_default(size=_FONT_SIZE * _SUPERSAMPLE)
|
| 52 |
+
|
| 53 |
+
WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent
|
| 54 |
+
if str(WORKSPACE_ROOT) not in sys.path:
|
| 55 |
+
sys.path.insert(0, str(WORKSPACE_ROOT))
|
| 56 |
+
|
| 57 |
+
from encoder import config as encoder_config # noqa: E402
|
| 58 |
+
from encoder import geometric as gm # noqa: E402
|
| 59 |
+
from encoder import run as perceive # noqa: E402
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _parse_meters(value):
|
| 63 |
+
return float(str(value).split()[0])
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _boxes_overlap(a, b):
|
| 67 |
+
return a[0] < b[2] and a[2] > b[0] and a[1] < b[3] and a[3] > b[1]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _place_label_box(anchor_x, anchor_y, width, height, placed, frame_h, step):
|
| 71 |
+
"""Return ((left, top, right, bottom), was_nudged) for one label, greedily moved
|
| 72 |
+
vertically away from every box already in ``placed`` (deterministic: labels are
|
| 73 |
+
tried in the caller's fixed order, so a given code always nudges the same way).
|
| 74 |
+
``was_nudged`` is False only for attempt 0 (the label's natural, un-collided
|
| 75 |
+
position) -- the caller uses it to draw a leader line ONLY when the label actually
|
| 76 |
+
moved away from its marker, instead of drawing one, unconditionally, that's too
|
| 77 |
+
short to see for every other label. Alternates below/above the anchor in
|
| 78 |
+
increasing steps so a crowded cluster fans out symmetrically instead of drifting
|
| 79 |
+
off in one direction; stops at ``_MAX_NUDGES`` attempts and returns the last-tried
|
| 80 |
+
box rather than looping forever -- a residual overlap in a dense cluster is a
|
| 81 |
+
real, visible property of that cluster, not something to hide by trying
|
| 82 |
+
indefinitely."""
|
| 83 |
+
for attempt in range(_MAX_NUDGES):
|
| 84 |
+
direction = 1 if attempt % 2 == 0 else -1
|
| 85 |
+
offset = direction * step * ((attempt + 1) // 2)
|
| 86 |
+
top = anchor_y + offset
|
| 87 |
+
box = (anchor_x, top, anchor_x + width, top + height)
|
| 88 |
+
if (
|
| 89 |
+
0 <= box[1]
|
| 90 |
+
and box[3] <= frame_h
|
| 91 |
+
and not any(_boxes_overlap(box, p) for p in placed)
|
| 92 |
+
):
|
| 93 |
+
return box, attempt > 0
|
| 94 |
+
return box, True
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def instance_ids(explicit_code):
|
| 98 |
+
"""Return a copy of an explicit code whose instances each carry an
|
| 99 |
+
'"instance id": "<class> <n>"' field (1-based, in the code's own list order --
|
| 100 |
+
the same numbering label_positions() and stamp_frames() use). Input not mutated."""
|
| 101 |
+
code = dict(explicit_code)
|
| 102 |
+
objects = {}
|
| 103 |
+
for class_name, rendered in code.get("objects", {}).items():
|
| 104 |
+
instances = [
|
| 105 |
+
{**instance, "instance id": f"{class_name} {index}"}
|
| 106 |
+
for index, instance in enumerate(rendered.get("instances", []), 1)
|
| 107 |
+
]
|
| 108 |
+
objects[class_name] = {**rendered, "instances": instances}
|
| 109 |
+
code["objects"] = objects
|
| 110 |
+
return code
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def label_positions(explicit_code):
|
| 114 |
+
"""Return [(label, floor_x, floor_y, height_above_floor, longest_dimension)] for
|
| 115 |
+
every instance, labeled identically to instance_ids(). NOT used by stamp_frames
|
| 116 |
+
(which sources positions from SAM3's own raw boxes, not the code's stored 3D
|
| 117 |
+
position) -- kept as a standalone utility for auditing the code's own claimed
|
| 118 |
+
geometry against a scene (e.g. checking a suspect instance's stored height)."""
|
| 119 |
+
out = []
|
| 120 |
+
for class_name, rendered in explicit_code.get("objects", {}).items():
|
| 121 |
+
for index, instance in enumerate(rendered.get("instances", []), 1):
|
| 122 |
+
position = instance["position"]
|
| 123 |
+
out.append(
|
| 124 |
+
(
|
| 125 |
+
f"{class_name} {index}",
|
| 126 |
+
_parse_meters(position["x coordinate"]),
|
| 127 |
+
_parse_meters(position["y coordinate"]),
|
| 128 |
+
_parse_meters(position["height above floor"]),
|
| 129 |
+
_parse_meters(instance["longest dimension"]),
|
| 130 |
+
)
|
| 131 |
+
)
|
| 132 |
+
return out
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _load_raw_sam3_boxes(scene_id, input_selection, tracking, frame_count):
|
| 136 |
+
"""Return {class_name: {frame_index: {masklet_id: (x, y, w, h) normalized [0,1]}}}
|
| 137 |
+
read directly from the native SAM3 tracking cache -- the same file
|
| 138 |
+
encoder.run.cache_or_load() itself reads, parsed here with NO further processing
|
| 139 |
+
(no masking, no merging, no geometry): exactly what SAM3's own tracker reported,
|
| 140 |
+
per frame, per masklet."""
|
| 141 |
+
import torch
|
| 142 |
+
|
| 143 |
+
path = encoder_config.sam3_cache_file(
|
| 144 |
+
scene_id, input_selection, tracking, frame_count
|
| 145 |
+
)
|
| 146 |
+
if not Path(path).is_file():
|
| 147 |
+
raise FileNotFoundError(
|
| 148 |
+
f"no raw SAM3 cache found for scene {scene_id!r} at {path} -- the strong "
|
| 149 |
+
"correspondence arm needs the scene's SAM3 perception cache on disk"
|
| 150 |
+
)
|
| 151 |
+
raw = torch.load(path, map_location="cpu", weights_only=False)
|
| 152 |
+
out = {}
|
| 153 |
+
for class_name, class_data in raw.items():
|
| 154 |
+
stream = class_data.get("stream", []) if isinstance(class_data, dict) else []
|
| 155 |
+
frames = {}
|
| 156 |
+
for entry in stream:
|
| 157 |
+
outputs = entry.get("outputs", {})
|
| 158 |
+
obj_ids = outputs.get("out_obj_ids", [])
|
| 159 |
+
boxes = outputs.get("out_boxes_xywh", [])
|
| 160 |
+
frames[int(entry["frame_index"])] = {
|
| 161 |
+
int(oid): tuple(float(v) for v in box)
|
| 162 |
+
for oid, box in zip(obj_ids, boxes)
|
| 163 |
+
}
|
| 164 |
+
out[str(class_name)] = frames
|
| 165 |
+
return out
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def overlay_frame_cache_dir(scene_id, depth, input_selection, tracking, frame_count):
|
| 169 |
+
"""Return the on-disk cache directory for one scene's stamped overlay frames --
|
| 170 |
+
same axes as the spatial code path (depth still matters here even though box
|
| 171 |
+
POSITIONS never touch it: instance_source_track_ids's provenance mapping, which
|
| 172 |
+
decides which raw SAM3 id becomes "chair 1" vs "chair 3", is computed via
|
| 173 |
+
room_gravity on the depth-specific geometry cache). Format is always explicit
|
| 174 |
+
(the only format the correspondence arms support), so it isn't part of the path."""
|
| 175 |
+
return (
|
| 176 |
+
encoder_config.CACHE_ROOT
|
| 177 |
+
/ "overlay-frames"
|
| 178 |
+
/ depth
|
| 179 |
+
/ tracking
|
| 180 |
+
/ input_selection
|
| 181 |
+
/ str(frame_count)
|
| 182 |
+
/ scene_id
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def overlay_spatial_code_path(scene_id, depth, input_selection, tracking, frame_count):
|
| 187 |
+
"""Return the durable overlay-code JSON path for one scene/config.
|
| 188 |
+
|
| 189 |
+
Overlay codes are stored under the configured spatial-code root's top-level
|
| 190 |
+
``overlay`` directory so an overlay run has a browsable code artifact matching
|
| 191 |
+
the stamped frames, instead of only an in-memory prompt transform.
|
| 192 |
+
"""
|
| 193 |
+
encoder_config._validate_dimensions(depth, input_selection, tracking, frame_count)
|
| 194 |
+
return (
|
| 195 |
+
encoder_config.CODES_ROOT
|
| 196 |
+
/ "overlay"
|
| 197 |
+
/ encoder_config.MODEL
|
| 198 |
+
/ depth
|
| 199 |
+
/ tracking
|
| 200 |
+
/ input_selection
|
| 201 |
+
/ str(frame_count)
|
| 202 |
+
/ "explicit"
|
| 203 |
+
/ f"{scene_id}.json"
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def load_or_create_overlay_code(
|
| 208 |
+
explicit_code, scene_id, depth, input_selection, tracking, frame_count
|
| 209 |
+
):
|
| 210 |
+
"""Load an existing overlay code, or create and save it from ``explicit_code``.
|
| 211 |
+
|
| 212 |
+
The saved code is exactly ``instance_ids(explicit_code)``. Existing files are
|
| 213 |
+
trusted as the durable artifact for that scene/config and are not rewritten.
|
| 214 |
+
Returns ``(code, path)``.
|
| 215 |
+
"""
|
| 216 |
+
path = overlay_spatial_code_path(
|
| 217 |
+
scene_id, depth, input_selection, tracking, frame_count
|
| 218 |
+
)
|
| 219 |
+
if path.is_file():
|
| 220 |
+
return json.loads(path.read_text(encoding="utf-8")), str(path)
|
| 221 |
+
code = instance_ids(explicit_code)
|
| 222 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 223 |
+
path.write_text(json.dumps(code, indent=1) + "\n", encoding="utf-8")
|
| 224 |
+
return code, str(path)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def _load_cached_frames(cache_dir, frame_count):
|
| 228 |
+
"""Return (stamped_frame_copies, per_frame_visible_labels) if a complete cache
|
| 229 |
+
exists at ``cache_dir`` (every frame PNG plus the labels sidecar present), else
|
| 230 |
+
None. A partial cache (e.g. an interrupted pre-generation run) is treated as
|
| 231 |
+
absent -- regenerated in full, never silently served incomplete."""
|
| 232 |
+
labels_path = cache_dir / "labels.json"
|
| 233 |
+
if not labels_path.is_file():
|
| 234 |
+
return None
|
| 235 |
+
frame_paths = [cache_dir / f"{i}.png" for i in range(frame_count)]
|
| 236 |
+
if not all(path.is_file() for path in frame_paths):
|
| 237 |
+
return None
|
| 238 |
+
images = [Image.open(path).convert("RGB") for path in frame_paths]
|
| 239 |
+
visible = json.loads(labels_path.read_text())
|
| 240 |
+
return images, visible
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def _save_cached_frames(cache_dir, stamped, visible):
|
| 244 |
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 245 |
+
for i, image in enumerate(stamped):
|
| 246 |
+
image.save(cache_dir / f"{i}.png")
|
| 247 |
+
(cache_dir / "labels.json").write_text(json.dumps(visible))
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def stamp_frames(
|
| 251 |
+
frame_images,
|
| 252 |
+
explicit_code,
|
| 253 |
+
scene_id,
|
| 254 |
+
depth,
|
| 255 |
+
input_selection,
|
| 256 |
+
tracking,
|
| 257 |
+
frame_count,
|
| 258 |
+
use_cache=True,
|
| 259 |
+
):
|
| 260 |
+
"""Return (stamped_frame_copies, per_frame_visible_labels). For every code
|
| 261 |
+
instance, looks up which raw SAM3 masklet id(s) it consolidated from
|
| 262 |
+
(encoder.geometric.instance_source_track_ids) and, per frame, whether SAM3's own
|
| 263 |
+
tracker reported any of those ids present -- if so, stamps SAM3's own reported box
|
| 264 |
+
for it, verbatim. An instance is absent from a frame's output iff SAM3's raw
|
| 265 |
+
tracker never reported it there; there is no other reason. Input images are
|
| 266 |
+
never mutated.
|
| 267 |
+
|
| 268 |
+
``use_cache=True`` (default) reads/writes a persistent on-disk cache under
|
| 269 |
+
overlay_frame_cache_dir() -- the same stamping is otherwise recomputed from
|
| 270 |
+
scratch on every call (once per scene per model per run), and the result is
|
| 271 |
+
scene-only (never model- or question-dependent), so caching it once and reusing
|
| 272 |
+
it across every model/run that touches this scene/config is a pure speed win.
|
| 273 |
+
Pass False to force a fresh computation (e.g. after a code or overlay-logic
|
| 274 |
+
change, before the cache is known to be stale and worth clearing)."""
|
| 275 |
+
cache_dir = overlay_frame_cache_dir(
|
| 276 |
+
scene_id, depth, input_selection, tracking, frame_count
|
| 277 |
+
)
|
| 278 |
+
if use_cache:
|
| 279 |
+
cached = _load_cached_frames(cache_dir, frame_count)
|
| 280 |
+
if cached is not None:
|
| 281 |
+
return cached
|
| 282 |
+
geometry, _how = perceive.cache_or_load(
|
| 283 |
+
scene_id, depth, input_selection, tracking, frame_count, False
|
| 284 |
+
)
|
| 285 |
+
provenance = gm.instance_source_track_ids(geometry)
|
| 286 |
+
raw_boxes = _load_raw_sam3_boxes(scene_id, input_selection, tracking, frame_count)
|
| 287 |
+
|
| 288 |
+
labels = []
|
| 289 |
+
for class_name, rendered in explicit_code.get("objects", {}).items():
|
| 290 |
+
oid_lists = provenance.get(class_name, [])
|
| 291 |
+
for index, _instance in enumerate(rendered.get("instances", []), 1):
|
| 292 |
+
oids = oid_lists[index - 1] if index - 1 < len(oid_lists) else []
|
| 293 |
+
labels.append((f"{class_name} {index}", class_name, oids))
|
| 294 |
+
|
| 295 |
+
stamped, visible = [], []
|
| 296 |
+
for frame_index, image in enumerate(frame_images):
|
| 297 |
+
image = image.convert("RGB")
|
| 298 |
+
# Markers are drawn on a transparent layer at _SUPERSAMPLE x resolution, THEN
|
| 299 |
+
# downsampled with LANCZOS and alpha-composited onto the (unscaled, un-blurred)
|
| 300 |
+
# frame -- crisp anti-aliased edges on the marker itself, no change to the
|
| 301 |
+
# underlying photo's own resolution or the marker's on-frame footprint.
|
| 302 |
+
hi_res_size = (image.size[0] * _SUPERSAMPLE, image.size[1] * _SUPERSAMPLE)
|
| 303 |
+
overlay_layer = Image.new("RGBA", hi_res_size, (0, 0, 0, 0))
|
| 304 |
+
draw = ImageDraw.Draw(overlay_layer)
|
| 305 |
+
marker_r = _MARKER_RADIUS * _SUPERSAMPLE
|
| 306 |
+
placed_boxes = []
|
| 307 |
+
frame_labels = []
|
| 308 |
+
for label, class_name, oids in labels:
|
| 309 |
+
frame_detections = raw_boxes.get(class_name, {}).get(frame_index, {})
|
| 310 |
+
box = next(
|
| 311 |
+
(frame_detections[oid] for oid in oids if oid in frame_detections), None
|
| 312 |
+
)
|
| 313 |
+
if box is None:
|
| 314 |
+
continue # SAM3's own tracker did not report this instance in this frame
|
| 315 |
+
nx, ny, nw, nh = box # normalized [0,1] -- SAM3's own box, verbatim
|
| 316 |
+
bx0, by0 = nx * hi_res_size[0], ny * hi_res_size[1]
|
| 317 |
+
bw, bh = nw * hi_res_size[0], nh * hi_res_size[1]
|
| 318 |
+
draw.rectangle(
|
| 319 |
+
[bx0, by0, bx0 + bw, by0 + bh],
|
| 320 |
+
outline="red",
|
| 321 |
+
width=max(2, _SUPERSAMPLE),
|
| 322 |
+
)
|
| 323 |
+
px, py = bx0 + bw / 2, by0 + bh / 2
|
| 324 |
+
draw.ellipse(
|
| 325 |
+
[px - marker_r, py - marker_r, px + marker_r, py + marker_r],
|
| 326 |
+
outline="red",
|
| 327 |
+
width=max(2, _SUPERSAMPLE),
|
| 328 |
+
)
|
| 329 |
+
# Flip the label to the opposite side of the marker whenever its default
|
| 330 |
+
# placement would run off the frame -- a label clipped at the image edge is
|
| 331 |
+
# unreadable to both a human reviewer and the model.
|
| 332 |
+
text_width = draw.textlength(label, font=_LABEL_FONT)
|
| 333 |
+
text_height = _FONT_SIZE * _SUPERSAMPLE * 1.3
|
| 334 |
+
gap = 8 * _SUPERSAMPLE
|
| 335 |
+
text_x = (
|
| 336 |
+
px - gap - text_width
|
| 337 |
+
if px + gap + text_width > hi_res_size[0]
|
| 338 |
+
else px + gap
|
| 339 |
+
)
|
| 340 |
+
anchor_y = (
|
| 341 |
+
py + 4 * _SUPERSAMPLE
|
| 342 |
+
if py - 10 * _SUPERSAMPLE < 0
|
| 343 |
+
else py - 10 * _SUPERSAMPLE
|
| 344 |
+
)
|
| 345 |
+
# Nudge this label's box away from every label already placed in this
|
| 346 |
+
# frame -- a crowded cluster fans its labels out instead of stacking them
|
| 347 |
+
# into an unreadable smear (see _place_label_box's docstring).
|
| 348 |
+
label_box, was_nudged = _place_label_box(
|
| 349 |
+
text_x,
|
| 350 |
+
anchor_y,
|
| 351 |
+
text_width,
|
| 352 |
+
text_height,
|
| 353 |
+
placed_boxes,
|
| 354 |
+
hi_res_size[1],
|
| 355 |
+
step=text_height + 2 * _SUPERSAMPLE,
|
| 356 |
+
)
|
| 357 |
+
placed_boxes.append(label_box)
|
| 358 |
+
if was_nudged:
|
| 359 |
+
# A leader line from the marker to its (moved) label -- needed because
|
| 360 |
+
# dense clusters (several instances detected close together) can leave
|
| 361 |
+
# an unconnected dot cluster reading as unowned "random circles" once
|
| 362 |
+
# collision avoidance fans their labels apart. Only drawn when nudging
|
| 363 |
+
# actually happened -- a label already next to its own dot doesn't
|
| 364 |
+
# need one, and it would be invisible under the marker anyway.
|
| 365 |
+
anchor_x = label_box[2] if text_x < px else label_box[0]
|
| 366 |
+
anchor_y_mid = (label_box[1] + label_box[3]) / 2
|
| 367 |
+
draw.line(
|
| 368 |
+
[(px, py), (anchor_x, anchor_y_mid)],
|
| 369 |
+
fill=(255, 70, 55, 210),
|
| 370 |
+
width=max(2, _SUPERSAMPLE),
|
| 371 |
+
)
|
| 372 |
+
# A thin dark stroke (not a solid fill box) keeps the label legible
|
| 373 |
+
# against any background without blotting out the photo underneath it.
|
| 374 |
+
draw.text(
|
| 375 |
+
(label_box[0], label_box[1]),
|
| 376 |
+
label,
|
| 377 |
+
font=_LABEL_FONT,
|
| 378 |
+
fill="#ff4030",
|
| 379 |
+
stroke_width=max(2, _SUPERSAMPLE),
|
| 380 |
+
stroke_fill=(0, 0, 0, 235),
|
| 381 |
+
)
|
| 382 |
+
frame_labels.append(label)
|
| 383 |
+
overlay_layer = overlay_layer.resize(image.size, Image.LANCZOS)
|
| 384 |
+
composited = Image.alpha_composite(
|
| 385 |
+
image.convert("RGBA"), overlay_layer
|
| 386 |
+
).convert("RGB")
|
| 387 |
+
stamped.append(composited)
|
| 388 |
+
visible.append(frame_labels)
|
| 389 |
+
if use_cache:
|
| 390 |
+
_save_cached_frames(cache_dir, stamped, visible)
|
| 391 |
+
return stamped, visible
|
harness/C/overlay_launch.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pre-generate the strong correspondence arm's stamped-frame cache for many scenes
|
| 2 |
+
at once (harness.C.overlay.overlay_frame_cache_dir/stamp_frames).
|
| 3 |
+
|
| 4 |
+
Stamping is scene-only (never model- or question-dependent), so pre-populating the
|
| 5 |
+
cache once here means every later --overlay-ids run, for every model, reuses these
|
| 6 |
+
same files instead of recomputing the identical stamping from scratch each time --
|
| 7 |
+
and the cached PNGs are themselves a durable, browsable record of what every scene's
|
| 8 |
+
overlay actually looks like, independent of any particular model run.
|
| 9 |
+
|
| 10 |
+
Usage:
|
| 11 |
+
python -m harness.C.overlay_launch --depth metric --tracking tracking \\
|
| 12 |
+
--input uniform --frames 32
|
| 13 |
+
Pre-generates every scene with BOTH an explicit spatial code AND a SAM3
|
| 14 |
+
perception cache for this config -- skips scenes already cached and scenes
|
| 15 |
+
missing either dependency (reported, not silently dropped).
|
| 16 |
+
|
| 17 |
+
python -m harness.C.overlay_launch --depth metric --tracking tracking \\
|
| 18 |
+
--input uniform --frames 32 --scenes 42444976,45b0dac5e3
|
| 19 |
+
Restrict to specific scenes.
|
| 20 |
+
|
| 21 |
+
python -m harness.C.overlay_launch ... --rebuild
|
| 22 |
+
Recompute even scenes whose cache already exists (e.g. after an overlay.py
|
| 23 |
+
rendering change).
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import argparse
|
| 29 |
+
import multiprocessing as mp
|
| 30 |
+
import os
|
| 31 |
+
import sys
|
| 32 |
+
import traceback
|
| 33 |
+
from pathlib import Path
|
| 34 |
+
|
| 35 |
+
HERE = Path(__file__).resolve().parent
|
| 36 |
+
WORKSPACE_ROOT = HERE.parent.parent
|
| 37 |
+
if str(WORKSPACE_ROOT) not in sys.path:
|
| 38 |
+
sys.path.insert(0, str(WORKSPACE_ROOT))
|
| 39 |
+
|
| 40 |
+
from harness.A.launch import scenes as all_scenes # noqa: E402
|
| 41 |
+
from harness.A import frames as frame_sampling # noqa: E402
|
| 42 |
+
from harness.B import spatial_codes # noqa: E402
|
| 43 |
+
from harness.C import overlay # noqa: E402
|
| 44 |
+
import inference as inference_config # noqa: E402
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _available_cpu_count():
|
| 48 |
+
configured = os.environ.get("VSI_CPU_WORKERS")
|
| 49 |
+
if configured is not None:
|
| 50 |
+
count = int(configured)
|
| 51 |
+
if count < 1:
|
| 52 |
+
raise ValueError("VSI_CPU_WORKERS must be positive")
|
| 53 |
+
return count
|
| 54 |
+
try:
|
| 55 |
+
return max(1, len(os.sched_getaffinity(0)))
|
| 56 |
+
except AttributeError:
|
| 57 |
+
return max(1, os.cpu_count() or 1)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _has_dependencies(scene, depth, input_selection, tracking, frame_count):
|
| 61 |
+
"""True iff this scene has both an explicit spatial code AND a raw SAM3 cache
|
| 62 |
+
for this config -- both are required to stamp its frames."""
|
| 63 |
+
try:
|
| 64 |
+
spatial_codes.load_spatial_code(
|
| 65 |
+
scene, depth, input_selection, tracking, frame_count, "explicit"
|
| 66 |
+
)
|
| 67 |
+
except FileNotFoundError:
|
| 68 |
+
return False
|
| 69 |
+
from encoder import config as encoder_config
|
| 70 |
+
|
| 71 |
+
return Path(
|
| 72 |
+
encoder_config.sam3_cache_file(scene, input_selection, tracking, frame_count)
|
| 73 |
+
).is_file()
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _generate_one(args):
|
| 77 |
+
scene, depth, input_selection, tracking, frame_count = args
|
| 78 |
+
try:
|
| 79 |
+
code, _path = spatial_codes.load_spatial_code(
|
| 80 |
+
scene, depth, input_selection, tracking, frame_count, "explicit"
|
| 81 |
+
)
|
| 82 |
+
video_path = inference_config.video_path(scene, None)
|
| 83 |
+
frame_images, _ts, _idx = frame_sampling.sample_frames(
|
| 84 |
+
video_path, frame_count, input_selection
|
| 85 |
+
)
|
| 86 |
+
overlay.stamp_frames(
|
| 87 |
+
frame_images,
|
| 88 |
+
code,
|
| 89 |
+
scene,
|
| 90 |
+
depth,
|
| 91 |
+
input_selection,
|
| 92 |
+
tracking,
|
| 93 |
+
frame_count,
|
| 94 |
+
use_cache=True,
|
| 95 |
+
)
|
| 96 |
+
overlay.load_or_create_overlay_code(
|
| 97 |
+
code, scene, depth, input_selection, tracking, frame_count
|
| 98 |
+
)
|
| 99 |
+
return scene, True, None
|
| 100 |
+
except Exception:
|
| 101 |
+
return scene, False, traceback.format_exc()
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def launch(
|
| 105 |
+
depth, input_selection, tracking, frame_count, selected, rebuild=False, workers=0
|
| 106 |
+
):
|
| 107 |
+
"""Pre-generate the overlay-frame cache for every scene in ``selected`` that has
|
| 108 |
+
both required dependencies. Returns (succeeded, failed, skipped_missing_deps)
|
| 109 |
+
scene-name lists."""
|
| 110 |
+
eligible, missing = [], []
|
| 111 |
+
for scene in selected:
|
| 112 |
+
if _has_dependencies(scene, depth, input_selection, tracking, frame_count):
|
| 113 |
+
eligible.append(scene)
|
| 114 |
+
else:
|
| 115 |
+
missing.append(scene)
|
| 116 |
+
if missing:
|
| 117 |
+
print(
|
| 118 |
+
f"[overlay-launch] {len(missing)} scene(s) missing a code or SAM3 cache, skipped:"
|
| 119 |
+
)
|
| 120 |
+
print(f" {missing}")
|
| 121 |
+
|
| 122 |
+
if not rebuild:
|
| 123 |
+
pending = []
|
| 124 |
+
for scene in eligible:
|
| 125 |
+
cache_dir = overlay.overlay_frame_cache_dir(
|
| 126 |
+
scene, depth, input_selection, tracking, frame_count
|
| 127 |
+
)
|
| 128 |
+
code_path = overlay.overlay_spatial_code_path(
|
| 129 |
+
scene, depth, input_selection, tracking, frame_count
|
| 130 |
+
)
|
| 131 |
+
if (
|
| 132 |
+
overlay._load_cached_frames(cache_dir, frame_count) is not None
|
| 133 |
+
and code_path.is_file()
|
| 134 |
+
):
|
| 135 |
+
continue
|
| 136 |
+
pending.append(scene)
|
| 137 |
+
skipped = len(eligible) - len(pending)
|
| 138 |
+
if skipped:
|
| 139 |
+
print(f"[overlay-launch] {skipped} scene(s) already cached, skipped")
|
| 140 |
+
else:
|
| 141 |
+
pending = eligible
|
| 142 |
+
|
| 143 |
+
if not pending:
|
| 144 |
+
print(
|
| 145 |
+
f"[overlay-launch] DONE: 0 generated, {len(eligible) - len(pending)} skipped"
|
| 146 |
+
)
|
| 147 |
+
return [], [], missing
|
| 148 |
+
|
| 149 |
+
worker_count = workers if workers > 0 else _available_cpu_count()
|
| 150 |
+
worker_count = min(worker_count, len(pending))
|
| 151 |
+
print(
|
| 152 |
+
f"[overlay-launch] generating {len(pending)} scene(s) with {worker_count} worker(s)"
|
| 153 |
+
)
|
| 154 |
+
tasks = [
|
| 155 |
+
(scene, depth, input_selection, tracking, frame_count) for scene in pending
|
| 156 |
+
]
|
| 157 |
+
with mp.get_context("spawn").Pool(worker_count) as pool:
|
| 158 |
+
results = pool.map(_generate_one, tasks)
|
| 159 |
+
|
| 160 |
+
succeeded = [scene for scene, ok, _ in results if ok]
|
| 161 |
+
failed = [(scene, detail) for scene, ok, detail in results if not ok]
|
| 162 |
+
for scene, detail in failed:
|
| 163 |
+
print(f"[overlay-launch] FAILED {scene}:\n{detail}")
|
| 164 |
+
print(
|
| 165 |
+
f"[overlay-launch] DONE: {len(succeeded)} generated, {len(failed)} failed, "
|
| 166 |
+
f"{len(eligible) - len(pending)} already cached"
|
| 167 |
+
)
|
| 168 |
+
return succeeded, failed, missing
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def main():
|
| 172 |
+
parser = argparse.ArgumentParser()
|
| 173 |
+
parser.add_argument("--depth", required=True)
|
| 174 |
+
parser.add_argument("--tracking", required=True)
|
| 175 |
+
parser.add_argument("--input", required=True, dest="input_selection")
|
| 176 |
+
parser.add_argument("--frames", type=int, required=True)
|
| 177 |
+
parser.add_argument(
|
| 178 |
+
"--scenes", default=None, help="comma-separated scenes (default: all)"
|
| 179 |
+
)
|
| 180 |
+
parser.add_argument("--rebuild", action="store_true")
|
| 181 |
+
parser.add_argument("--workers", type=int, default=0, help="0 = all available CPUs")
|
| 182 |
+
args = parser.parse_args()
|
| 183 |
+
selected = (
|
| 184 |
+
[s.strip() for s in args.scenes.split(",") if s.strip()]
|
| 185 |
+
if args.scenes
|
| 186 |
+
else all_scenes()
|
| 187 |
+
)
|
| 188 |
+
_succeeded, failed, _missing = launch(
|
| 189 |
+
args.depth,
|
| 190 |
+
args.input_selection,
|
| 191 |
+
args.tracking,
|
| 192 |
+
args.frames,
|
| 193 |
+
selected,
|
| 194 |
+
rebuild=args.rebuild,
|
| 195 |
+
workers=args.workers,
|
| 196 |
+
)
|
| 197 |
+
if failed:
|
| 198 |
+
raise SystemExit(1)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
if __name__ == "__main__":
|
| 202 |
+
main()
|
harness/C/run.py
CHANGED
|
@@ -51,9 +51,6 @@ def results_dir_for(
|
|
| 51 |
tracking,
|
| 52 |
input_selection,
|
| 53 |
frame_count,
|
| 54 |
-
spatial_code_source="frames",
|
| 55 |
-
spatial_code_input_selection=DEFAULT_INPUT_SELECTION,
|
| 56 |
-
spatial_code_frame_count=FRAMES_PER_VIDEO,
|
| 57 |
results_dir=None,
|
| 58 |
):
|
| 59 |
"""Return the result root isolated by model + protocol + fixed explicit spatial code +
|
|
@@ -63,9 +60,9 @@ def results_dir_for(
|
|
| 63 |
if results_dir is not None:
|
| 64 |
return Path(results_dir)
|
| 65 |
root = RESULTS_DIR / model / spatial_code_format / depth / tracking
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
return root /
|
| 69 |
|
| 70 |
|
| 71 |
def _build_record(
|
|
@@ -81,22 +78,17 @@ def _build_record(
|
|
| 81 |
"condition": (
|
| 82 |
f"{source_info['protocol']}:{source_info['spatial_code_format']}:"
|
| 83 |
f"{source_info['depth']}:{source_info['tracking']}:"
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
+ ("" if source_info["input_selection"] == "video" else
|
| 90 |
-
f"-{source_info['frame_count']}")
|
| 91 |
),
|
| 92 |
"protocol": source_info["protocol"],
|
| 93 |
"question_group": question_group(row["question_type"]),
|
| 94 |
"spatial_code_format": source_info["spatial_code_format"],
|
| 95 |
"input_selection": source_info["input_selection"],
|
| 96 |
"frame_count": source_info["frame_count"],
|
| 97 |
-
"spatial_code_source": source_info["spatial_code_source"],
|
| 98 |
-
"spatial_code_input_selection": source_info["spatial_code_input_selection"],
|
| 99 |
-
"spatial_code_frame_count": source_info["spatial_code_frame_count"],
|
| 100 |
"depth": source_info["depth"],
|
| 101 |
"tracking": source_info["tracking"],
|
| 102 |
"spatial_code_path": source_info["spatial_code_path"],
|
|
@@ -157,9 +149,6 @@ def write_question_result(
|
|
| 157 |
source_info["tracking"],
|
| 158 |
source_info["input_selection"],
|
| 159 |
source_info["frame_count"],
|
| 160 |
-
source_info["spatial_code_source"],
|
| 161 |
-
source_info["spatial_code_input_selection"],
|
| 162 |
-
source_info["spatial_code_frame_count"],
|
| 163 |
results_dir,
|
| 164 |
)
|
| 165 |
scene_dir = root / record["scene"]
|
|
@@ -176,9 +165,6 @@ def run(
|
|
| 176 |
input_selection=DEFAULT_INPUT_SELECTION,
|
| 177 |
frame_count=FRAMES_PER_VIDEO,
|
| 178 |
video=False,
|
| 179 |
-
spatial_code_source="frames",
|
| 180 |
-
spatial_code_input_selection=DEFAULT_INPUT_SELECTION,
|
| 181 |
-
spatial_code_frame_count=FRAMES_PER_VIDEO,
|
| 182 |
depth=DEFAULT_DEPTH,
|
| 183 |
tracking=DEFAULT_TRACKING,
|
| 184 |
scene=None,
|
|
@@ -214,15 +200,6 @@ def run(
|
|
| 214 |
frame_count = None
|
| 215 |
elif frame_count is None or frame_count < 1:
|
| 216 |
raise ValueError("frame_count must be positive in frames mode")
|
| 217 |
-
if spatial_code_source == "video":
|
| 218 |
-
code_input_selection, code_frame_count = "video", None
|
| 219 |
-
elif spatial_code_source == "frames":
|
| 220 |
-
if spatial_code_frame_count is None or spatial_code_frame_count < 1:
|
| 221 |
-
raise ValueError("spatial_code_frame_count must be positive")
|
| 222 |
-
code_input_selection = spatial_code_input_selection
|
| 223 |
-
code_frame_count = spatial_code_frame_count
|
| 224 |
-
else:
|
| 225 |
-
raise ValueError("spatial_code_source must be frames or video")
|
| 226 |
if spatial_code_format != "explicit":
|
| 227 |
raise ValueError("Harness C supports explicit spatial codes only")
|
| 228 |
protocol = "mixed"
|
|
@@ -234,9 +211,6 @@ def run(
|
|
| 234 |
tracking,
|
| 235 |
input_selection,
|
| 236 |
frame_count,
|
| 237 |
-
spatial_code_source,
|
| 238 |
-
code_input_selection,
|
| 239 |
-
code_frame_count,
|
| 240 |
results_dir,
|
| 241 |
)
|
| 242 |
rows = load_questions(jsonl_path, scene, scenes, limit)
|
|
@@ -267,9 +241,9 @@ def run(
|
|
| 267 |
code, code_path = spatial_codes.load_spatial_code(
|
| 268 |
scene_id,
|
| 269 |
depth,
|
| 270 |
-
|
| 271 |
tracking,
|
| 272 |
-
|
| 273 |
spatial_code_format,
|
| 274 |
)
|
| 275 |
source_cache[scene_id] = {
|
|
@@ -313,9 +287,6 @@ def run(
|
|
| 313 |
"spatial_code_format": spatial_code_format,
|
| 314 |
"input_selection": input_selection,
|
| 315 |
"frame_count": frame_count,
|
| 316 |
-
"spatial_code_source": spatial_code_source,
|
| 317 |
-
"spatial_code_input_selection": code_input_selection,
|
| 318 |
-
"spatial_code_frame_count": code_frame_count,
|
| 319 |
"depth": depth,
|
| 320 |
"tracking": tracking,
|
| 321 |
"spatial_code_path": cached["spatial_code_path"],
|
|
@@ -368,9 +339,6 @@ def main():
|
|
| 368 |
input_mode = parser.add_mutually_exclusive_group(required=True)
|
| 369 |
input_mode.add_argument("--frames", type=int)
|
| 370 |
input_mode.add_argument("--video", action="store_true")
|
| 371 |
-
parser.add_argument("--spatial-code-source", required=True, choices=("frames", "video"))
|
| 372 |
-
parser.add_argument("--spatial-code-input-selection", choices=INPUT_SELECTIONS)
|
| 373 |
-
parser.add_argument("--spatial-code-frames", type=int)
|
| 374 |
parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS)
|
| 375 |
parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES)
|
| 376 |
parser.add_argument(
|
|
@@ -409,14 +377,6 @@ def main():
|
|
| 409 |
parser.error("--input-selection is required with --frames")
|
| 410 |
if args.frames < 1:
|
| 411 |
parser.error("--frames must be positive")
|
| 412 |
-
if args.spatial_code_source == "video":
|
| 413 |
-
if args.spatial_code_input_selection is not None or args.spatial_code_frames is not None:
|
| 414 |
-
parser.error("spatial-code frame flags cannot be used with --spatial-code-source video")
|
| 415 |
-
else:
|
| 416 |
-
if args.spatial_code_input_selection is None or args.spatial_code_frames is None:
|
| 417 |
-
parser.error("--spatial-code-input-selection and --spatial-code-frames are required with --spatial-code-source frames")
|
| 418 |
-
if args.spatial_code_frames < 1:
|
| 419 |
-
parser.error("--spatial-code-frames must be positive")
|
| 420 |
resolve_protocol_budgets(parser, args)
|
| 421 |
results = run(
|
| 422 |
args.model,
|
|
@@ -424,9 +384,6 @@ def main():
|
|
| 424 |
input_selection=args.input_selection,
|
| 425 |
frame_count=args.frames,
|
| 426 |
video=args.video,
|
| 427 |
-
spatial_code_source=args.spatial_code_source,
|
| 428 |
-
spatial_code_input_selection=args.spatial_code_input_selection,
|
| 429 |
-
spatial_code_frame_count=args.spatial_code_frames,
|
| 430 |
depth=args.depth,
|
| 431 |
tracking=args.tracking,
|
| 432 |
scene=args.scene,
|
|
|
|
| 51 |
tracking,
|
| 52 |
input_selection,
|
| 53 |
frame_count,
|
|
|
|
|
|
|
|
|
|
| 54 |
results_dir=None,
|
| 55 |
):
|
| 56 |
"""Return the result root isolated by model + protocol + fixed explicit spatial code +
|
|
|
|
| 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"],
|
|
|
|
|
|
|
|
|
|
| 92 |
"depth": source_info["depth"],
|
| 93 |
"tracking": source_info["tracking"],
|
| 94 |
"spatial_code_path": source_info["spatial_code_path"],
|
|
|
|
| 149 |
source_info["tracking"],
|
| 150 |
source_info["input_selection"],
|
| 151 |
source_info["frame_count"],
|
|
|
|
|
|
|
|
|
|
| 152 |
results_dir,
|
| 153 |
)
|
| 154 |
scene_dir = root / record["scene"]
|
|
|
|
| 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,
|
|
|
|
| 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"
|
|
|
|
| 211 |
tracking,
|
| 212 |
input_selection,
|
| 213 |
frame_count,
|
|
|
|
|
|
|
|
|
|
| 214 |
results_dir,
|
| 215 |
)
|
| 216 |
rows = load_questions(jsonl_path, scene, scenes, limit)
|
|
|
|
| 241 |
code, code_path = spatial_codes.load_spatial_code(
|
| 242 |
scene_id,
|
| 243 |
depth,
|
| 244 |
+
input_selection,
|
| 245 |
tracking,
|
| 246 |
+
frame_count,
|
| 247 |
spatial_code_format,
|
| 248 |
)
|
| 249 |
source_cache[scene_id] = {
|
|
|
|
| 287 |
"spatial_code_format": spatial_code_format,
|
| 288 |
"input_selection": input_selection,
|
| 289 |
"frame_count": frame_count,
|
|
|
|
|
|
|
|
|
|
| 290 |
"depth": depth,
|
| 291 |
"tracking": tracking,
|
| 292 |
"spatial_code_path": cached["spatial_code_path"],
|
|
|
|
| 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(
|
|
|
|
| 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,
|
|
|
|
| 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,
|
harness/C/sweep.py
CHANGED
|
@@ -27,7 +27,6 @@ from harness.A import EXTENDED_MAX_NEW_TOKENS # noqa: E402
|
|
| 27 |
from harness.A.sweep import _parse_csv_choice, _parse_frame_counts # noqa: E402
|
| 28 |
from harness.B import ( # noqa: E402
|
| 29 |
DEFAULT_DEPTH,
|
| 30 |
-
DEFAULT_INPUT_SELECTION,
|
| 31 |
DEFAULT_SPATIAL_CODE_FORMAT,
|
| 32 |
DEFAULT_TRACKING,
|
| 33 |
DEPTH_VARIANTS,
|
|
@@ -38,131 +37,163 @@ from harness.C import launch as harness_launch # noqa: E402
|
|
| 38 |
|
| 39 |
|
| 40 |
def build_plan(
|
| 41 |
-
models, spatial_code_formats, input_selections, frame_counts, depths, trackings
|
| 42 |
-
spatial_code_sources, spatial_code_input_selections, spatial_code_frame_counts,
|
| 43 |
):
|
| 44 |
-
"""Return every
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
if source == "video":
|
| 48 |
-
code_configs.append(("video", "video", None))
|
| 49 |
-
else:
|
| 50 |
-
code_configs.extend(
|
| 51 |
-
("frames", selection, count)
|
| 52 |
-
for count in sorted(spatial_code_frame_counts)
|
| 53 |
-
for selection in spatial_code_input_selections
|
| 54 |
-
)
|
| 55 |
return [
|
| 56 |
-
(model,
|
| 57 |
-
|
| 58 |
-
for count in frame_counts
|
| 59 |
for model in models
|
| 60 |
-
for
|
| 61 |
for depth in depths
|
| 62 |
for tracking in trackings
|
| 63 |
-
for
|
| 64 |
-
for code_source, code_selection, code_count in code_configs
|
| 65 |
]
|
| 66 |
|
| 67 |
|
| 68 |
def sweep(
|
| 69 |
-
models,
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
):
|
| 76 |
-
"""Run every
|
| 77 |
plan = build_plan(
|
| 78 |
-
models, spatial_code_formats, input_selections, frame_counts, depths, trackings
|
| 79 |
-
spatial_code_sources, spatial_code_input_selections, spatial_code_frame_counts,
|
| 80 |
)
|
| 81 |
-
for index,
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
harness_launch.launch(
|
| 89 |
-
model,
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
)
|
| 96 |
|
|
|
|
| 97 |
def main():
|
| 98 |
parser = argparse.ArgumentParser()
|
| 99 |
parser.add_argument("scene", nargs="?")
|
| 100 |
-
parser.add_argument(
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
parser.add_argument(
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
parser.add_argument("--rebuild", action="store_true")
|
| 113 |
-
parser.add_argument(
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
args = parser.parse_args()
|
| 116 |
resolve_protocol_budgets(parser, args)
|
| 117 |
if args.scene and args.scenes:
|
| 118 |
parser.error("positional scene and --scenes cannot be used together")
|
|
|
|
| 119 |
try:
|
| 120 |
-
models = _parse_csv_choice(
|
|
|
|
|
|
|
|
|
|
| 121 |
if args.video:
|
| 122 |
if args.input_selections is not None:
|
| 123 |
raise ValueError("--input-selections cannot be used with --video")
|
| 124 |
-
|
|
|
|
| 125 |
else:
|
| 126 |
if args.input_selections is None:
|
| 127 |
raise ValueError("--input-selections is required with --frames")
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
("frames", "video"),
|
| 133 |
-
"--spatial-code-sources")
|
| 134 |
-
if "frames" in code_sources:
|
| 135 |
-
if (args.spatial_code_input_selections is None or
|
| 136 |
-
args.spatial_code_frames is None):
|
| 137 |
-
raise ValueError("spatial-code selections and frame counts are required "
|
| 138 |
-
"when frame-derived codes are included")
|
| 139 |
-
code_selections = _parse_csv_choice(
|
| 140 |
-
args.spatial_code_input_selections, INPUT_SELECTIONS,
|
| 141 |
-
"--spatial-code-input-selections")
|
| 142 |
-
code_counts = _parse_frame_counts(args.spatial_code_frames)
|
| 143 |
-
else:
|
| 144 |
-
if (args.spatial_code_input_selections is not None or
|
| 145 |
-
args.spatial_code_frames is not None):
|
| 146 |
-
raise ValueError("spatial-code frame flags cannot be used with video-only codes")
|
| 147 |
-
code_selections, code_counts = [], []
|
| 148 |
depths = _parse_csv_choice(args.depths, DEPTH_VARIANTS, "--depths")
|
| 149 |
trackings = _parse_csv_choice(args.trackings, TRACKING_MODES, "--trackings")
|
| 150 |
except ValueError as exc:
|
| 151 |
parser.error(str(exc))
|
|
|
|
| 152 |
if args.scenes is not None:
|
| 153 |
-
selected =
|
| 154 |
if not selected:
|
| 155 |
parser.error("--scenes must contain at least one scene")
|
|
|
|
| 156 |
else:
|
| 157 |
from harness.A.launch import scenes
|
|
|
|
| 158 |
selected = [args.scene] if args.scene else scenes()
|
|
|
|
| 159 |
sweep(
|
| 160 |
-
models,
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
reasoning_budget=args.reasoning_budget,
|
| 167 |
)
|
| 168 |
|
|
|
|
| 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,
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
def build_plan(
|
| 40 |
+
models, spatial_code_formats, input_selections, frame_counts, depths, trackings
|
|
|
|
| 41 |
):
|
| 42 |
+
"""Return every (model, spatial_code_format, depth, tracking, input_selection,
|
| 43 |
+
frame_count) 6-tuple in the sweep, in a stable, cheapest-first-ish order (frame
|
| 44 |
+
count sorted first)."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
return [
|
| 46 |
+
(model, spatial_code_format, depth, tracking, input_selection, frame_count)
|
| 47 |
+
for frame_count in sorted(frame_counts)
|
|
|
|
| 48 |
for model in models
|
| 49 |
+
for spatial_code_format in spatial_code_formats
|
| 50 |
for depth in depths
|
| 51 |
for tracking in trackings
|
| 52 |
+
for input_selection in input_selections
|
|
|
|
| 53 |
]
|
| 54 |
|
| 55 |
|
| 56 |
def sweep(
|
| 57 |
+
models,
|
| 58 |
+
spatial_code_formats,
|
| 59 |
+
input_selections,
|
| 60 |
+
frame_counts,
|
| 61 |
+
selected_scenes,
|
| 62 |
+
video=False,
|
| 63 |
+
depths=(DEFAULT_DEPTH,),
|
| 64 |
+
trackings=(DEFAULT_TRACKING,),
|
| 65 |
+
results_dir=None,
|
| 66 |
+
rebuild=False,
|
| 67 |
+
extended=True,
|
| 68 |
+
reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
|
| 69 |
):
|
| 70 |
+
"""Run every sweep combination across all visible GPUs."""
|
| 71 |
plan = build_plan(
|
| 72 |
+
models, spatial_code_formats, input_selections, frame_counts, depths, trackings
|
|
|
|
| 73 |
)
|
| 74 |
+
for index, (
|
| 75 |
+
model,
|
| 76 |
+
spatial_code_format,
|
| 77 |
+
depth,
|
| 78 |
+
tracking,
|
| 79 |
+
input_selection,
|
| 80 |
+
frame_count,
|
| 81 |
+
) in enumerate(plan, start=1):
|
| 82 |
+
print(
|
| 83 |
+
f"=== sweep {index}/{len(plan)}: {model}/"
|
| 84 |
+
f"{spatial_code_format}/{depth}/{tracking}/"
|
| 85 |
+
+ ("video" if video else f"{input_selection}/{frame_count}")
|
| 86 |
+
+ " ===",
|
| 87 |
+
flush=True,
|
| 88 |
+
)
|
| 89 |
harness_launch.launch(
|
| 90 |
+
model,
|
| 91 |
+
spatial_code_format,
|
| 92 |
+
input_selection,
|
| 93 |
+
frame_count,
|
| 94 |
+
selected_scenes,
|
| 95 |
+
video=video,
|
| 96 |
+
depth=depth,
|
| 97 |
+
tracking=tracking,
|
| 98 |
+
results_dir=results_dir,
|
| 99 |
+
rebuild=rebuild,
|
| 100 |
+
extended=extended,
|
| 101 |
+
reasoning_budget=reasoning_budget,
|
| 102 |
)
|
| 103 |
|
| 104 |
+
|
| 105 |
def main():
|
| 106 |
parser = argparse.ArgumentParser()
|
| 107 |
parser.add_argument("scene", nargs="?")
|
| 108 |
+
parser.add_argument(
|
| 109 |
+
"--scenes",
|
| 110 |
+
help="comma-separated scenes (cannot be combined with positional scene)",
|
| 111 |
+
)
|
| 112 |
+
parser.add_argument(
|
| 113 |
+
"--models",
|
| 114 |
+
required=True,
|
| 115 |
+
help=f"comma-separated models (or 'all'); one of {vlm_models.available_models()}",
|
| 116 |
+
)
|
| 117 |
+
parser.add_argument(
|
| 118 |
+
"--input-selections",
|
| 119 |
+
required=False,
|
| 120 |
+
dest="input_selections",
|
| 121 |
+
help=f"comma-separated selections (or 'all'); one of {INPUT_SELECTIONS}",
|
| 122 |
+
)
|
| 123 |
+
input_mode = parser.add_mutually_exclusive_group(required=True)
|
| 124 |
+
input_mode.add_argument(
|
| 125 |
+
"--frames", help="comma-separated frame counts, e.g. 16,32,64"
|
| 126 |
+
)
|
| 127 |
+
input_mode.add_argument("--video", action="store_true")
|
| 128 |
+
parser.add_argument(
|
| 129 |
+
"--depths",
|
| 130 |
+
default=DEFAULT_DEPTH,
|
| 131 |
+
help=f"comma-separated depths (or 'all'); one of {DEPTH_VARIANTS}",
|
| 132 |
+
)
|
| 133 |
+
parser.add_argument(
|
| 134 |
+
"--trackings",
|
| 135 |
+
default=DEFAULT_TRACKING,
|
| 136 |
+
help=f"comma-separated tracking modes (or 'all'); one of {TRACKING_MODES}",
|
| 137 |
+
)
|
| 138 |
+
parser.add_argument("--results-dir", default=None)
|
| 139 |
parser.add_argument("--rebuild", action="store_true")
|
| 140 |
+
parser.add_argument(
|
| 141 |
+
"--reasoning-budget",
|
| 142 |
+
type=int,
|
| 143 |
+
default=None,
|
| 144 |
+
dest="reasoning_budget",
|
| 145 |
+
help="thinking-protocol first-pass budget (the calibrated value from "
|
| 146 |
+
"preregistration.md, e.g. 512)",
|
| 147 |
+
)
|
| 148 |
args = parser.parse_args()
|
| 149 |
resolve_protocol_budgets(parser, args)
|
| 150 |
if args.scene and args.scenes:
|
| 151 |
parser.error("positional scene and --scenes cannot be used together")
|
| 152 |
+
|
| 153 |
try:
|
| 154 |
+
models = _parse_csv_choice(
|
| 155 |
+
args.models, vlm_models.available_models(), "--models"
|
| 156 |
+
)
|
| 157 |
+
spatial_code_formats = (DEFAULT_SPATIAL_CODE_FORMAT,)
|
| 158 |
if args.video:
|
| 159 |
if args.input_selections is not None:
|
| 160 |
raise ValueError("--input-selections cannot be used with --video")
|
| 161 |
+
input_selections = ["video"]
|
| 162 |
+
frame_counts = [None]
|
| 163 |
else:
|
| 164 |
if args.input_selections is None:
|
| 165 |
raise ValueError("--input-selections is required with --frames")
|
| 166 |
+
input_selections = _parse_csv_choice(
|
| 167 |
+
args.input_selections, INPUT_SELECTIONS, "--input-selections"
|
| 168 |
+
)
|
| 169 |
+
frame_counts = _parse_frame_counts(args.frames)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
depths = _parse_csv_choice(args.depths, DEPTH_VARIANTS, "--depths")
|
| 171 |
trackings = _parse_csv_choice(args.trackings, TRACKING_MODES, "--trackings")
|
| 172 |
except ValueError as exc:
|
| 173 |
parser.error(str(exc))
|
| 174 |
+
|
| 175 |
if args.scenes is not None:
|
| 176 |
+
selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
|
| 177 |
if not selected:
|
| 178 |
parser.error("--scenes must contain at least one scene")
|
| 179 |
+
selected = list(dict.fromkeys(selected))
|
| 180 |
else:
|
| 181 |
from harness.A.launch import scenes
|
| 182 |
+
|
| 183 |
selected = [args.scene] if args.scene else scenes()
|
| 184 |
+
|
| 185 |
sweep(
|
| 186 |
+
models,
|
| 187 |
+
spatial_code_formats,
|
| 188 |
+
input_selections,
|
| 189 |
+
frame_counts,
|
| 190 |
+
selected,
|
| 191 |
+
video=args.video,
|
| 192 |
+
depths=depths,
|
| 193 |
+
trackings=trackings,
|
| 194 |
+
results_dir=args.results_dir,
|
| 195 |
+
rebuild=args.rebuild,
|
| 196 |
+
extended=True,
|
| 197 |
reasoning_budget=args.reasoning_budget,
|
| 198 |
)
|
| 199 |
|
harness/D/__init__.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Harness D: harness.B's spatial-code-as-text routing, but the spatial code is the
|
| 2 |
+
GROUND-TRUTH one (encoder.ground_truth -- built from the dataset's own 3D annotations,
|
| 3 |
+
zero perception error) instead of the SAM3+DA3-perceived one B reads off disk.
|
| 4 |
+
|
| 5 |
+
Ground truth has no depth/tracking/input-selection/frame-count axis at all (it is built
|
| 6 |
+
once per scene directly from annotations, not from any particular video-frame sampling
|
| 7 |
+
run) -- so D only sweeps model x spatial_code_format, both formats, mirroring exactly
|
| 8 |
+
the (model, format) grid harness.B actually swept at its one frozen (selection, frames)
|
| 9 |
+
config. Deliberately NOT narrowed to just B's winning format: ground-truth codes cost
|
| 10 |
+
nothing extra to build across formats (no encoder GPU pass at all), so running both
|
| 11 |
+
formats is free relative to running one, and it is the only way to see whether a
|
| 12 |
+
format's real-vs-perfect-perception ranking flips.
|
| 13 |
+
|
| 14 |
+
Results are written in the identical per-question JSON shape harness.A/B/C use, so D's
|
| 15 |
+
records are directly comparable and drop straight into analysis.aggregate/analysis.compare
|
| 16 |
+
alongside every other harness. harness.D.symbolic_eval additionally answers every
|
| 17 |
+
question with the real symbolic solver run directly against the ground-truth code (no
|
| 18 |
+
VLM at all) -- the perfect-information ceiling -- written through symbolic.run's own
|
| 19 |
+
writer into results/symbolic/ground truth/<format>/, the same results family every
|
| 20 |
+
other symbolic-solver result already lives in, not a separate results/D/... location.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import os
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
from harness.A import (
|
| 29 |
+
DO_SAMPLE,
|
| 30 |
+
JSONL,
|
| 31 |
+
MAX_NEW_TOKENS,
|
| 32 |
+
MODEL_PATHS,
|
| 33 |
+
TEMPERATURE,
|
| 34 |
+
WORKSPACE_ROOT,
|
| 35 |
+
)
|
| 36 |
+
from harness.B import SPATIAL_CODE_FORMATS
|
| 37 |
+
|
| 38 |
+
DEFAULT_SPATIAL_CODE_FORMAT = "explicit"
|
| 39 |
+
|
| 40 |
+
# One JSON per question, matching harness.B's layout minus the axes ground truth doesn't
|
| 41 |
+
# have: results/D/<model>/code/<protocol>/<spatial_code_format>/<scene>/<question_id>.json
|
| 42 |
+
RESULTS_DIR = Path(os.environ.get("VSI_HARNESS_D_RESULTS_DIR", "/root/results/D"))
|
harness/D/launch.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Keep every visible GPU busy with persistent harness-D inference workers.
|
| 2 |
+
|
| 3 |
+
Same shape as ``harness.B.launch``, minus the depth/tracking/input-selection/frame-count
|
| 4 |
+
axes ground truth doesn't have: one persistent worker process per visible GPU, pulling
|
| 5 |
+
scenes off a shared queue, each loading its model exactly once and reusing it for every
|
| 6 |
+
scene it's assigned (via ``run.run(..., adapter=...)``). One invocation covers one
|
| 7 |
+
(model, spatial_code_format) pair across every requested scene; sweep multiple pairs by
|
| 8 |
+
invoking this once per pair (see harness.D.sweep).
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import importlib.util
|
| 15 |
+
import multiprocessing as mp
|
| 16 |
+
import os
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
import sys
|
| 19 |
+
import traceback
|
| 20 |
+
|
| 21 |
+
HERE = Path(__file__).resolve().parent
|
| 22 |
+
WORKSPACE_ROOT = HERE.parent.parent
|
| 23 |
+
if str(WORKSPACE_ROOT) not in sys.path:
|
| 24 |
+
sys.path.insert(0, str(WORKSPACE_ROOT))
|
| 25 |
+
|
| 26 |
+
from encoder.ground_truth import scenes as ground_truth_scenes # noqa: E402
|
| 27 |
+
from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402
|
| 28 |
+
from harness.A import models as vlm_models # noqa: E402
|
| 29 |
+
from harness.B import (
|
| 30 |
+
DEFAULT_INPUT_SELECTION,
|
| 31 |
+
FRAMES_PER_VIDEO,
|
| 32 |
+
INPUT_SELECTIONS,
|
| 33 |
+
) # noqa: E402
|
| 34 |
+
from harness.D import DEFAULT_SPATIAL_CODE_FORMAT, SPATIAL_CODE_FORMATS # noqa: E402
|
| 35 |
+
from inference.launch import available_cpu_count, visible_gpus # noqa: E402
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _load_run_module():
|
| 39 |
+
spec = importlib.util.spec_from_file_location("_harness_D_run", HERE / "run.py")
|
| 40 |
+
module = importlib.util.module_from_spec(spec)
|
| 41 |
+
sys.modules[spec.name] = module
|
| 42 |
+
spec.loader.exec_module(module)
|
| 43 |
+
return module
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _worker(
|
| 47 |
+
tasks,
|
| 48 |
+
results,
|
| 49 |
+
model,
|
| 50 |
+
spatial_code_format,
|
| 51 |
+
results_dir,
|
| 52 |
+
gpu,
|
| 53 |
+
cpu_threads,
|
| 54 |
+
extended,
|
| 55 |
+
reasoning_budget,
|
| 56 |
+
force_budget,
|
| 57 |
+
frames,
|
| 58 |
+
frame_selection,
|
| 59 |
+
frame_count,
|
| 60 |
+
raw_budget,
|
| 61 |
+
thinking,
|
| 62 |
+
):
|
| 63 |
+
if gpu is not None:
|
| 64 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
|
| 65 |
+
for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
|
| 66 |
+
os.environ[variable] = str(cpu_threads)
|
| 67 |
+
run = _load_run_module()
|
| 68 |
+
adapter = None
|
| 69 |
+
load_error = None
|
| 70 |
+
try:
|
| 71 |
+
adapter = vlm_models.get_adapter(model)
|
| 72 |
+
if thinking and not adapter.set_thinking(True):
|
| 73 |
+
raise ValueError(f"{model} has no native thinking mode to enable")
|
| 74 |
+
adapter.load_model("cuda:0" if gpu is not None else "cpu")
|
| 75 |
+
except Exception:
|
| 76 |
+
load_error = traceback.format_exc()
|
| 77 |
+
while True:
|
| 78 |
+
scene = tasks.get()
|
| 79 |
+
if scene is None:
|
| 80 |
+
return
|
| 81 |
+
if load_error is not None:
|
| 82 |
+
results.put((scene, False, load_error))
|
| 83 |
+
continue
|
| 84 |
+
try:
|
| 85 |
+
answered = run.run(
|
| 86 |
+
model,
|
| 87 |
+
spatial_code_format=spatial_code_format,
|
| 88 |
+
scene=scene,
|
| 89 |
+
results_dir=results_dir,
|
| 90 |
+
adapter=adapter,
|
| 91 |
+
extended=extended,
|
| 92 |
+
reasoning_budget=reasoning_budget,
|
| 93 |
+
force_budget=force_budget,
|
| 94 |
+
frames=frames,
|
| 95 |
+
frame_selection=frame_selection,
|
| 96 |
+
frame_count=frame_count,
|
| 97 |
+
raw_budget=raw_budget,
|
| 98 |
+
thinking=thinking,
|
| 99 |
+
)
|
| 100 |
+
mean_score = (
|
| 101 |
+
sum(r["score"] for r in answered) / len(answered) if answered else None
|
| 102 |
+
)
|
| 103 |
+
results.put(
|
| 104 |
+
(scene, True, f"{len(answered)} question(s), mean_score={mean_score}")
|
| 105 |
+
)
|
| 106 |
+
except Exception:
|
| 107 |
+
results.put((scene, False, traceback.format_exc()))
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def launch(
|
| 111 |
+
model,
|
| 112 |
+
spatial_code_format,
|
| 113 |
+
selected,
|
| 114 |
+
results_dir=None,
|
| 115 |
+
rebuild=False,
|
| 116 |
+
extended=True,
|
| 117 |
+
reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
|
| 118 |
+
force_budget=MAX_NEW_TOKENS,
|
| 119 |
+
frames=False,
|
| 120 |
+
frame_selection=DEFAULT_INPUT_SELECTION,
|
| 121 |
+
frame_count=FRAMES_PER_VIDEO,
|
| 122 |
+
raw_budget=None,
|
| 123 |
+
thinking=False,
|
| 124 |
+
):
|
| 125 |
+
"""Answer every question for ``selected`` scenes, sharded across every visible GPU.
|
| 126 |
+
|
| 127 |
+
``raw_budget`` (mutually exclusive with ``extended``) runs the raw-budget arm:
|
| 128 |
+
base-protocol mechanics at this token cap, under its own truncated/<budget> path
|
| 129 |
+
segment -- see harness.D.run.run."""
|
| 130 |
+
if extended and raw_budget is not None:
|
| 131 |
+
raise ValueError("extended and raw_budget are mutually exclusive")
|
| 132 |
+
protocol = (
|
| 133 |
+
f"{reasoning_budget}"
|
| 134 |
+
if extended
|
| 135 |
+
else f"truncated/{raw_budget}" if raw_budget is not None else "base"
|
| 136 |
+
)
|
| 137 |
+
condition = f"{model}/{protocol}/{spatial_code_format}"
|
| 138 |
+
if frames:
|
| 139 |
+
condition += f"/frames/{frame_selection}/{frame_count}"
|
| 140 |
+
run = _load_run_module()
|
| 141 |
+
root = run.results_dir_for(
|
| 142 |
+
model,
|
| 143 |
+
protocol,
|
| 144 |
+
spatial_code_format,
|
| 145 |
+
results_dir,
|
| 146 |
+
frames=frames,
|
| 147 |
+
frame_selection=frame_selection,
|
| 148 |
+
frame_count=frame_count,
|
| 149 |
+
)
|
| 150 |
+
pending = []
|
| 151 |
+
completed = 0
|
| 152 |
+
for scene in selected:
|
| 153 |
+
rows = run.load_questions(scene=scene)
|
| 154 |
+
if not rows:
|
| 155 |
+
raise ValueError(
|
| 156 |
+
f"no questions found for scene {scene!r}; check the manifest/scene selection"
|
| 157 |
+
)
|
| 158 |
+
answered = all((root / scene / f"{row['id']}.json").is_file() for row in rows)
|
| 159 |
+
if answered and not rebuild:
|
| 160 |
+
completed += 1
|
| 161 |
+
print(
|
| 162 |
+
f"[{condition} {completed}/{len(selected)}] {scene}: skipped",
|
| 163 |
+
flush=True,
|
| 164 |
+
)
|
| 165 |
+
else:
|
| 166 |
+
pending.append(scene)
|
| 167 |
+
if not pending:
|
| 168 |
+
print(f"[{condition}] DONE: {len(selected)} ok, 0 failed")
|
| 169 |
+
return
|
| 170 |
+
|
| 171 |
+
gpus = visible_gpus()
|
| 172 |
+
worker_count = min(len(pending), len(gpus) if gpus else 1)
|
| 173 |
+
assignments = gpus[:worker_count] if gpus else [None]
|
| 174 |
+
cpu_count = available_cpu_count()
|
| 175 |
+
cpu_threads = max(1, cpu_count // worker_count)
|
| 176 |
+
print(
|
| 177 |
+
f"[{condition}] starting {worker_count} persistent worker(s); "
|
| 178 |
+
f"GPUs={assignments}; CPU threads/worker={cpu_threads}",
|
| 179 |
+
flush=True,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
context = mp.get_context("spawn")
|
| 183 |
+
tasks, results = context.Queue(), context.Queue()
|
| 184 |
+
for scene in pending:
|
| 185 |
+
tasks.put(scene)
|
| 186 |
+
for _ in range(worker_count):
|
| 187 |
+
tasks.put(None)
|
| 188 |
+
workers = [
|
| 189 |
+
context.Process(
|
| 190 |
+
target=_worker,
|
| 191 |
+
args=(
|
| 192 |
+
tasks,
|
| 193 |
+
results,
|
| 194 |
+
model,
|
| 195 |
+
spatial_code_format,
|
| 196 |
+
results_dir,
|
| 197 |
+
gpu,
|
| 198 |
+
cpu_threads,
|
| 199 |
+
extended,
|
| 200 |
+
reasoning_budget,
|
| 201 |
+
force_budget,
|
| 202 |
+
frames,
|
| 203 |
+
frame_selection,
|
| 204 |
+
frame_count,
|
| 205 |
+
raw_budget,
|
| 206 |
+
thinking,
|
| 207 |
+
),
|
| 208 |
+
)
|
| 209 |
+
for gpu in assignments
|
| 210 |
+
]
|
| 211 |
+
for worker in workers:
|
| 212 |
+
worker.start()
|
| 213 |
+
failed = []
|
| 214 |
+
for finished in range(1, len(pending) + 1):
|
| 215 |
+
scene, ok, detail = results.get()
|
| 216 |
+
if not ok:
|
| 217 |
+
failed.append(scene)
|
| 218 |
+
print(
|
| 219 |
+
f"[{condition} {completed + finished}/{len(selected)}] {scene}: "
|
| 220 |
+
f"{'done' if ok else 'FAILED'}\n{detail}",
|
| 221 |
+
flush=True,
|
| 222 |
+
)
|
| 223 |
+
for worker in workers:
|
| 224 |
+
worker.join()
|
| 225 |
+
print(
|
| 226 |
+
f"[{condition}] DONE: {len(pending) - len(failed)} answered, {completed} skipped, "
|
| 227 |
+
f"{len(failed)} failed"
|
| 228 |
+
)
|
| 229 |
+
if failed:
|
| 230 |
+
raise SystemExit(1)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def scenes():
|
| 234 |
+
"""Every scene that both has a real VSI-Bench question AND ground-truth annotation
|
| 235 |
+
coverage -- i.e. every scene harness.A/B/C could ever be run on (all of them have GT,
|
| 236 |
+
since encoder.ground_truth covers the full 288-scene meta_info set, a superset of any
|
| 237 |
+
perception-built spatial code's coverage)."""
|
| 238 |
+
from harness.A.launch import scenes as vsi_scenes
|
| 239 |
+
|
| 240 |
+
ground_truth = set(ground_truth_scenes())
|
| 241 |
+
return [scene for scene in vsi_scenes() if scene in ground_truth]
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def main():
|
| 245 |
+
parser = argparse.ArgumentParser()
|
| 246 |
+
parser.add_argument("scene", nargs="?")
|
| 247 |
+
parser.add_argument(
|
| 248 |
+
"--scenes",
|
| 249 |
+
help="comma-separated scenes (cannot be combined with positional scene)",
|
| 250 |
+
)
|
| 251 |
+
parser.add_argument("--model", required=True, choices=vlm_models.available_models())
|
| 252 |
+
parser.add_argument(
|
| 253 |
+
"--spatial-code-format",
|
| 254 |
+
default=DEFAULT_SPATIAL_CODE_FORMAT,
|
| 255 |
+
choices=SPATIAL_CODE_FORMATS,
|
| 256 |
+
dest="spatial_code_format",
|
| 257 |
+
)
|
| 258 |
+
parser.add_argument("--results-dir", default=None)
|
| 259 |
+
parser.add_argument("--rebuild", action="store_true")
|
| 260 |
+
parser.add_argument(
|
| 261 |
+
"--base-protocol",
|
| 262 |
+
action="store_true",
|
| 263 |
+
help="run harness.A's exact fixed 16-token protocol instead of the extended default",
|
| 264 |
+
)
|
| 265 |
+
parser.add_argument(
|
| 266 |
+
"--with-frames",
|
| 267 |
+
action="store_true",
|
| 268 |
+
dest="frames",
|
| 269 |
+
help="frames+ground-truth-code arm: also sample and show the scene's raw video "
|
| 270 |
+
"frames alongside the ground-truth code (default sampling: uniform, 32 frames -- "
|
| 271 |
+
"the frozen Step-1 config)",
|
| 272 |
+
)
|
| 273 |
+
parser.add_argument(
|
| 274 |
+
"--frame-selection",
|
| 275 |
+
default=DEFAULT_INPUT_SELECTION,
|
| 276 |
+
choices=INPUT_SELECTIONS,
|
| 277 |
+
dest="frame_selection",
|
| 278 |
+
help="only used with --with-frames",
|
| 279 |
+
)
|
| 280 |
+
parser.add_argument(
|
| 281 |
+
"--frames-per-video",
|
| 282 |
+
type=int,
|
| 283 |
+
default=FRAMES_PER_VIDEO,
|
| 284 |
+
dest="frame_count",
|
| 285 |
+
help="only used with --with-frames",
|
| 286 |
+
)
|
| 287 |
+
parser.add_argument(
|
| 288 |
+
"--thinking",
|
| 289 |
+
action="store_true",
|
| 290 |
+
help="enable the model's native thinking mode where supported; errors on models without the switch",
|
| 291 |
+
)
|
| 292 |
+
parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
|
| 293 |
+
parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
|
| 294 |
+
parser.add_argument(
|
| 295 |
+
"--truncated-budget",
|
| 296 |
+
type=int,
|
| 297 |
+
default=None,
|
| 298 |
+
help="raw-budget arm: base-protocol mechanics (single generation, no forced "
|
| 299 |
+
"rescue) at this token cap instead of the hardcoded 16 (mutually exclusive "
|
| 300 |
+
"with --base-protocol)",
|
| 301 |
+
)
|
| 302 |
+
args = parser.parse_args()
|
| 303 |
+
if args.scene and args.scenes:
|
| 304 |
+
parser.error("positional scene and --scenes cannot be used together")
|
| 305 |
+
if args.scenes is not None:
|
| 306 |
+
selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
|
| 307 |
+
if not selected:
|
| 308 |
+
parser.error("--scenes must contain at least one scene")
|
| 309 |
+
selected = list(dict.fromkeys(selected))
|
| 310 |
+
else:
|
| 311 |
+
selected = [args.scene] if args.scene else scenes()
|
| 312 |
+
if args.reasoning_budget < 1:
|
| 313 |
+
parser.error("--reasoning-budget must be positive")
|
| 314 |
+
if args.force_budget < 1:
|
| 315 |
+
parser.error("--force-budget must be positive")
|
| 316 |
+
if args.frame_count < 1:
|
| 317 |
+
parser.error("--frames-per-video must be positive")
|
| 318 |
+
if args.truncated_budget is not None and args.truncated_budget < 1:
|
| 319 |
+
parser.error("--truncated-budget must be positive")
|
| 320 |
+
if args.base_protocol and args.truncated_budget is not None:
|
| 321 |
+
parser.error("--base-protocol and --truncated-budget are mutually exclusive")
|
| 322 |
+
launch(
|
| 323 |
+
args.model,
|
| 324 |
+
args.spatial_code_format,
|
| 325 |
+
selected,
|
| 326 |
+
results_dir=args.results_dir,
|
| 327 |
+
rebuild=args.rebuild,
|
| 328 |
+
extended=not args.base_protocol and args.truncated_budget is None,
|
| 329 |
+
frames=args.frames,
|
| 330 |
+
frame_selection=args.frame_selection,
|
| 331 |
+
frame_count=args.frame_count,
|
| 332 |
+
thinking=args.thinking,
|
| 333 |
+
reasoning_budget=args.reasoning_budget,
|
| 334 |
+
force_budget=args.force_budget,
|
| 335 |
+
raw_budget=args.truncated_budget,
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
if __name__ == "__main__":
|
| 340 |
+
main()
|
harness/D/prompts.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Ground-truth spatial-code prompt construction.
|
| 2 |
+
|
| 3 |
+
Ground-truth and perceived code use the same v2 prompt text; only the loaded code file
|
| 4 |
+
differs.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from harness.B.prompts import build_prompt
|
harness/D/run.py
ADDED
|
@@ -0,0 +1,457 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run one VLM over VSI-Bench questions through harness D's ground-truth-spatial-code-
|
| 2 |
+
as-text routing.
|
| 3 |
+
|
| 4 |
+
Writes one JSON file per question in the identical shape harness.A/B/C use -- the
|
| 5 |
+
frame-provenance fields are replaced with spatial-code provenance fields
|
| 6 |
+
(spatial_code_format, spatial_code_path), since D has no video frames and no depth/
|
| 7 |
+
tracking/input-selection/frame-count axis at all (ground truth is built once per scene
|
| 8 |
+
straight from dataset annotations). Scoring reuses the same real, unmodified official
|
| 9 |
+
scorer every harness uses.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import json
|
| 16 |
+
import sys
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent
|
| 20 |
+
if str(WORKSPACE_ROOT) not in sys.path:
|
| 21 |
+
sys.path.insert(0, str(WORKSPACE_ROOT))
|
| 22 |
+
|
| 23 |
+
import inference as inference_config # noqa: E402
|
| 24 |
+
from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402
|
| 25 |
+
from harness.A import frames as frame_sampling # noqa: E402
|
| 26 |
+
from harness.A import models as vlm_models # noqa: E402
|
| 27 |
+
from harness.A.run import _scalar_score, load_questions, vsi_official_eval # noqa: E402
|
| 28 |
+
from harness.B import (
|
| 29 |
+
DEFAULT_INPUT_SELECTION,
|
| 30 |
+
FRAMES_PER_VIDEO,
|
| 31 |
+
INPUT_SELECTIONS,
|
| 32 |
+
) # noqa: E402
|
| 33 |
+
from harness.C import prompts as combined_prompts # noqa: E402
|
| 34 |
+
from harness.D import (
|
| 35 |
+
DEFAULT_SPATIAL_CODE_FORMAT,
|
| 36 |
+
RESULTS_DIR,
|
| 37 |
+
SPATIAL_CODE_FORMATS,
|
| 38 |
+
) # noqa: E402
|
| 39 |
+
from harness.D import prompts as code_prompts # noqa: E402
|
| 40 |
+
from harness.D import spatial_codes # noqa: E402
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def results_dir_for(
|
| 44 |
+
model,
|
| 45 |
+
protocol,
|
| 46 |
+
spatial_code_format,
|
| 47 |
+
results_dir=None,
|
| 48 |
+
frames=False,
|
| 49 |
+
frame_selection=DEFAULT_INPUT_SELECTION,
|
| 50 |
+
frame_count=FRAMES_PER_VIDEO,
|
| 51 |
+
):
|
| 52 |
+
"""Return the result root isolated by model + protocol + spatial-code-format.
|
| 53 |
+
``protocol`` is "base" (16-token) or "<reasoning budget>" (e.g. "512") -- a real path segment, so records from different protocols OR
|
| 54 |
+
different reasoning budgets can never collide on disk.
|
| 55 |
+
|
| 56 |
+
``frames=True`` (the frames+ground-truth-code arm) selects the sibling
|
| 57 |
+
"code + frames" branch and appends "<selection>/<count>" -- video frames have no bearing on which ground-truth
|
| 58 |
+
code gets loaded (ground truth has no depth/tracking/input-selection axis at all;
|
| 59 |
+
see harness/D/__init__.py), but they DO change what the model sees, so this arm's
|
| 60 |
+
records must never share a path with the text-only condition's."""
|
| 61 |
+
if results_dir is not None:
|
| 62 |
+
return Path(results_dir)
|
| 63 |
+
root = (
|
| 64 |
+
RESULTS_DIR
|
| 65 |
+
/ model
|
| 66 |
+
/ ("code + frames" if frames else "code")
|
| 67 |
+
/ protocol
|
| 68 |
+
/ spatial_code_format
|
| 69 |
+
)
|
| 70 |
+
if frames:
|
| 71 |
+
root = root / frame_selection / str(frame_count)
|
| 72 |
+
return root
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _build_record(
|
| 76 |
+
row, prompt, answer, metric_name, score, model, model_path, code_info
|
| 77 |
+
):
|
| 78 |
+
"""Assemble one question's full, untruncated result record (nothing summarized).
|
| 79 |
+
|
| 80 |
+
``code_info`` carries frame provenance (``video_path``, ``frame_indices``,
|
| 81 |
+
``frame_timestamps``) only for the frames+ground-truth-code arm; all three are None
|
| 82 |
+
on the standard text-only condition, matching how harness.A/B/D's other optional
|
| 83 |
+
fields (``reasoning_text`` etc.) are present-but-null rather than absent."""
|
| 84 |
+
condition = f"{code_info['protocol']}:{code_info['spatial_code_format']}"
|
| 85 |
+
if code_info.get("frames"):
|
| 86 |
+
condition += (
|
| 87 |
+
f":frames:{code_info['frame_selection']}:{code_info['frame_count']}"
|
| 88 |
+
)
|
| 89 |
+
return {
|
| 90 |
+
"model": model,
|
| 91 |
+
"model_path": str(model_path),
|
| 92 |
+
"device": answer["device"],
|
| 93 |
+
"dtype": answer["dtype"],
|
| 94 |
+
"library_versions": answer["library_versions"],
|
| 95 |
+
"condition": condition,
|
| 96 |
+
"protocol": code_info["protocol"],
|
| 97 |
+
"spatial_code_format": code_info["spatial_code_format"],
|
| 98 |
+
"spatial_code_path": code_info["spatial_code_path"],
|
| 99 |
+
"frames": code_info.get("frames", False),
|
| 100 |
+
"frame_selection": code_info.get("frame_selection"),
|
| 101 |
+
"frame_count": code_info.get("frame_count"),
|
| 102 |
+
"video_path": code_info.get("video_path"),
|
| 103 |
+
"frame_indices": code_info.get("frame_indices"),
|
| 104 |
+
"frame_timestamps_seconds": code_info.get("frame_timestamps"),
|
| 105 |
+
"scene": row["scene_name"],
|
| 106 |
+
"dataset": row.get("dataset"),
|
| 107 |
+
"question_id": row["id"],
|
| 108 |
+
"question_type": row["question_type"],
|
| 109 |
+
"question": row["question"],
|
| 110 |
+
"options": row.get("options"),
|
| 111 |
+
"full_prompt": prompt,
|
| 112 |
+
"rendered_prompt": answer["prompt_text"],
|
| 113 |
+
"answer_expected": row["ground_truth"],
|
| 114 |
+
"answer_given": answer["answer_text"],
|
| 115 |
+
"answer_raw": answer["answer_raw"],
|
| 116 |
+
"input_token_count": answer["input_token_count"],
|
| 117 |
+
"vision_input_shapes": answer["vision_input_shapes"],
|
| 118 |
+
"output_token_ids": answer["output_token_ids"],
|
| 119 |
+
"output_token_count": answer["output_token_count"],
|
| 120 |
+
"hit_token_limit": answer["hit_token_limit"],
|
| 121 |
+
"eos_token_ids": answer["eos_token_ids"],
|
| 122 |
+
"generation_seconds": answer["generation_seconds"],
|
| 123 |
+
"generation_config": answer["generation_config"],
|
| 124 |
+
"reasoning_text": answer.get("reasoning_text"),
|
| 125 |
+
"reasoning_raw": answer.get("reasoning_raw"),
|
| 126 |
+
"reasoning_token_ids": answer.get("reasoning_token_ids"),
|
| 127 |
+
"reasoning_token_count": answer.get("reasoning_token_count"),
|
| 128 |
+
"reasoning_hit_limit": answer.get("reasoning_hit_limit"),
|
| 129 |
+
"forced": answer.get("forced", False),
|
| 130 |
+
"forced_input_token_count": answer.get("forced_input_token_count"),
|
| 131 |
+
"metric": metric_name,
|
| 132 |
+
"score": score,
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def write_question_result(
|
| 137 |
+
row,
|
| 138 |
+
prompt,
|
| 139 |
+
answer,
|
| 140 |
+
metric_name,
|
| 141 |
+
score,
|
| 142 |
+
model,
|
| 143 |
+
model_path,
|
| 144 |
+
code_info,
|
| 145 |
+
results_dir=None,
|
| 146 |
+
):
|
| 147 |
+
"""Write one question's full, untruncated result record. Return (path, record)."""
|
| 148 |
+
record = _build_record(
|
| 149 |
+
row, prompt, answer, metric_name, score, model, model_path, code_info
|
| 150 |
+
)
|
| 151 |
+
root = results_dir_for(
|
| 152 |
+
model,
|
| 153 |
+
code_info["protocol"],
|
| 154 |
+
code_info["spatial_code_format"],
|
| 155 |
+
results_dir,
|
| 156 |
+
frames=code_info.get("frames", False),
|
| 157 |
+
frame_selection=code_info.get("frame_selection", DEFAULT_INPUT_SELECTION),
|
| 158 |
+
frame_count=code_info.get("frame_count", FRAMES_PER_VIDEO),
|
| 159 |
+
)
|
| 160 |
+
scene_dir = root / record["scene"]
|
| 161 |
+
scene_dir.mkdir(parents=True, exist_ok=True)
|
| 162 |
+
path = scene_dir / f"{row['id']}.json"
|
| 163 |
+
with path.open("w", encoding="utf-8") as stream:
|
| 164 |
+
json.dump(record, stream, indent=1)
|
| 165 |
+
return path, record
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def run(
|
| 169 |
+
model,
|
| 170 |
+
spatial_code_format=DEFAULT_SPATIAL_CODE_FORMAT,
|
| 171 |
+
scene=None,
|
| 172 |
+
scenes=None,
|
| 173 |
+
limit=None,
|
| 174 |
+
device="cuda",
|
| 175 |
+
jsonl_path=None,
|
| 176 |
+
results_dir=None,
|
| 177 |
+
write_results=True,
|
| 178 |
+
adapter=None,
|
| 179 |
+
thinking=False,
|
| 180 |
+
extended=True,
|
| 181 |
+
reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
|
| 182 |
+
force_budget=MAX_NEW_TOKENS,
|
| 183 |
+
code_transform=None,
|
| 184 |
+
frames=False,
|
| 185 |
+
frame_selection=DEFAULT_INPUT_SELECTION,
|
| 186 |
+
frame_count=FRAMES_PER_VIDEO,
|
| 187 |
+
raw_budget=None,
|
| 188 |
+
):
|
| 189 |
+
"""Answer every matching question with one model, given its scene's GROUND-TRUTH
|
| 190 |
+
spatial code as text. Each question's full record is written to its own JSON file
|
| 191 |
+
as soon as it is answered (unless ``write_results=False``).
|
| 192 |
+
|
| 193 |
+
``frames=True`` runs the frames+ground-truth-code arm: the scene's raw video is
|
| 194 |
+
ALSO sampled (``frame_selection``/``frame_count``, harness.A.frames.sample_frames --
|
| 195 |
+
the same sampling every harness uses; ground truth has no depth/tracking axis for
|
| 196 |
+
frames to be sourced "from", so there is nothing for this to mismatch against) and
|
| 197 |
+
shown alongside the ground-truth code, with harness.C's frames+code context line
|
| 198 |
+
(byte-identical composition rule: harness.A's frame sentence + harness.B's code
|
| 199 |
+
sentence, the same CODE_DESCRIPTION D's own text-only line already uses). This is
|
| 200 |
+
the ground-truth counterpart of harness C -- C answers with frames + a PERCEIVED
|
| 201 |
+
code; this is frames + the PERFECT code -- which harness C itself cannot produce,
|
| 202 |
+
since its spatial-code loader is perception-only. The default ``frame_selection``/
|
| 203 |
+
``frame_count`` match the frozen Step-1 config (uniform, 32) so a default frames=True
|
| 204 |
+
call needs no extra flags to land on the same sampling every other harness uses.
|
| 205 |
+
|
| 206 |
+
Uses ``adapter.answer_extended`` as the standing default protocol, same as
|
| 207 |
+
harness.B -- working through a full spatial-code JSON before answering benefits
|
| 208 |
+
from more room than a short visual caption does. ``extended=False`` runs
|
| 209 |
+
harness.A's exact fixed 16-token base protocol instead (plain ``adapter.answer``).
|
| 210 |
+
|
| 211 |
+
``raw_budget`` (mutually exclusive with ``extended``) runs the raw-budget arm --
|
| 212 |
+
same mechanism as ``extended=False`` (single generation, no forced rescue) but at
|
| 213 |
+
this token cap instead of the hardcoded 16, under its own "truncated/<budget>"
|
| 214 |
+
protocol path segment (mirrors harness.B/C's identical arm) so it can never collide
|
| 215 |
+
with either the extended or the base-protocol condition on disk.
|
| 216 |
+
|
| 217 |
+
``code_transform``, when given, is called as ``code_transform(code, scene_id,
|
| 218 |
+
spatial_code_format)`` on each freshly loaded code and its return value is what
|
| 219 |
+
the prompt is built from -- the hook the corruption module (README Theme 8) uses
|
| 220 |
+
to run corrupted codes through this EXACT prompt/adapter path instead of a
|
| 221 |
+
duplicated one. ``None`` (the default) leaves behavior byte-identical to before.
|
| 222 |
+
|
| 223 |
+
Pass a pre-loaded ``adapter`` (as harness.D.launch's persistent per-GPU workers do)
|
| 224 |
+
to reuse one already-loaded model across many calls; the caller then owns unloading
|
| 225 |
+
it. Without one, ``run`` loads and unloads its own adapter, same as harness.A/B.
|
| 226 |
+
"""
|
| 227 |
+
if extended and raw_budget is not None:
|
| 228 |
+
raise ValueError("extended and raw_budget are mutually exclusive")
|
| 229 |
+
rows = load_questions(jsonl_path, scene, scenes, limit)
|
| 230 |
+
if not rows:
|
| 231 |
+
return []
|
| 232 |
+
owns_adapter = adapter is None
|
| 233 |
+
if owns_adapter:
|
| 234 |
+
adapter = vlm_models.get_adapter(model)
|
| 235 |
+
if thinking and not adapter.set_thinking(True):
|
| 236 |
+
raise ValueError(f"{model} has no native thinking mode to enable")
|
| 237 |
+
adapter.load_model(device)
|
| 238 |
+
code_cache = {}
|
| 239 |
+
results = []
|
| 240 |
+
try:
|
| 241 |
+
for row in rows:
|
| 242 |
+
scene_id = row["scene_name"]
|
| 243 |
+
if scene_id not in code_cache:
|
| 244 |
+
code, path = spatial_codes.load_spatial_code(
|
| 245 |
+
scene_id, spatial_code_format
|
| 246 |
+
)
|
| 247 |
+
if code_transform is not None:
|
| 248 |
+
code = code_transform(code, scene_id, spatial_code_format)
|
| 249 |
+
entry = {"code": code, "path": path}
|
| 250 |
+
if frames:
|
| 251 |
+
video_path = inference_config.video_path(
|
| 252 |
+
scene_id, row.get("dataset")
|
| 253 |
+
)
|
| 254 |
+
frame_images, frame_timestamps, frame_indices = (
|
| 255 |
+
frame_sampling.sample_frames(
|
| 256 |
+
video_path, frame_count, frame_selection
|
| 257 |
+
)
|
| 258 |
+
)
|
| 259 |
+
entry.update(
|
| 260 |
+
video_path=video_path,
|
| 261 |
+
frame_images=frame_images,
|
| 262 |
+
frame_timestamps=frame_timestamps,
|
| 263 |
+
frame_indices=frame_indices,
|
| 264 |
+
)
|
| 265 |
+
code_cache[scene_id] = entry
|
| 266 |
+
cached = code_cache[scene_id]
|
| 267 |
+
prompt_builder = combined_prompts.build_prompt if frames else code_prompts.build_prompt
|
| 268 |
+
prompt = prompt_builder(
|
| 269 |
+
cached["code"],
|
| 270 |
+
row["question_type"],
|
| 271 |
+
row["question"],
|
| 272 |
+
row.get("options"),
|
| 273 |
+
)
|
| 274 |
+
answer = (
|
| 275 |
+
adapter.answer_extended(
|
| 276 |
+
cached["frame_images"] if frames else [],
|
| 277 |
+
prompt,
|
| 278 |
+
reasoning_budget=reasoning_budget,
|
| 279 |
+
force_budget=force_budget,
|
| 280 |
+
)
|
| 281 |
+
if extended
|
| 282 |
+
else adapter.answer(
|
| 283 |
+
cached["frame_images"] if frames else [],
|
| 284 |
+
prompt,
|
| 285 |
+
max_new_tokens=raw_budget,
|
| 286 |
+
)
|
| 287 |
+
)
|
| 288 |
+
doc = {
|
| 289 |
+
"question_type": row["question_type"],
|
| 290 |
+
"ground_truth": row["ground_truth"],
|
| 291 |
+
}
|
| 292 |
+
score_doc = vsi_official_eval.vsibench_process_results(
|
| 293 |
+
doc, [answer["answer_text"]]
|
| 294 |
+
)["vsibench_score"]
|
| 295 |
+
metric_name, score = _scalar_score(row["question_type"], score_doc)
|
| 296 |
+
code_info = {
|
| 297 |
+
"protocol": (
|
| 298 |
+
f"{reasoning_budget}"
|
| 299 |
+
if extended
|
| 300 |
+
else f"truncated/{raw_budget}" if raw_budget is not None else "base"
|
| 301 |
+
),
|
| 302 |
+
"spatial_code_format": spatial_code_format,
|
| 303 |
+
"spatial_code_path": cached["path"],
|
| 304 |
+
"frames": frames,
|
| 305 |
+
"frame_selection": frame_selection if frames else None,
|
| 306 |
+
"frame_count": frame_count if frames else None,
|
| 307 |
+
"video_path": cached.get("video_path"),
|
| 308 |
+
"frame_indices": cached.get("frame_indices"),
|
| 309 |
+
"frame_timestamps": cached.get("frame_timestamps"),
|
| 310 |
+
}
|
| 311 |
+
if write_results:
|
| 312 |
+
path, record = write_question_result(
|
| 313 |
+
row,
|
| 314 |
+
prompt,
|
| 315 |
+
answer,
|
| 316 |
+
metric_name,
|
| 317 |
+
score,
|
| 318 |
+
model,
|
| 319 |
+
adapter.model_path,
|
| 320 |
+
code_info,
|
| 321 |
+
results_dir,
|
| 322 |
+
)
|
| 323 |
+
else:
|
| 324 |
+
path = None
|
| 325 |
+
record = _build_record(
|
| 326 |
+
row,
|
| 327 |
+
prompt,
|
| 328 |
+
answer,
|
| 329 |
+
metric_name,
|
| 330 |
+
score,
|
| 331 |
+
model,
|
| 332 |
+
adapter.model_path,
|
| 333 |
+
code_info,
|
| 334 |
+
)
|
| 335 |
+
record["result_path"] = str(path) if path else None
|
| 336 |
+
results.append(record)
|
| 337 |
+
finally:
|
| 338 |
+
if owns_adapter:
|
| 339 |
+
adapter.unload()
|
| 340 |
+
return results
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def main():
|
| 344 |
+
parser = argparse.ArgumentParser()
|
| 345 |
+
parser.add_argument("--model", required=True, choices=vlm_models.available_models())
|
| 346 |
+
parser.add_argument("--scene", default=None, help="restrict to one VSI-Bench scene")
|
| 347 |
+
parser.add_argument(
|
| 348 |
+
"--spatial-code-format",
|
| 349 |
+
default=DEFAULT_SPATIAL_CODE_FORMAT,
|
| 350 |
+
choices=SPATIAL_CODE_FORMATS,
|
| 351 |
+
dest="spatial_code_format",
|
| 352 |
+
)
|
| 353 |
+
parser.add_argument(
|
| 354 |
+
"--limit", type=int, default=None, help="cap the number of questions"
|
| 355 |
+
)
|
| 356 |
+
parser.add_argument("--device", default="cuda")
|
| 357 |
+
parser.add_argument(
|
| 358 |
+
"--results-dir",
|
| 359 |
+
default=None,
|
| 360 |
+
help="override the default results/D/<model>/<code or code + frames>/<protocol>/<format> root",
|
| 361 |
+
)
|
| 362 |
+
parser.add_argument(
|
| 363 |
+
"--no-write",
|
| 364 |
+
action="store_true",
|
| 365 |
+
help="skip writing per-question JSON files; print/score only",
|
| 366 |
+
)
|
| 367 |
+
parser.add_argument(
|
| 368 |
+
"--base-protocol",
|
| 369 |
+
action="store_true",
|
| 370 |
+
help="run harness.A's exact fixed 16-token protocol (plain answer()) instead of "
|
| 371 |
+
"the extended 2048-token default",
|
| 372 |
+
)
|
| 373 |
+
parser.add_argument(
|
| 374 |
+
"--with-frames",
|
| 375 |
+
action="store_true",
|
| 376 |
+
dest="frames",
|
| 377 |
+
help="frames+ground-truth-code arm: also sample and show the scene's raw video "
|
| 378 |
+
"frames alongside the ground-truth code (default sampling: uniform, 32 frames -- "
|
| 379 |
+
"the frozen Step-1 config)",
|
| 380 |
+
)
|
| 381 |
+
parser.add_argument(
|
| 382 |
+
"--frame-selection",
|
| 383 |
+
default=DEFAULT_INPUT_SELECTION,
|
| 384 |
+
choices=INPUT_SELECTIONS,
|
| 385 |
+
dest="frame_selection",
|
| 386 |
+
help="only used with --with-frames",
|
| 387 |
+
)
|
| 388 |
+
parser.add_argument(
|
| 389 |
+
"--frames-per-video",
|
| 390 |
+
type=int,
|
| 391 |
+
default=FRAMES_PER_VIDEO,
|
| 392 |
+
dest="frame_count",
|
| 393 |
+
help="only used with --with-frames",
|
| 394 |
+
)
|
| 395 |
+
parser.add_argument(
|
| 396 |
+
"--thinking",
|
| 397 |
+
action="store_true",
|
| 398 |
+
help="enable the model's native thinking mode where supported; errors on models without the switch",
|
| 399 |
+
)
|
| 400 |
+
parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
|
| 401 |
+
parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
|
| 402 |
+
parser.add_argument(
|
| 403 |
+
"--truncated-budget",
|
| 404 |
+
type=int,
|
| 405 |
+
default=None,
|
| 406 |
+
help="raw-budget arm: base-protocol mechanics (single generation, no forced "
|
| 407 |
+
"rescue) at this token cap instead of the hardcoded 16 (mutually exclusive "
|
| 408 |
+
"with --base-protocol)",
|
| 409 |
+
)
|
| 410 |
+
args = parser.parse_args()
|
| 411 |
+
if args.reasoning_budget < 1:
|
| 412 |
+
parser.error("--reasoning-budget must be positive")
|
| 413 |
+
if args.force_budget < 1:
|
| 414 |
+
parser.error("--force-budget must be positive")
|
| 415 |
+
if args.frame_count < 1:
|
| 416 |
+
parser.error("--frames-per-video must be positive")
|
| 417 |
+
if args.truncated_budget is not None and args.truncated_budget < 1:
|
| 418 |
+
parser.error("--truncated-budget must be positive")
|
| 419 |
+
if args.base_protocol and args.truncated_budget is not None:
|
| 420 |
+
parser.error("--base-protocol and --truncated-budget are mutually exclusive")
|
| 421 |
+
|
| 422 |
+
results = run(
|
| 423 |
+
args.model,
|
| 424 |
+
spatial_code_format=args.spatial_code_format,
|
| 425 |
+
scene=args.scene,
|
| 426 |
+
limit=args.limit,
|
| 427 |
+
device=args.device,
|
| 428 |
+
results_dir=args.results_dir,
|
| 429 |
+
write_results=not args.no_write,
|
| 430 |
+
extended=not args.base_protocol and args.truncated_budget is None,
|
| 431 |
+
thinking=args.thinking,
|
| 432 |
+
reasoning_budget=args.reasoning_budget,
|
| 433 |
+
force_budget=args.force_budget,
|
| 434 |
+
frames=args.frames,
|
| 435 |
+
frame_selection=args.frame_selection,
|
| 436 |
+
frame_count=args.frame_count,
|
| 437 |
+
raw_budget=args.truncated_budget,
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
for result in results:
|
| 441 |
+
print(
|
| 442 |
+
f"[{result['scene']}#{result['question_id']}] {result['question_type']}: "
|
| 443 |
+
f"pred={result['answer_given']!r} gt={result['answer_expected']!r} "
|
| 444 |
+
f"score={result['score']} ({result['generation_seconds']:.2f}s) -> "
|
| 445 |
+
f"{result['result_path']}"
|
| 446 |
+
)
|
| 447 |
+
if results:
|
| 448 |
+
mean_score = sum(r["score"] for r in results) / len(results)
|
| 449 |
+
total_seconds = sum(r["generation_seconds"] for r in results)
|
| 450 |
+
print(
|
| 451 |
+
f"\n{len(results)} questions, mean vsibench_score={mean_score:.4f}, "
|
| 452 |
+
f"total generation time={total_seconds:.1f}s"
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
if __name__ == "__main__":
|
| 457 |
+
main()
|
harness/D/spatial_codes.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Load one scene's GROUND-TRUTH spatial code (explicit or compact) as plain JSON.
|
| 2 |
+
|
| 3 |
+
Same "no solver-side adaptation" philosophy as harness.B.spatial_codes: the model is
|
| 4 |
+
shown literally the same file encoder.ground_truth wrote to disk -- schema legend
|
| 5 |
+
included -- not a derived, answer-oriented shape a solver would compute from it.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
from encoder.config import ground_truth_spatial_code_path
|
| 14 |
+
|
| 15 |
+
from harness.D import SPATIAL_CODE_FORMATS
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def load_spatial_code(scene, spatial_code_format):
|
| 19 |
+
"""Return (spatial code dict, path it was loaded from)."""
|
| 20 |
+
if spatial_code_format not in SPATIAL_CODE_FORMATS:
|
| 21 |
+
raise ValueError(
|
| 22 |
+
f"unknown spatial-code format {spatial_code_format!r}; "
|
| 23 |
+
f"expected one of {SPATIAL_CODE_FORMATS}"
|
| 24 |
+
)
|
| 25 |
+
path = ground_truth_spatial_code_path(scene, spatial_code_format)
|
| 26 |
+
if not Path(path).is_file():
|
| 27 |
+
raise FileNotFoundError(
|
| 28 |
+
f"no ground-truth spatial code found for scene {scene!r} at {path} -- "
|
| 29 |
+
"run `python -m encoder.ground_truth` to build it"
|
| 30 |
+
)
|
| 31 |
+
with open(path, encoding="utf-8") as stream:
|
| 32 |
+
return json.load(stream), path
|
harness/D/sweep.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sweep any set of models x spatial-code-formats over ground-truth spatial codes.
|
| 2 |
+
|
| 3 |
+
Every (model, spatial_code_format) pair in the sweep is run through
|
| 4 |
+
``harness.D.launch.launch`` in turn, so each pair individually saturates every visible
|
| 5 |
+
GPU before the next one starts. No depth/tracking/input-selection/frame-count axes --
|
| 6 |
+
ground truth has none of those (see harness/D/__init__.py) -- so by design this sweeps
|
| 7 |
+
BOTH spatial_code_formats for every model rather than picking one winning format, per
|
| 8 |
+
this session's execution-design decision: ground-truth codes cost nothing extra to build
|
| 9 |
+
across formats (no GPU encoder pass at all), so the marginal cost of covering both is
|
| 10 |
+
just the extra VLM inference calls, and seeing whether a format's real-vs-perfect
|
| 11 |
+
ranking flips is exactly the kind of thing this phase exists to check.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
import sys
|
| 19 |
+
|
| 20 |
+
HERE = Path(__file__).resolve().parent
|
| 21 |
+
WORKSPACE_ROOT = HERE.parent.parent
|
| 22 |
+
if str(WORKSPACE_ROOT) not in sys.path:
|
| 23 |
+
sys.path.insert(0, str(WORKSPACE_ROOT))
|
| 24 |
+
|
| 25 |
+
from harness.A import models as vlm_models # noqa: E402
|
| 26 |
+
from harness.A import EXTENDED_MAX_NEW_TOKENS # noqa: E402
|
| 27 |
+
from harness.A.sweep import _parse_csv_choice # noqa: E402
|
| 28 |
+
from harness.B import (
|
| 29 |
+
DEFAULT_INPUT_SELECTION,
|
| 30 |
+
FRAMES_PER_VIDEO,
|
| 31 |
+
INPUT_SELECTIONS,
|
| 32 |
+
SPATIAL_CODE_FORMATS,
|
| 33 |
+
) # noqa: E402
|
| 34 |
+
from harness.D import launch as harness_launch # noqa: E402
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def build_plan(models, spatial_code_formats):
|
| 38 |
+
"""Return every (model, spatial_code_format) pair in the sweep."""
|
| 39 |
+
return [
|
| 40 |
+
(model, spatial_code_format)
|
| 41 |
+
for model in models
|
| 42 |
+
for spatial_code_format in spatial_code_formats
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def sweep(
|
| 47 |
+
models,
|
| 48 |
+
spatial_code_formats,
|
| 49 |
+
selected_scenes,
|
| 50 |
+
results_dir=None,
|
| 51 |
+
rebuild=False,
|
| 52 |
+
thinking=False,
|
| 53 |
+
extended=True,
|
| 54 |
+
reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
|
| 55 |
+
frames=False,
|
| 56 |
+
frame_selection=DEFAULT_INPUT_SELECTION,
|
| 57 |
+
frame_count=FRAMES_PER_VIDEO,
|
| 58 |
+
raw_budget=None,
|
| 59 |
+
):
|
| 60 |
+
"""Run every (model, spatial_code_format) pair across all visible GPUs."""
|
| 61 |
+
plan = build_plan(models, spatial_code_formats)
|
| 62 |
+
protocol = (
|
| 63 |
+
f"{reasoning_budget}"
|
| 64 |
+
if extended
|
| 65 |
+
else f"truncated/{raw_budget}" if raw_budget is not None else "base"
|
| 66 |
+
)
|
| 67 |
+
for index, (model, spatial_code_format) in enumerate(plan, start=1):
|
| 68 |
+
print(
|
| 69 |
+
f"=== sweep {index}/{len(plan)}: {model}/{protocol}/{spatial_code_format}"
|
| 70 |
+
+ (f"/frames/{frame_selection}/{frame_count}" if frames else "")
|
| 71 |
+
+ " ===",
|
| 72 |
+
flush=True,
|
| 73 |
+
)
|
| 74 |
+
harness_launch.launch(
|
| 75 |
+
model,
|
| 76 |
+
spatial_code_format,
|
| 77 |
+
selected_scenes,
|
| 78 |
+
results_dir=results_dir,
|
| 79 |
+
rebuild=rebuild,
|
| 80 |
+
thinking=thinking,
|
| 81 |
+
extended=extended,
|
| 82 |
+
reasoning_budget=reasoning_budget,
|
| 83 |
+
frames=frames,
|
| 84 |
+
frame_selection=frame_selection,
|
| 85 |
+
frame_count=frame_count,
|
| 86 |
+
raw_budget=raw_budget,
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def main():
|
| 91 |
+
parser = argparse.ArgumentParser()
|
| 92 |
+
parser.add_argument("scene", nargs="?")
|
| 93 |
+
parser.add_argument(
|
| 94 |
+
"--scenes",
|
| 95 |
+
help="comma-separated scenes (cannot be combined with positional scene)",
|
| 96 |
+
)
|
| 97 |
+
parser.add_argument(
|
| 98 |
+
"--models",
|
| 99 |
+
required=True,
|
| 100 |
+
help=f"comma-separated models (or 'all'); one of {vlm_models.available_models()}",
|
| 101 |
+
)
|
| 102 |
+
parser.add_argument(
|
| 103 |
+
"--spatial-code-formats",
|
| 104 |
+
default="all",
|
| 105 |
+
dest="spatial_code_formats",
|
| 106 |
+
help=f"comma-separated formats (or 'all'); one of {SPATIAL_CODE_FORMATS}",
|
| 107 |
+
)
|
| 108 |
+
parser.add_argument("--results-dir", default=None)
|
| 109 |
+
parser.add_argument("--rebuild", action="store_true")
|
| 110 |
+
parser.add_argument(
|
| 111 |
+
"--base-protocol",
|
| 112 |
+
action="store_true",
|
| 113 |
+
help="run the whole sweep under harness.A's exact fixed 16-token protocol "
|
| 114 |
+
"instead of the extended default",
|
| 115 |
+
)
|
| 116 |
+
parser.add_argument(
|
| 117 |
+
"--thinking",
|
| 118 |
+
action="store_true",
|
| 119 |
+
help="enable the model's native thinking mode where supported; errors on models without the switch",
|
| 120 |
+
)
|
| 121 |
+
parser.add_argument(
|
| 122 |
+
"--reasoning-budget",
|
| 123 |
+
type=int,
|
| 124 |
+
default=EXTENDED_MAX_NEW_TOKENS,
|
| 125 |
+
dest="reasoning_budget",
|
| 126 |
+
help="extended-protocol first-pass budget (the calibrated value from "
|
| 127 |
+
"analysis/preregistration.md, e.g. 512)",
|
| 128 |
+
)
|
| 129 |
+
parser.add_argument(
|
| 130 |
+
"--with-frames",
|
| 131 |
+
action="store_true",
|
| 132 |
+
dest="frames",
|
| 133 |
+
help="frames+ground-truth-code arm: also sample and show the scene's raw video "
|
| 134 |
+
"frames alongside the ground-truth code (default sampling: uniform, 32 frames -- "
|
| 135 |
+
"the frozen Step-1 config)",
|
| 136 |
+
)
|
| 137 |
+
parser.add_argument(
|
| 138 |
+
"--frame-selection",
|
| 139 |
+
default=DEFAULT_INPUT_SELECTION,
|
| 140 |
+
choices=INPUT_SELECTIONS,
|
| 141 |
+
dest="frame_selection",
|
| 142 |
+
help="only used with --with-frames",
|
| 143 |
+
)
|
| 144 |
+
parser.add_argument(
|
| 145 |
+
"--frames-per-video",
|
| 146 |
+
type=int,
|
| 147 |
+
default=FRAMES_PER_VIDEO,
|
| 148 |
+
dest="frame_count",
|
| 149 |
+
help="only used with --with-frames",
|
| 150 |
+
)
|
| 151 |
+
parser.add_argument(
|
| 152 |
+
"--truncated-budget",
|
| 153 |
+
type=int,
|
| 154 |
+
default=None,
|
| 155 |
+
help="raw-budget arm: base-protocol mechanics (single generation, no forced "
|
| 156 |
+
"rescue) at this token cap instead of the hardcoded 16 (mutually exclusive "
|
| 157 |
+
"with --base-protocol)",
|
| 158 |
+
)
|
| 159 |
+
args = parser.parse_args()
|
| 160 |
+
if args.scene and args.scenes:
|
| 161 |
+
parser.error("positional scene and --scenes cannot be used together")
|
| 162 |
+
if args.frame_count < 1:
|
| 163 |
+
parser.error("--frames-per-video must be positive")
|
| 164 |
+
if args.truncated_budget is not None and args.truncated_budget < 1:
|
| 165 |
+
parser.error("--truncated-budget must be positive")
|
| 166 |
+
if args.base_protocol and args.truncated_budget is not None:
|
| 167 |
+
parser.error("--base-protocol and --truncated-budget are mutually exclusive")
|
| 168 |
+
|
| 169 |
+
try:
|
| 170 |
+
models = _parse_csv_choice(
|
| 171 |
+
args.models, vlm_models.available_models(), "--models"
|
| 172 |
+
)
|
| 173 |
+
spatial_code_formats = _parse_csv_choice(
|
| 174 |
+
args.spatial_code_formats, SPATIAL_CODE_FORMATS, "--spatial-code-formats"
|
| 175 |
+
)
|
| 176 |
+
except ValueError as exc:
|
| 177 |
+
parser.error(str(exc))
|
| 178 |
+
|
| 179 |
+
if args.scenes is not None:
|
| 180 |
+
selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
|
| 181 |
+
if not selected:
|
| 182 |
+
parser.error("--scenes must contain at least one scene")
|
| 183 |
+
selected = list(dict.fromkeys(selected))
|
| 184 |
+
else:
|
| 185 |
+
selected = [args.scene] if args.scene else harness_launch.scenes()
|
| 186 |
+
|
| 187 |
+
sweep(
|
| 188 |
+
models,
|
| 189 |
+
spatial_code_formats,
|
| 190 |
+
selected,
|
| 191 |
+
results_dir=args.results_dir,
|
| 192 |
+
rebuild=args.rebuild,
|
| 193 |
+
thinking=args.thinking,
|
| 194 |
+
extended=not args.base_protocol and args.truncated_budget is None,
|
| 195 |
+
reasoning_budget=args.reasoning_budget,
|
| 196 |
+
frames=args.frames,
|
| 197 |
+
frame_selection=args.frame_selection,
|
| 198 |
+
frame_count=args.frame_count,
|
| 199 |
+
raw_budget=args.truncated_budget,
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
if __name__ == "__main__":
|
| 204 |
+
main()
|
harness/D/symbolic_eval.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run the real symbolic solver directly against ground-truth spatial codes -- no VLM at
|
| 2 |
+
all -- the perfect-information ceiling: perfect geometry AND perfect (deterministic,
|
| 3 |
+
formula-driven) reasoning over it.
|
| 4 |
+
|
| 5 |
+
Reuses symbolic/solver.py and symbolic/adapters.py completely unmodified (the same
|
| 6 |
+
solver harness.D.run's VLM path is being compared against use for scoring, and
|
| 7 |
+
symbolic/run.py itself uses for the encoder-perceived spatial codes) -- this module only
|
| 8 |
+
supplies ground-truth-sourced input instead of a perception-pipeline-sourced one.
|
| 9 |
+
|
| 10 |
+
Results are written through symbolic.run's own writer, in symbolic's own native record
|
| 11 |
+
shape, landing in the SAME results family every other symbolic-solver result already
|
| 12 |
+
lives in: results/symbolic/ground truth/<format>/<scene>/<question_id>.json -- not a
|
| 13 |
+
separate results/D/... location -- since this IS a symbolic-solver run, just against
|
| 14 |
+
ground-truth input instead of a perception-pipeline selection
|
| 15 |
+
(symbolic.run.select_ground_truth_spatial_codes).
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import sys
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent
|
| 25 |
+
if str(WORKSPACE_ROOT) not in sys.path:
|
| 26 |
+
sys.path.insert(0, str(WORKSPACE_ROOT))
|
| 27 |
+
|
| 28 |
+
from harness.A.run import _scalar_score, load_questions, vsi_official_eval # noqa: E402
|
| 29 |
+
from harness.D import DEFAULT_SPATIAL_CODE_FORMAT, SPATIAL_CODE_FORMATS # noqa: E402
|
| 30 |
+
from harness.D import spatial_codes # noqa: E402
|
| 31 |
+
from symbolic import adapters, solver # noqa: E402
|
| 32 |
+
from symbolic import run as symbolic_run # noqa: E402
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def run(
|
| 36 |
+
spatial_code_format=DEFAULT_SPATIAL_CODE_FORMAT,
|
| 37 |
+
scene=None,
|
| 38 |
+
scenes=None,
|
| 39 |
+
limit=None,
|
| 40 |
+
jsonl_path=None,
|
| 41 |
+
results_dir=None,
|
| 42 |
+
write_results=True,
|
| 43 |
+
):
|
| 44 |
+
"""Answer every matching question with the real symbolic solver, given each
|
| 45 |
+
question's scene's GROUND-TRUTH spatial code. Writes symbolic's own native-shape
|
| 46 |
+
record (results/symbolic/ground truth/<format>/...) when ``write_results``."""
|
| 47 |
+
rows = load_questions(jsonl_path, scene, scenes, limit)
|
| 48 |
+
if not rows:
|
| 49 |
+
return []
|
| 50 |
+
if write_results:
|
| 51 |
+
symbolic_run.select_ground_truth_spatial_codes(spatial_code_format)
|
| 52 |
+
code_cache = {}
|
| 53 |
+
results = []
|
| 54 |
+
for row in rows:
|
| 55 |
+
scene_id = row["scene_name"]
|
| 56 |
+
if scene_id not in code_cache:
|
| 57 |
+
code, path = spatial_codes.load_spatial_code(scene_id, spatial_code_format)
|
| 58 |
+
code_cache[scene_id] = {
|
| 59 |
+
"adapted": adapters.adapt_spatial_code(code),
|
| 60 |
+
"path": path,
|
| 61 |
+
}
|
| 62 |
+
cached = code_cache[scene_id]
|
| 63 |
+
answer = solver.answer(
|
| 64 |
+
row["question_type"], row["question"], row["options"], cached["adapted"]
|
| 65 |
+
)
|
| 66 |
+
pred_str = "" if answer is None else str(answer)
|
| 67 |
+
doc = {
|
| 68 |
+
"question_type": row["question_type"],
|
| 69 |
+
"ground_truth": row["ground_truth"],
|
| 70 |
+
}
|
| 71 |
+
score_doc = vsi_official_eval.vsibench_process_results(doc, [pred_str])[
|
| 72 |
+
"vsibench_score"
|
| 73 |
+
]
|
| 74 |
+
_metric_name, score = _scalar_score(row["question_type"], score_doc)
|
| 75 |
+
record = {
|
| 76 |
+
"scene": scene_id,
|
| 77 |
+
"dataset": row.get("dataset"),
|
| 78 |
+
"question_id": row["id"],
|
| 79 |
+
"question_type": row["question_type"],
|
| 80 |
+
"question": row["question"],
|
| 81 |
+
"answer_expected": row["ground_truth"],
|
| 82 |
+
"answer_given": pred_str,
|
| 83 |
+
"score": score,
|
| 84 |
+
}
|
| 85 |
+
if write_results:
|
| 86 |
+
pq = {
|
| 87 |
+
"question_id": row["id"],
|
| 88 |
+
"dataset": row.get("dataset"),
|
| 89 |
+
"question_type": row["question_type"],
|
| 90 |
+
"question": row["question"],
|
| 91 |
+
"options": row.get("options"),
|
| 92 |
+
"engine_answer": answer,
|
| 93 |
+
"ground_truth": row["ground_truth"],
|
| 94 |
+
"score": score,
|
| 95 |
+
}
|
| 96 |
+
path = symbolic_run.write_question_result(
|
| 97 |
+
scene_id, pq, cached["adapted"], results_dir=results_dir
|
| 98 |
+
)
|
| 99 |
+
record["result_path"] = str(path)
|
| 100 |
+
else:
|
| 101 |
+
record["result_path"] = None
|
| 102 |
+
results.append(record)
|
| 103 |
+
return results
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def main():
|
| 107 |
+
parser = argparse.ArgumentParser()
|
| 108 |
+
parser.add_argument("scene", nargs="?")
|
| 109 |
+
parser.add_argument("--scenes", help="comma-separated scenes")
|
| 110 |
+
parser.add_argument(
|
| 111 |
+
"--spatial-code-format",
|
| 112 |
+
default=DEFAULT_SPATIAL_CODE_FORMAT,
|
| 113 |
+
choices=SPATIAL_CODE_FORMATS,
|
| 114 |
+
dest="spatial_code_format",
|
| 115 |
+
)
|
| 116 |
+
parser.add_argument("--limit", type=int, default=None)
|
| 117 |
+
parser.add_argument(
|
| 118 |
+
"--results-dir",
|
| 119 |
+
default=None,
|
| 120 |
+
help="override the default results/symbolic/ground truth/<format> root",
|
| 121 |
+
)
|
| 122 |
+
parser.add_argument("--no-write", action="store_true")
|
| 123 |
+
args = parser.parse_args()
|
| 124 |
+
if args.scene and args.scenes:
|
| 125 |
+
parser.error("positional scene and --scenes cannot be used together")
|
| 126 |
+
selected = None
|
| 127 |
+
if args.scenes:
|
| 128 |
+
selected = list(
|
| 129 |
+
dict.fromkeys(s.strip() for s in args.scenes.split(",") if s.strip())
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
results = run(
|
| 133 |
+
spatial_code_format=args.spatial_code_format,
|
| 134 |
+
scene=args.scene,
|
| 135 |
+
scenes=selected,
|
| 136 |
+
limit=args.limit,
|
| 137 |
+
results_dir=args.results_dir,
|
| 138 |
+
write_results=not args.no_write,
|
| 139 |
+
)
|
| 140 |
+
for result in results:
|
| 141 |
+
print(
|
| 142 |
+
f"[{result['scene']}#{result['question_id']}] {result['question_type']}: "
|
| 143 |
+
f"pred={result['answer_given']!r} gt={result['answer_expected']!r} "
|
| 144 |
+
f"score={result['score']} -> {result['result_path']}"
|
| 145 |
+
)
|
| 146 |
+
if results:
|
| 147 |
+
mean_score = sum(r["score"] for r in results) / len(results)
|
| 148 |
+
print(f"\n{len(results)} questions, mean vsibench_score={mean_score:.4f}")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
main()
|
harness/E/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Harness E: the BLIND floor -- question (and options) only, no video frames, no
|
| 2 |
+
spatial code, no scene information of any kind.
|
| 3 |
+
|
| 4 |
+
VSI-Bench's own paper shows blind LLMs beat chance on several categories through pure
|
| 5 |
+
priors (typical room sizes, typical object sizes), so a question-only floor is what
|
| 6 |
+
separates "the model used the geometry it was given" from "the prompt shifted its
|
| 7 |
+
priors." Every harness A/B/C/D delta is only interpretable against this floor.
|
| 8 |
+
|
| 9 |
+
Reuses harness.A's models, generation protocols (base 16-token by default, --extended
|
| 10 |
+
opt-in, exactly like harness.A), question-type split, and post-prompts. Results are
|
| 11 |
+
written in the identical per-question record shape as every other harness:
|
| 12 |
+
results/E/<model>/<protocol>/<scene>/<question_id>.json.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
from harness.A import (
|
| 21 |
+
DO_SAMPLE,
|
| 22 |
+
JSONL,
|
| 23 |
+
MAX_NEW_TOKENS,
|
| 24 |
+
MODEL_PATHS,
|
| 25 |
+
PROTOCOLS,
|
| 26 |
+
TEMPERATURE,
|
| 27 |
+
WORKSPACE_ROOT,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
# One JSON per question: results/E/<model>/<protocol>/<scene>/<question_id>.json
|
| 31 |
+
RESULTS_DIR = Path(os.environ.get("VSI_HARNESS_E_RESULTS_DIR", "/root/results/E"))
|
harness/E/launch.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Keep every visible GPU busy with persistent harness-E (blind floor) workers.
|
| 2 |
+
|
| 3 |
+
Same shape as ``harness.A.launch``: one persistent worker process per visible GPU,
|
| 4 |
+
pulling scenes off a shared queue, each loading its model exactly once and reusing it
|
| 5 |
+
for every scene it's assigned (via ``run.run(..., adapter=...)``). One invocation
|
| 6 |
+
covers one (model, protocol) pair across every requested scene.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import importlib.util
|
| 13 |
+
import multiprocessing as mp
|
| 14 |
+
import os
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import sys
|
| 17 |
+
import traceback
|
| 18 |
+
|
| 19 |
+
HERE = Path(__file__).resolve().parent
|
| 20 |
+
WORKSPACE_ROOT = HERE.parent.parent
|
| 21 |
+
if str(WORKSPACE_ROOT) not in sys.path:
|
| 22 |
+
sys.path.insert(0, str(WORKSPACE_ROOT))
|
| 23 |
+
|
| 24 |
+
from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402
|
| 25 |
+
from harness.A import models as vlm_models # noqa: E402
|
| 26 |
+
from harness.A.launch import scenes # noqa: E402
|
| 27 |
+
from inference.launch import available_cpu_count, visible_gpus # noqa: E402
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _load_run_module():
|
| 31 |
+
spec = importlib.util.spec_from_file_location("_harness_E_run", HERE / "run.py")
|
| 32 |
+
module = importlib.util.module_from_spec(spec)
|
| 33 |
+
sys.modules[spec.name] = module
|
| 34 |
+
spec.loader.exec_module(module)
|
| 35 |
+
return module
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _worker(
|
| 39 |
+
tasks,
|
| 40 |
+
results,
|
| 41 |
+
model,
|
| 42 |
+
results_dir,
|
| 43 |
+
gpu,
|
| 44 |
+
cpu_threads,
|
| 45 |
+
extended,
|
| 46 |
+
reasoning_budget,
|
| 47 |
+
force_budget,
|
| 48 |
+
thinking,
|
| 49 |
+
):
|
| 50 |
+
if gpu is not None:
|
| 51 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
|
| 52 |
+
for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
|
| 53 |
+
os.environ[variable] = str(cpu_threads)
|
| 54 |
+
run = _load_run_module()
|
| 55 |
+
adapter = None
|
| 56 |
+
load_error = None
|
| 57 |
+
try:
|
| 58 |
+
adapter = vlm_models.get_adapter(model)
|
| 59 |
+
if thinking and not adapter.set_thinking(True):
|
| 60 |
+
raise ValueError(f"{model} has no native thinking mode to enable")
|
| 61 |
+
adapter.load_model("cuda:0" if gpu is not None else "cpu")
|
| 62 |
+
except Exception:
|
| 63 |
+
load_error = traceback.format_exc()
|
| 64 |
+
while True:
|
| 65 |
+
scene = tasks.get()
|
| 66 |
+
if scene is None:
|
| 67 |
+
return
|
| 68 |
+
if load_error is not None:
|
| 69 |
+
results.put((scene, False, load_error))
|
| 70 |
+
continue
|
| 71 |
+
try:
|
| 72 |
+
answered = run.run(
|
| 73 |
+
model,
|
| 74 |
+
scene=scene,
|
| 75 |
+
results_dir=results_dir,
|
| 76 |
+
adapter=adapter,
|
| 77 |
+
extended=extended,
|
| 78 |
+
reasoning_budget=reasoning_budget,
|
| 79 |
+
force_budget=force_budget,
|
| 80 |
+
thinking=thinking,
|
| 81 |
+
)
|
| 82 |
+
mean_score = (
|
| 83 |
+
sum(r["score"] for r in answered) / len(answered) if answered else None
|
| 84 |
+
)
|
| 85 |
+
results.put(
|
| 86 |
+
(scene, True, f"{len(answered)} question(s), mean_score={mean_score}")
|
| 87 |
+
)
|
| 88 |
+
except Exception:
|
| 89 |
+
results.put((scene, False, traceback.format_exc()))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def launch(
|
| 93 |
+
model,
|
| 94 |
+
selected,
|
| 95 |
+
results_dir=None,
|
| 96 |
+
rebuild=False,
|
| 97 |
+
extended=False,
|
| 98 |
+
reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
|
| 99 |
+
force_budget=MAX_NEW_TOKENS,
|
| 100 |
+
thinking=False,
|
| 101 |
+
):
|
| 102 |
+
"""Answer every question for ``selected`` scenes, sharded across every visible GPU."""
|
| 103 |
+
protocol = f"{reasoning_budget}" if extended else "base"
|
| 104 |
+
condition = f"{model}/{protocol}"
|
| 105 |
+
run = _load_run_module()
|
| 106 |
+
root = run.results_dir_for(model, protocol, results_dir)
|
| 107 |
+
pending = []
|
| 108 |
+
completed = 0
|
| 109 |
+
for scene in selected:
|
| 110 |
+
rows = run.load_questions(scene=scene)
|
| 111 |
+
if not rows:
|
| 112 |
+
raise ValueError(
|
| 113 |
+
f"no questions found for scene {scene!r}; check the manifest/scene selection"
|
| 114 |
+
)
|
| 115 |
+
answered = all((root / scene / f"{row['id']}.json").is_file() for row in rows)
|
| 116 |
+
if answered and not rebuild:
|
| 117 |
+
completed += 1
|
| 118 |
+
print(
|
| 119 |
+
f"[{condition} {completed}/{len(selected)}] {scene}: skipped",
|
| 120 |
+
flush=True,
|
| 121 |
+
)
|
| 122 |
+
else:
|
| 123 |
+
pending.append(scene)
|
| 124 |
+
if not pending:
|
| 125 |
+
print(f"[{condition}] DONE: {len(selected)} ok, 0 failed")
|
| 126 |
+
return
|
| 127 |
+
|
| 128 |
+
gpus = visible_gpus()
|
| 129 |
+
worker_count = min(len(pending), len(gpus) if gpus else 1)
|
| 130 |
+
assignments = gpus[:worker_count] if gpus else [None]
|
| 131 |
+
cpu_count = available_cpu_count()
|
| 132 |
+
cpu_threads = max(1, cpu_count // worker_count)
|
| 133 |
+
print(
|
| 134 |
+
f"[{condition}] starting {worker_count} persistent worker(s); "
|
| 135 |
+
f"GPUs={assignments}; CPU threads/worker={cpu_threads}",
|
| 136 |
+
flush=True,
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
context = mp.get_context("spawn")
|
| 140 |
+
tasks, results = context.Queue(), context.Queue()
|
| 141 |
+
for scene in pending:
|
| 142 |
+
tasks.put(scene)
|
| 143 |
+
for _ in range(worker_count):
|
| 144 |
+
tasks.put(None)
|
| 145 |
+
workers = [
|
| 146 |
+
context.Process(
|
| 147 |
+
target=_worker,
|
| 148 |
+
args=(
|
| 149 |
+
tasks,
|
| 150 |
+
results,
|
| 151 |
+
model,
|
| 152 |
+
results_dir,
|
| 153 |
+
gpu,
|
| 154 |
+
cpu_threads,
|
| 155 |
+
extended,
|
| 156 |
+
reasoning_budget,
|
| 157 |
+
force_budget,
|
| 158 |
+
thinking,
|
| 159 |
+
),
|
| 160 |
+
)
|
| 161 |
+
for gpu in assignments
|
| 162 |
+
]
|
| 163 |
+
for worker in workers:
|
| 164 |
+
worker.start()
|
| 165 |
+
failed = []
|
| 166 |
+
for finished in range(1, len(pending) + 1):
|
| 167 |
+
scene, ok, detail = results.get()
|
| 168 |
+
if not ok:
|
| 169 |
+
failed.append(scene)
|
| 170 |
+
print(
|
| 171 |
+
f"[{condition} {completed + finished}/{len(selected)}] {scene}: "
|
| 172 |
+
f"{'done' if ok else 'FAILED'}\n{detail}",
|
| 173 |
+
flush=True,
|
| 174 |
+
)
|
| 175 |
+
for worker in workers:
|
| 176 |
+
worker.join()
|
| 177 |
+
print(
|
| 178 |
+
f"[{condition}] DONE: {len(pending) - len(failed)} answered, {completed} skipped, "
|
| 179 |
+
f"{len(failed)} failed"
|
| 180 |
+
)
|
| 181 |
+
if failed:
|
| 182 |
+
raise SystemExit(1)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def main():
|
| 186 |
+
parser = argparse.ArgumentParser()
|
| 187 |
+
parser.add_argument("scene", nargs="?")
|
| 188 |
+
parser.add_argument(
|
| 189 |
+
"--scenes",
|
| 190 |
+
help="comma-separated scenes (cannot be combined with positional scene)",
|
| 191 |
+
)
|
| 192 |
+
parser.add_argument("--model", required=True, choices=vlm_models.available_models())
|
| 193 |
+
parser.add_argument("--results-dir", default=None)
|
| 194 |
+
parser.add_argument("--rebuild", action="store_true")
|
| 195 |
+
parser.add_argument(
|
| 196 |
+
"--extended",
|
| 197 |
+
action="store_true",
|
| 198 |
+
help="use the extended 2048-token protocol instead of the fixed 16-token default",
|
| 199 |
+
)
|
| 200 |
+
parser.add_argument(
|
| 201 |
+
"--thinking",
|
| 202 |
+
action="store_true",
|
| 203 |
+
help="enable the model's native thinking mode where supported; errors on models without the switch",
|
| 204 |
+
)
|
| 205 |
+
parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
|
| 206 |
+
parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
|
| 207 |
+
args = parser.parse_args()
|
| 208 |
+
if args.scene and args.scenes:
|
| 209 |
+
parser.error("positional scene and --scenes cannot be used together")
|
| 210 |
+
if args.scenes is not None:
|
| 211 |
+
selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
|
| 212 |
+
if not selected:
|
| 213 |
+
parser.error("--scenes must contain at least one scene")
|
| 214 |
+
selected = list(dict.fromkeys(selected))
|
| 215 |
+
else:
|
| 216 |
+
selected = [args.scene] if args.scene else scenes()
|
| 217 |
+
if args.reasoning_budget < 1:
|
| 218 |
+
parser.error("--reasoning-budget must be positive")
|
| 219 |
+
if args.force_budget < 1:
|
| 220 |
+
parser.error("--force-budget must be positive")
|
| 221 |
+
launch(
|
| 222 |
+
args.model,
|
| 223 |
+
selected,
|
| 224 |
+
results_dir=args.results_dir,
|
| 225 |
+
rebuild=args.rebuild,
|
| 226 |
+
extended=args.extended,
|
| 227 |
+
thinking=args.thinking,
|
| 228 |
+
reasoning_budget=args.reasoning_budget,
|
| 229 |
+
force_budget=args.force_budget,
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
if __name__ == "__main__":
|
| 234 |
+
main()
|
harness/E/prompts.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""VSI-Bench prompt construction with NO scene input at all -- the blind floor.
|
| 2 |
+
|
| 3 |
+
Reuses harness.A.prompts's question-type split and final-answer constraints. There
|
| 4 |
+
is deliberately NO context line: there are no frames and no spatial code to describe,
|
| 5 |
+
and inventing one ("answer from your general knowledge") would itself be an
|
| 6 |
+
uncontrolled prompt manipulation. The prompt is exactly the question (and options)
|
| 7 |
+
plus the same post-prompt every other harness uses for that question type.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
from harness.A.prompts import (
|
| 13 |
+
MCA_POST_PROMPT,
|
| 14 |
+
MCA_QUESTION_TYPES,
|
| 15 |
+
NA_POST_PROMPT,
|
| 16 |
+
NA_QUESTION_TYPES,
|
| 17 |
+
STEP_BY_STEP_REASONING_PROMPT,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def build_prompt(question_type, question, options=None):
|
| 22 |
+
"""Return the blind text prompt: the question, options (for MCA types), and the
|
| 23 |
+
same VSI-Bench post-prompt harness.A uses for the same question_type."""
|
| 24 |
+
if question_type in NA_QUESTION_TYPES:
|
| 25 |
+
return "\n".join([question, STEP_BY_STEP_REASONING_PROMPT, NA_POST_PROMPT])
|
| 26 |
+
if question_type in MCA_QUESTION_TYPES:
|
| 27 |
+
if not options:
|
| 28 |
+
raise ValueError(f"question_type {question_type!r} requires options")
|
| 29 |
+
options_block = "Options:\n" + "\n".join(options)
|
| 30 |
+
return "\n".join(
|
| 31 |
+
[question, options_block, STEP_BY_STEP_REASONING_PROMPT, MCA_POST_PROMPT]
|
| 32 |
+
)
|
| 33 |
+
raise ValueError(
|
| 34 |
+
f"unknown question_type {question_type!r}; "
|
| 35 |
+
f"expected one of {MCA_QUESTION_TYPES + NA_QUESTION_TYPES}"
|
| 36 |
+
)
|
harness/E/run.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run one VLM over VSI-Bench questions completely blind -- question text only.
|
| 2 |
+
|
| 3 |
+
Writes one JSON file per question in the identical shape harness.A/B/C/D use -- with no
|
| 4 |
+
frame or spatial-code provenance fields at all, since E receives no scene input of any
|
| 5 |
+
kind. Scoring reuses the same real, unmodified official scorer every harness uses.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
import sys
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent
|
| 16 |
+
if str(WORKSPACE_ROOT) not in sys.path:
|
| 17 |
+
sys.path.insert(0, str(WORKSPACE_ROOT))
|
| 18 |
+
|
| 19 |
+
from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402
|
| 20 |
+
from harness.A import models as vlm_models # noqa: E402
|
| 21 |
+
from harness.A.run import _scalar_score, load_questions, vsi_official_eval # noqa: E402
|
| 22 |
+
from harness.E import RESULTS_DIR # noqa: E402
|
| 23 |
+
from harness.E import prompts as blind_prompts # noqa: E402
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def results_dir_for(model, protocol, results_dir=None):
|
| 27 |
+
"""Return the result root isolated by model + protocol. ``protocol`` is "base"
|
| 28 |
+
(16-token) or "extended" (2048-token) -- a real path segment, so the two protocols'
|
| 29 |
+
records can never collide on disk."""
|
| 30 |
+
if results_dir is not None:
|
| 31 |
+
return Path(results_dir)
|
| 32 |
+
return RESULTS_DIR / model / protocol
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _build_record(row, prompt, answer, metric_name, score, model, model_path, protocol):
|
| 36 |
+
"""Assemble one question's full, untruncated result record (nothing summarized)."""
|
| 37 |
+
return {
|
| 38 |
+
"model": model,
|
| 39 |
+
"model_path": str(model_path),
|
| 40 |
+
"device": answer["device"],
|
| 41 |
+
"dtype": answer["dtype"],
|
| 42 |
+
"library_versions": answer["library_versions"],
|
| 43 |
+
"condition": protocol,
|
| 44 |
+
"protocol": protocol,
|
| 45 |
+
"scene": row["scene_name"],
|
| 46 |
+
"dataset": row.get("dataset"),
|
| 47 |
+
"question_id": row["id"],
|
| 48 |
+
"question_type": row["question_type"],
|
| 49 |
+
"question": row["question"],
|
| 50 |
+
"options": row.get("options"),
|
| 51 |
+
"full_prompt": prompt,
|
| 52 |
+
"rendered_prompt": answer["prompt_text"],
|
| 53 |
+
"answer_expected": row["ground_truth"],
|
| 54 |
+
"answer_given": answer["answer_text"],
|
| 55 |
+
"answer_raw": answer["answer_raw"],
|
| 56 |
+
"input_token_count": answer["input_token_count"],
|
| 57 |
+
"vision_input_shapes": answer["vision_input_shapes"],
|
| 58 |
+
"output_token_ids": answer["output_token_ids"],
|
| 59 |
+
"output_token_count": answer["output_token_count"],
|
| 60 |
+
"hit_token_limit": answer["hit_token_limit"],
|
| 61 |
+
"eos_token_ids": answer["eos_token_ids"],
|
| 62 |
+
"generation_seconds": answer["generation_seconds"],
|
| 63 |
+
"generation_config": answer["generation_config"],
|
| 64 |
+
"reasoning_text": answer.get("reasoning_text"),
|
| 65 |
+
"reasoning_raw": answer.get("reasoning_raw"),
|
| 66 |
+
"reasoning_token_ids": answer.get("reasoning_token_ids"),
|
| 67 |
+
"reasoning_token_count": answer.get("reasoning_token_count"),
|
| 68 |
+
"reasoning_hit_limit": answer.get("reasoning_hit_limit"),
|
| 69 |
+
"forced": answer.get("forced", False),
|
| 70 |
+
"forced_input_token_count": answer.get("forced_input_token_count"),
|
| 71 |
+
"metric": metric_name,
|
| 72 |
+
"score": score,
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def write_question_result(
|
| 77 |
+
row,
|
| 78 |
+
prompt,
|
| 79 |
+
answer,
|
| 80 |
+
metric_name,
|
| 81 |
+
score,
|
| 82 |
+
model,
|
| 83 |
+
model_path,
|
| 84 |
+
protocol,
|
| 85 |
+
results_dir=None,
|
| 86 |
+
):
|
| 87 |
+
"""Write one question's full, untruncated result record. Return (path, record)."""
|
| 88 |
+
record = _build_record(
|
| 89 |
+
row, prompt, answer, metric_name, score, model, model_path, protocol
|
| 90 |
+
)
|
| 91 |
+
root = results_dir_for(model, protocol, results_dir)
|
| 92 |
+
scene_dir = root / record["scene"]
|
| 93 |
+
scene_dir.mkdir(parents=True, exist_ok=True)
|
| 94 |
+
path = scene_dir / f"{row['id']}.json"
|
| 95 |
+
with path.open("w", encoding="utf-8") as stream:
|
| 96 |
+
json.dump(record, stream, indent=1)
|
| 97 |
+
return path, record
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def run(
|
| 101 |
+
model,
|
| 102 |
+
scene=None,
|
| 103 |
+
scenes=None,
|
| 104 |
+
limit=None,
|
| 105 |
+
device="cuda",
|
| 106 |
+
jsonl_path=None,
|
| 107 |
+
results_dir=None,
|
| 108 |
+
write_results=True,
|
| 109 |
+
adapter=None,
|
| 110 |
+
thinking=False,
|
| 111 |
+
extended=False,
|
| 112 |
+
reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
|
| 113 |
+
force_budget=MAX_NEW_TOKENS,
|
| 114 |
+
):
|
| 115 |
+
"""Answer every matching question with one model, completely blind (question text
|
| 116 |
+
only, no frames, no spatial code). Each question's full record is written to its
|
| 117 |
+
own JSON file as soon as it is answered (unless ``write_results=False``).
|
| 118 |
+
|
| 119 |
+
Base 16-token protocol by default, exactly like harness.A; ``extended=True``
|
| 120 |
+
switches to the same ``answer_extended`` protocol every other harness supports.
|
| 121 |
+
|
| 122 |
+
Pass a pre-loaded ``adapter`` (as harness.E.launch's persistent per-GPU workers do)
|
| 123 |
+
to reuse one already-loaded model across many calls; the caller then owns unloading
|
| 124 |
+
it. Without one, ``run`` loads and unloads its own adapter, same as harness.A.
|
| 125 |
+
"""
|
| 126 |
+
rows = load_questions(jsonl_path, scene, scenes, limit)
|
| 127 |
+
if not rows:
|
| 128 |
+
return []
|
| 129 |
+
owns_adapter = adapter is None
|
| 130 |
+
if owns_adapter:
|
| 131 |
+
adapter = vlm_models.get_adapter(model)
|
| 132 |
+
if thinking and not adapter.set_thinking(True):
|
| 133 |
+
raise ValueError(f"{model} has no native thinking mode to enable")
|
| 134 |
+
adapter.load_model(device)
|
| 135 |
+
protocol = f"{reasoning_budget}" if extended else "base"
|
| 136 |
+
results = []
|
| 137 |
+
try:
|
| 138 |
+
for row in rows:
|
| 139 |
+
prompt = blind_prompts.build_prompt(
|
| 140 |
+
row["question_type"], row["question"], row.get("options")
|
| 141 |
+
)
|
| 142 |
+
answer = (
|
| 143 |
+
adapter.answer_extended(
|
| 144 |
+
[],
|
| 145 |
+
prompt,
|
| 146 |
+
reasoning_budget=reasoning_budget,
|
| 147 |
+
force_budget=force_budget,
|
| 148 |
+
)
|
| 149 |
+
if extended
|
| 150 |
+
else adapter.answer([], prompt)
|
| 151 |
+
)
|
| 152 |
+
doc = {
|
| 153 |
+
"question_type": row["question_type"],
|
| 154 |
+
"ground_truth": row["ground_truth"],
|
| 155 |
+
}
|
| 156 |
+
score_doc = vsi_official_eval.vsibench_process_results(
|
| 157 |
+
doc, [answer["answer_text"]]
|
| 158 |
+
)["vsibench_score"]
|
| 159 |
+
metric_name, score = _scalar_score(row["question_type"], score_doc)
|
| 160 |
+
if write_results:
|
| 161 |
+
path, record = write_question_result(
|
| 162 |
+
row,
|
| 163 |
+
prompt,
|
| 164 |
+
answer,
|
| 165 |
+
metric_name,
|
| 166 |
+
score,
|
| 167 |
+
model,
|
| 168 |
+
adapter.model_path,
|
| 169 |
+
protocol,
|
| 170 |
+
results_dir,
|
| 171 |
+
)
|
| 172 |
+
else:
|
| 173 |
+
path = None
|
| 174 |
+
record = _build_record(
|
| 175 |
+
row,
|
| 176 |
+
prompt,
|
| 177 |
+
answer,
|
| 178 |
+
metric_name,
|
| 179 |
+
score,
|
| 180 |
+
model,
|
| 181 |
+
adapter.model_path,
|
| 182 |
+
protocol,
|
| 183 |
+
)
|
| 184 |
+
record["result_path"] = str(path) if path else None
|
| 185 |
+
results.append(record)
|
| 186 |
+
finally:
|
| 187 |
+
if owns_adapter:
|
| 188 |
+
adapter.unload()
|
| 189 |
+
return results
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def main():
|
| 193 |
+
parser = argparse.ArgumentParser()
|
| 194 |
+
parser.add_argument("--model", required=True, choices=vlm_models.available_models())
|
| 195 |
+
parser.add_argument("--scene", default=None, help="restrict to one VSI-Bench scene")
|
| 196 |
+
parser.add_argument(
|
| 197 |
+
"--limit", type=int, default=None, help="cap the number of questions"
|
| 198 |
+
)
|
| 199 |
+
parser.add_argument("--device", default="cuda")
|
| 200 |
+
parser.add_argument(
|
| 201 |
+
"--results-dir",
|
| 202 |
+
default=None,
|
| 203 |
+
help="override the default results/E/<model>/<protocol> root",
|
| 204 |
+
)
|
| 205 |
+
parser.add_argument(
|
| 206 |
+
"--no-write",
|
| 207 |
+
action="store_true",
|
| 208 |
+
help="skip writing per-question JSON files; print/score only",
|
| 209 |
+
)
|
| 210 |
+
parser.add_argument(
|
| 211 |
+
"--extended",
|
| 212 |
+
action="store_true",
|
| 213 |
+
help=(
|
| 214 |
+
f"use a {EXTENDED_MAX_NEW_TOKENS}-token reasoning budget instead of the fixed "
|
| 215 |
+
f"{MAX_NEW_TOKENS}-token VSI-Bench protocol, with a short forced second call "
|
| 216 |
+
"only if the model doesn't conclude within it"
|
| 217 |
+
),
|
| 218 |
+
)
|
| 219 |
+
parser.add_argument(
|
| 220 |
+
"--thinking",
|
| 221 |
+
action="store_true",
|
| 222 |
+
help="enable the model's native thinking mode where supported; errors on models without the switch",
|
| 223 |
+
)
|
| 224 |
+
parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS)
|
| 225 |
+
parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS)
|
| 226 |
+
args = parser.parse_args()
|
| 227 |
+
if args.reasoning_budget < 1:
|
| 228 |
+
parser.error("--reasoning-budget must be positive")
|
| 229 |
+
if args.force_budget < 1:
|
| 230 |
+
parser.error("--force-budget must be positive")
|
| 231 |
+
|
| 232 |
+
results = run(
|
| 233 |
+
args.model,
|
| 234 |
+
scene=args.scene,
|
| 235 |
+
limit=args.limit,
|
| 236 |
+
device=args.device,
|
| 237 |
+
results_dir=args.results_dir,
|
| 238 |
+
write_results=not args.no_write,
|
| 239 |
+
extended=args.extended,
|
| 240 |
+
thinking=args.thinking,
|
| 241 |
+
reasoning_budget=args.reasoning_budget,
|
| 242 |
+
force_budget=args.force_budget,
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
for result in results:
|
| 246 |
+
print(
|
| 247 |
+
f"[{result['scene']}#{result['question_id']}] {result['question_type']}: "
|
| 248 |
+
f"pred={result['answer_given']!r} gt={result['answer_expected']!r} "
|
| 249 |
+
f"score={result['score']} ({result['generation_seconds']:.2f}s) -> "
|
| 250 |
+
f"{result['result_path']}"
|
| 251 |
+
)
|
| 252 |
+
if results:
|
| 253 |
+
mean_score = sum(r["score"] for r in results) / len(results)
|
| 254 |
+
total_seconds = sum(r["generation_seconds"] for r in results)
|
| 255 |
+
print(
|
| 256 |
+
f"\n{len(results)} questions, mean vsibench_score={mean_score:.4f}, "
|
| 257 |
+
f"total generation time={total_seconds:.1f}s"
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
if __name__ == "__main__":
|
| 262 |
+
main()
|
harness/E/sweep.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sweep any set of models over the blind floor (question-only, no scene input).
|
| 2 |
+
|
| 3 |
+
Every model in the sweep is run through ``harness.E.launch.launch`` in turn, so each
|
| 4 |
+
model individually saturates every visible GPU before the next one starts. The only
|
| 5 |
+
other axis is the generation protocol (--extended), matching harness.A's flag.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
import sys
|
| 13 |
+
|
| 14 |
+
HERE = Path(__file__).resolve().parent
|
| 15 |
+
WORKSPACE_ROOT = HERE.parent.parent
|
| 16 |
+
if str(WORKSPACE_ROOT) not in sys.path:
|
| 17 |
+
sys.path.insert(0, str(WORKSPACE_ROOT))
|
| 18 |
+
|
| 19 |
+
from harness.A import EXTENDED_MAX_NEW_TOKENS # noqa: E402
|
| 20 |
+
from harness.A import models as vlm_models # noqa: E402
|
| 21 |
+
from harness.A.sweep import _parse_csv_choice # noqa: E402
|
| 22 |
+
from harness.E import launch as harness_launch # noqa: E402
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def sweep(
|
| 26 |
+
models,
|
| 27 |
+
selected_scenes,
|
| 28 |
+
results_dir=None,
|
| 29 |
+
rebuild=False,
|
| 30 |
+
thinking=False,
|
| 31 |
+
extended=False,
|
| 32 |
+
reasoning_budget=EXTENDED_MAX_NEW_TOKENS,
|
| 33 |
+
):
|
| 34 |
+
"""Run every model across all visible GPUs."""
|
| 35 |
+
protocol = "extended" if extended else "base"
|
| 36 |
+
for index, model in enumerate(models, start=1):
|
| 37 |
+
print(f"=== sweep {index}/{len(models)}: {model}/{protocol} ===", flush=True)
|
| 38 |
+
harness_launch.launch(
|
| 39 |
+
model,
|
| 40 |
+
selected_scenes,
|
| 41 |
+
results_dir=results_dir,
|
| 42 |
+
rebuild=rebuild,
|
| 43 |
+
thinking=thinking,
|
| 44 |
+
extended=extended,
|
| 45 |
+
reasoning_budget=reasoning_budget,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def main():
|
| 50 |
+
parser = argparse.ArgumentParser()
|
| 51 |
+
parser.add_argument("scene", nargs="?")
|
| 52 |
+
parser.add_argument(
|
| 53 |
+
"--scenes",
|
| 54 |
+
help="comma-separated scenes (cannot be combined with positional scene)",
|
| 55 |
+
)
|
| 56 |
+
parser.add_argument(
|
| 57 |
+
"--models",
|
| 58 |
+
required=True,
|
| 59 |
+
help=f"comma-separated models (or 'all'); one of {vlm_models.available_models()}",
|
| 60 |
+
)
|
| 61 |
+
parser.add_argument("--results-dir", default=None)
|
| 62 |
+
parser.add_argument("--rebuild", action="store_true")
|
| 63 |
+
parser.add_argument(
|
| 64 |
+
"--extended",
|
| 65 |
+
action="store_true",
|
| 66 |
+
help="run the whole sweep under the extended protocol instead of the fixed "
|
| 67 |
+
"16-token default",
|
| 68 |
+
)
|
| 69 |
+
parser.add_argument(
|
| 70 |
+
"--thinking",
|
| 71 |
+
action="store_true",
|
| 72 |
+
help="enable the model's native thinking mode where supported; errors on models without the switch",
|
| 73 |
+
)
|
| 74 |
+
parser.add_argument(
|
| 75 |
+
"--reasoning-budget",
|
| 76 |
+
type=int,
|
| 77 |
+
default=EXTENDED_MAX_NEW_TOKENS,
|
| 78 |
+
dest="reasoning_budget",
|
| 79 |
+
help="extended-protocol first-pass budget (the calibrated value from "
|
| 80 |
+
"analysis/preregistration.md, e.g. 512)",
|
| 81 |
+
)
|
| 82 |
+
args = parser.parse_args()
|
| 83 |
+
if args.scene and args.scenes:
|
| 84 |
+
parser.error("positional scene and --scenes cannot be used together")
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
models = _parse_csv_choice(
|
| 88 |
+
args.models, vlm_models.available_models(), "--models"
|
| 89 |
+
)
|
| 90 |
+
except ValueError as exc:
|
| 91 |
+
parser.error(str(exc))
|
| 92 |
+
|
| 93 |
+
if args.scenes is not None:
|
| 94 |
+
selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
|
| 95 |
+
if not selected:
|
| 96 |
+
parser.error("--scenes must contain at least one scene")
|
| 97 |
+
selected = list(dict.fromkeys(selected))
|
| 98 |
+
else:
|
| 99 |
+
from harness.A.launch import scenes
|
| 100 |
+
|
| 101 |
+
selected = [args.scene] if args.scene else scenes()
|
| 102 |
+
|
| 103 |
+
sweep(
|
| 104 |
+
models,
|
| 105 |
+
selected,
|
| 106 |
+
results_dir=args.results_dir,
|
| 107 |
+
rebuild=args.rebuild,
|
| 108 |
+
thinking=args.thinking,
|
| 109 |
+
extended=args.extended,
|
| 110 |
+
reasoning_budget=args.reasoning_budget,
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
if __name__ == "__main__":
|
| 115 |
+
main()
|
tests/test_C/test_overlay.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for harness/C/overlay.py -- overlay labels, cache, and stamping."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
from PIL import Image
|
| 8 |
+
|
| 9 |
+
from harness.C import overlay
|
| 10 |
+
|
| 11 |
+
_EXPLICIT_CODE = {
|
| 12 |
+
"objects": {
|
| 13 |
+
"chair": {
|
| 14 |
+
"instances": [
|
| 15 |
+
{
|
| 16 |
+
"position": {
|
| 17 |
+
"x coordinate": "1.5 m",
|
| 18 |
+
"y coordinate": "-2 m",
|
| 19 |
+
"height above floor": "0.25 m",
|
| 20 |
+
},
|
| 21 |
+
"longest dimension": "0.80 m",
|
| 22 |
+
}
|
| 23 |
+
]
|
| 24 |
+
},
|
| 25 |
+
"table": {
|
| 26 |
+
"instances": [
|
| 27 |
+
{
|
| 28 |
+
"position": {
|
| 29 |
+
"x coordinate": "3 m",
|
| 30 |
+
"y coordinate": "4 m",
|
| 31 |
+
"height above floor": "0 m",
|
| 32 |
+
},
|
| 33 |
+
"longest dimension": "1.20 m",
|
| 34 |
+
}
|
| 35 |
+
]
|
| 36 |
+
},
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_instance_ids_adds_stable_one_based_labels_without_mutating_input():
|
| 42 |
+
original = {"objects": {"chair": {"instances": [{"position": {}}]}}}
|
| 43 |
+
|
| 44 |
+
labeled = overlay.instance_ids(original)
|
| 45 |
+
|
| 46 |
+
assert labeled["objects"]["chair"]["instances"][0]["instance id"] == "chair 1"
|
| 47 |
+
assert "instance id" not in original["objects"]["chair"]["instances"][0]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_overlay_spatial_code_path_lives_under_overlay_root(monkeypatch, tmp_path):
|
| 51 |
+
monkeypatch.setattr(
|
| 52 |
+
overlay.encoder_config, "CODES_ROOT", tmp_path / "data" / "spatial codes"
|
| 53 |
+
)
|
| 54 |
+
monkeypatch.setattr(overlay.encoder_config, "MODEL", "sam3+depth-anything-3")
|
| 55 |
+
|
| 56 |
+
path = overlay.overlay_spatial_code_path(
|
| 57 |
+
"scene", "metric", "uniform", "tracking", 32
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
assert path == (
|
| 61 |
+
tmp_path
|
| 62 |
+
/ "data"
|
| 63 |
+
/ "spatial codes"
|
| 64 |
+
/ "overlay"
|
| 65 |
+
/ "sam3+depth-anything-3"
|
| 66 |
+
/ "metric"
|
| 67 |
+
/ "tracking"
|
| 68 |
+
/ "uniform"
|
| 69 |
+
/ "32"
|
| 70 |
+
/ "explicit"
|
| 71 |
+
/ "scene.json"
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_load_or_create_overlay_code_saves_missing_file(monkeypatch, tmp_path):
|
| 76 |
+
monkeypatch.setattr(overlay.encoder_config, "CODES_ROOT", tmp_path / "codes")
|
| 77 |
+
monkeypatch.setattr(overlay.encoder_config, "MODEL", "model")
|
| 78 |
+
|
| 79 |
+
code, path = overlay.load_or_create_overlay_code(
|
| 80 |
+
_EXPLICIT_CODE, "scene", "metric", "uniform", "tracking", 32
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
path = Path(path)
|
| 84 |
+
assert path.is_file()
|
| 85 |
+
assert json.loads(path.read_text()) == code
|
| 86 |
+
assert code["objects"]["chair"]["instances"][0]["instance id"] == "chair 1"
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def test_load_or_create_overlay_code_reuses_existing_file(monkeypatch, tmp_path):
|
| 90 |
+
monkeypatch.setattr(overlay.encoder_config, "CODES_ROOT", tmp_path / "codes")
|
| 91 |
+
monkeypatch.setattr(overlay.encoder_config, "MODEL", "model")
|
| 92 |
+
path = overlay.overlay_spatial_code_path(
|
| 93 |
+
"scene", "metric", "uniform", "tracking", 32
|
| 94 |
+
)
|
| 95 |
+
path.parent.mkdir(parents=True)
|
| 96 |
+
existing = {"objects": {"saved": {"instances": []}}, "sentinel": True}
|
| 97 |
+
path.write_text(json.dumps(existing))
|
| 98 |
+
|
| 99 |
+
code, returned = overlay.load_or_create_overlay_code(
|
| 100 |
+
_EXPLICIT_CODE, "scene", "metric", "uniform", "tracking", 32
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
assert returned == str(path)
|
| 104 |
+
assert code == existing
|
| 105 |
+
assert json.loads(path.read_text()) == existing
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_label_positions_parse_meter_strings_in_code_order():
|
| 109 |
+
assert overlay.label_positions(_EXPLICIT_CODE) == [
|
| 110 |
+
("chair 1", 1.5, -2.0, 0.25, 0.8),
|
| 111 |
+
("table 1", 3.0, 4.0, 0.0, 1.2),
|
| 112 |
+
]
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def test_load_cached_frames_requires_complete_png_set_and_labels(tmp_path):
|
| 116 |
+
assert overlay._load_cached_frames(tmp_path, 2) is None
|
| 117 |
+
(tmp_path / "labels.json").write_text(json.dumps([["chair 1"], []]))
|
| 118 |
+
Image.new("RGB", (4, 4), "white").save(tmp_path / "0.png")
|
| 119 |
+
assert overlay._load_cached_frames(tmp_path, 2) is None
|
| 120 |
+
|
| 121 |
+
Image.new("RGB", (4, 4), "black").save(tmp_path / "1.png")
|
| 122 |
+
images, visible = overlay._load_cached_frames(tmp_path, 2)
|
| 123 |
+
|
| 124 |
+
assert [image.mode for image in images] == ["RGB", "RGB"]
|
| 125 |
+
assert visible == [["chair 1"], []]
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_save_cached_frames_writes_pngs_and_labels(tmp_path):
|
| 129 |
+
frames = [Image.new("RGB", (2, 2), color) for color in ("white", "black")]
|
| 130 |
+
|
| 131 |
+
overlay._save_cached_frames(tmp_path, frames, [["a"], ["b"]])
|
| 132 |
+
|
| 133 |
+
assert (tmp_path / "0.png").is_file()
|
| 134 |
+
assert (tmp_path / "1.png").is_file()
|
| 135 |
+
assert json.loads((tmp_path / "labels.json").read_text()) == [["a"], ["b"]]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def test_stamp_frames_uses_raw_sam3_boxes_and_does_not_mutate_inputs(
|
| 139 |
+
monkeypatch, tmp_path
|
| 140 |
+
):
|
| 141 |
+
monkeypatch.setattr(
|
| 142 |
+
overlay, "overlay_frame_cache_dir", lambda *args: tmp_path / "cache"
|
| 143 |
+
)
|
| 144 |
+
monkeypatch.setattr(
|
| 145 |
+
overlay.perceive,
|
| 146 |
+
"cache_or_load",
|
| 147 |
+
lambda *args: ({"geometry": "fake"}, "cache"),
|
| 148 |
+
)
|
| 149 |
+
monkeypatch.setattr(
|
| 150 |
+
overlay.gm,
|
| 151 |
+
"instance_source_track_ids",
|
| 152 |
+
lambda geometry: {"chair": [[10]], "table": [[20]]},
|
| 153 |
+
)
|
| 154 |
+
monkeypatch.setattr(
|
| 155 |
+
overlay,
|
| 156 |
+
"_load_raw_sam3_boxes",
|
| 157 |
+
lambda *args: {
|
| 158 |
+
"chair": {0: {10: (0.10, 0.10, 0.30, 0.30)}},
|
| 159 |
+
"table": {1: {20: (0.50, 0.50, 0.25, 0.25)}},
|
| 160 |
+
},
|
| 161 |
+
)
|
| 162 |
+
frames = [Image.new("RGB", (40, 40), "white"), Image.new("RGB", (40, 40), "white")]
|
| 163 |
+
before = frames[0].copy()
|
| 164 |
+
|
| 165 |
+
stamped, visible = overlay.stamp_frames(
|
| 166 |
+
frames,
|
| 167 |
+
_EXPLICIT_CODE,
|
| 168 |
+
"scene",
|
| 169 |
+
"metric",
|
| 170 |
+
"uniform",
|
| 171 |
+
"tracking",
|
| 172 |
+
2,
|
| 173 |
+
use_cache=True,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
assert visible == [["chair 1"], ["table 1"]]
|
| 177 |
+
assert stamped[0].getpixel((8, 8)) != before.getpixel((8, 8))
|
| 178 |
+
assert frames[0].tobytes() == before.tobytes()
|
| 179 |
+
cached = overlay._load_cached_frames(tmp_path / "cache", 2)
|
| 180 |
+
assert cached is not None
|
| 181 |
+
assert cached[1] == visible
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def test_stamp_frames_serves_complete_cache_without_loading_dependencies(
|
| 185 |
+
monkeypatch, tmp_path
|
| 186 |
+
):
|
| 187 |
+
cache_dir = tmp_path / "cache"
|
| 188 |
+
overlay._save_cached_frames(
|
| 189 |
+
cache_dir, [Image.new("RGB", (2, 2), "red")], [["cached"]]
|
| 190 |
+
)
|
| 191 |
+
monkeypatch.setattr(overlay, "overlay_frame_cache_dir", lambda *args: cache_dir)
|
| 192 |
+
monkeypatch.setattr(
|
| 193 |
+
overlay.perceive,
|
| 194 |
+
"cache_or_load",
|
| 195 |
+
lambda *args: pytest.fail("cache hit should not touch perception"),
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
stamped, visible = overlay.stamp_frames(
|
| 199 |
+
[Image.new("RGB", (2, 2), "white")],
|
| 200 |
+
{},
|
| 201 |
+
"scene",
|
| 202 |
+
"metric",
|
| 203 |
+
"uniform",
|
| 204 |
+
"tracking",
|
| 205 |
+
1,
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
assert visible == [["cached"]]
|
| 209 |
+
assert stamped[0].getpixel((0, 0)) == (255, 0, 0)
|
tests/test_C/test_overlay_launch.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for harness/C/overlay_launch.py -- cache pregeneration orchestration."""
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
from harness.C import overlay_launch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_available_cpu_count_honors_positive_environment(monkeypatch):
|
| 9 |
+
monkeypatch.setenv("VSI_CPU_WORKERS", "3")
|
| 10 |
+
assert overlay_launch._available_cpu_count() == 3
|
| 11 |
+
monkeypatch.setenv("VSI_CPU_WORKERS", "0")
|
| 12 |
+
with pytest.raises(ValueError, match="positive"):
|
| 13 |
+
overlay_launch._available_cpu_count()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_has_dependencies_requires_spatial_code_and_sam3_cache(monkeypatch, tmp_path):
|
| 17 |
+
cache = tmp_path / "sam3.pt"
|
| 18 |
+
monkeypatch.setattr(
|
| 19 |
+
overlay_launch.spatial_codes,
|
| 20 |
+
"load_spatial_code",
|
| 21 |
+
lambda *args: ({"objects": {}}, "code.json"),
|
| 22 |
+
)
|
| 23 |
+
monkeypatch.setattr(
|
| 24 |
+
"encoder.config.sam3_cache_file",
|
| 25 |
+
lambda *args: cache,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
assert (
|
| 29 |
+
overlay_launch._has_dependencies("scene", "metric", "uniform", "tracking", 32)
|
| 30 |
+
is False
|
| 31 |
+
)
|
| 32 |
+
cache.write_text("cache")
|
| 33 |
+
assert (
|
| 34 |
+
overlay_launch._has_dependencies("scene", "metric", "uniform", "tracking", 32)
|
| 35 |
+
is True
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_has_dependencies_treats_missing_code_as_ineligible(monkeypatch):
|
| 40 |
+
def missing(*args):
|
| 41 |
+
raise FileNotFoundError("missing code")
|
| 42 |
+
|
| 43 |
+
monkeypatch.setattr(overlay_launch.spatial_codes, "load_spatial_code", missing)
|
| 44 |
+
assert (
|
| 45 |
+
overlay_launch._has_dependencies("scene", "metric", "uniform", "tracking", 32)
|
| 46 |
+
is False
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_launch_skips_missing_and_already_cached_without_pool(
|
| 51 |
+
monkeypatch, tmp_path, capsys
|
| 52 |
+
):
|
| 53 |
+
monkeypatch.setattr(
|
| 54 |
+
overlay_launch,
|
| 55 |
+
"_has_dependencies",
|
| 56 |
+
lambda scene, *args: scene != "missing",
|
| 57 |
+
)
|
| 58 |
+
monkeypatch.setattr(
|
| 59 |
+
overlay_launch.overlay,
|
| 60 |
+
"overlay_frame_cache_dir",
|
| 61 |
+
lambda scene, *args: tmp_path / scene,
|
| 62 |
+
)
|
| 63 |
+
monkeypatch.setattr(
|
| 64 |
+
overlay_launch.overlay,
|
| 65 |
+
"_load_cached_frames",
|
| 66 |
+
lambda cache_dir, frame_count: (
|
| 67 |
+
([object()], [[]]) if cache_dir.name == "cached" else None
|
| 68 |
+
),
|
| 69 |
+
)
|
| 70 |
+
monkeypatch.setattr(
|
| 71 |
+
overlay_launch.overlay,
|
| 72 |
+
"overlay_spatial_code_path",
|
| 73 |
+
lambda scene, *args: tmp_path / scene / "overlay-code.json",
|
| 74 |
+
)
|
| 75 |
+
(tmp_path / "cached").mkdir()
|
| 76 |
+
(tmp_path / "cached" / "overlay-code.json").write_text("{}")
|
| 77 |
+
monkeypatch.setattr(
|
| 78 |
+
overlay_launch.mp,
|
| 79 |
+
"get_context",
|
| 80 |
+
lambda *_: pytest.fail("no pending scenes should avoid multiprocessing"),
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
succeeded, failed, missing = overlay_launch.launch(
|
| 84 |
+
"metric", "uniform", "tracking", 32, ["missing", "cached"]
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
assert succeeded == []
|
| 88 |
+
assert failed == []
|
| 89 |
+
assert missing == ["missing"]
|
| 90 |
+
output = capsys.readouterr().out
|
| 91 |
+
assert "missing a code or SAM3 cache" in output
|
| 92 |
+
assert "already cached" in output
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def test_launch_does_not_skip_frames_cache_when_overlay_code_is_missing(
|
| 96 |
+
monkeypatch, tmp_path
|
| 97 |
+
):
|
| 98 |
+
monkeypatch.setattr(overlay_launch, "_has_dependencies", lambda scene, *args: True)
|
| 99 |
+
monkeypatch.setattr(
|
| 100 |
+
overlay_launch.overlay,
|
| 101 |
+
"overlay_frame_cache_dir",
|
| 102 |
+
lambda scene, *args: tmp_path / scene,
|
| 103 |
+
)
|
| 104 |
+
monkeypatch.setattr(
|
| 105 |
+
overlay_launch.overlay,
|
| 106 |
+
"_load_cached_frames",
|
| 107 |
+
lambda cache_dir, frame_count: ([object()], [[]]),
|
| 108 |
+
)
|
| 109 |
+
monkeypatch.setattr(
|
| 110 |
+
overlay_launch.overlay,
|
| 111 |
+
"overlay_spatial_code_path",
|
| 112 |
+
lambda scene, *args: tmp_path / scene / "missing-overlay-code.json",
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
calls = []
|
| 116 |
+
|
| 117 |
+
class FakePool:
|
| 118 |
+
def __init__(self, workers):
|
| 119 |
+
self.workers = workers
|
| 120 |
+
|
| 121 |
+
def __enter__(self):
|
| 122 |
+
return self
|
| 123 |
+
|
| 124 |
+
def __exit__(self, *exc):
|
| 125 |
+
return False
|
| 126 |
+
|
| 127 |
+
def map(self, fn, tasks):
|
| 128 |
+
calls.extend(tasks)
|
| 129 |
+
return [(task[0], True, None) for task in tasks]
|
| 130 |
+
|
| 131 |
+
class FakeContext:
|
| 132 |
+
def Pool(self, workers):
|
| 133 |
+
return FakePool(workers)
|
| 134 |
+
|
| 135 |
+
monkeypatch.setattr(overlay_launch.mp, "get_context", lambda *_: FakeContext())
|
| 136 |
+
|
| 137 |
+
succeeded, failed, missing = overlay_launch.launch(
|
| 138 |
+
"metric", "uniform", "tracking", 32, ["frames_only"], workers=1
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
assert calls == [("frames_only", "metric", "uniform", "tracking", 32)]
|
| 142 |
+
assert succeeded == ["frames_only"]
|
| 143 |
+
assert failed == []
|
| 144 |
+
assert missing == []
|
tests/test_D/__init__.py
ADDED
|
File without changes
|
tests/test_D/conftest.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared, self-contained import setup for harness.D tests."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import sys
|
| 6 |
+
import tempfile
|
| 7 |
+
import types
|
| 8 |
+
|
| 9 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 10 |
+
if str(ROOT) not in sys.path:
|
| 11 |
+
sys.path.insert(0, str(ROOT))
|
| 12 |
+
|
| 13 |
+
# D imports the official VSI scorer eagerly. Provide a tiny interface-compatible scorer
|
| 14 |
+
# and manifest so unit tests do not depend on /root/data being mounted.
|
| 15 |
+
_FIXTURES = Path(tempfile.mkdtemp(prefix="test_D_"))
|
| 16 |
+
_SCORER = _FIXTURES / "utils.py"
|
| 17 |
+
_SCORER.write_text(
|
| 18 |
+
'MCA_QUESTION_TYPES = ("object_rel_direction_easy", "object_rel_direction_medium", "object_rel_direction_hard", "object_rel_distance", "route_planning", "obj_appearance_order")\n'
|
| 19 |
+
'NA_QUESTION_TYPES = ("object_abs_distance", "object_counting", "object_size_estimation", "room_size_estimation")\n'
|
| 20 |
+
'METRICS_FOR_MCA = {"exact_match": None}\n'
|
| 21 |
+
'METRICS_FOR_NA = {"MRA:.5:.95:.05": None}\n'
|
| 22 |
+
"def vsibench_process_results(doc, results):\n"
|
| 23 |
+
' metric = "exact_match" if doc["question_type"] in MCA_QUESTION_TYPES else "MRA:.5:.95:.05"\n'
|
| 24 |
+
' score = float(str(results[0]).strip() == str(doc["ground_truth"]).strip())\n'
|
| 25 |
+
' return {"vsibench_score": {metric: score}}\n'
|
| 26 |
+
)
|
| 27 |
+
_MANIFEST = _FIXTURES / "test.jsonl"
|
| 28 |
+
_MANIFEST.write_text(
|
| 29 |
+
'{"id": 7, "scene_name": "13c3e046d7", "dataset": "scannet", "question_type": "object_counting", "question": "How many chairs?", "options": null, "ground_truth": "1"}\n'
|
| 30 |
+
)
|
| 31 |
+
os.environ["HARNESS_OFFICIAL_EVAL"] = str(_SCORER)
|
| 32 |
+
os.environ["SYMBOLIC_OFFICIAL_EVAL"] = str(_SCORER)
|
| 33 |
+
sys.path.insert(0, str(_FIXTURES))
|
| 34 |
+
os.environ["VSI_JSONL"] = str(_MANIFEST)
|
| 35 |
+
|
| 36 |
+
# OpenCV is only needed when the optional frame arm actually decodes a video. Frame
|
| 37 |
+
# unit tests monkeypatch that boundary and never call this placeholder.
|
| 38 |
+
if "cv2" not in sys.modules:
|
| 39 |
+
cv2 = types.ModuleType("cv2")
|
| 40 |
+
cv2.CAP_PROP_FPS = 5
|
| 41 |
+
sys.modules["cv2"] = cv2
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def pytest_configure(config):
|
| 45 |
+
config.option.importmode = "importlib"
|
tests/test_D/test_D.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for harness/D/__init__.py -- shared config constants."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from harness import A, B, D
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_spatial_code_formats_reuse_harness_b_vocabulary():
|
| 9 |
+
assert D.SPATIAL_CODE_FORMATS == B.SPATIAL_CODE_FORMATS
|
| 10 |
+
assert D.DEFAULT_SPATIAL_CODE_FORMAT in D.SPATIAL_CODE_FORMATS
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_reuses_harness_a_model_paths_and_generation_protocol():
|
| 14 |
+
assert D.MODEL_PATHS is A.MODEL_PATHS
|
| 15 |
+
assert D.MAX_NEW_TOKENS == A.MAX_NEW_TOKENS
|
| 16 |
+
assert D.DO_SAMPLE == A.DO_SAMPLE
|
| 17 |
+
assert D.TEMPERATURE == A.TEMPERATURE
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def test_results_dir_defaults_under_root_results():
|
| 21 |
+
assert D.RESULTS_DIR == Path("/root/results/D")
|
tests/test_D/test_init.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for harness/D/__init__.py -- shared config constants."""
|
| 2 |
+
|
| 3 |
+
from harness import A, B, D
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_spatial_code_formats_reuse_harness_b_vocabulary():
|
| 7 |
+
assert D.SPATIAL_CODE_FORMATS == B.SPATIAL_CODE_FORMATS
|
| 8 |
+
assert D.DEFAULT_SPATIAL_CODE_FORMAT in D.SPATIAL_CODE_FORMATS
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_reuses_harness_a_model_paths_and_generation_protocol():
|
| 12 |
+
assert D.MODEL_PATHS is A.MODEL_PATHS
|
| 13 |
+
assert D.MAX_NEW_TOKENS == A.MAX_NEW_TOKENS
|
| 14 |
+
assert D.DO_SAMPLE == A.DO_SAMPLE
|
| 15 |
+
assert D.TEMPERATURE == A.TEMPERATURE
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_results_dir_defaults_under_workspace_results():
|
| 19 |
+
assert D.RESULTS_DIR == D.WORKSPACE_ROOT / "results" / "D"
|
tests/test_D/test_launch.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for harness/D/launch.py -- multi-GPU scene sharding across workers."""
|
| 2 |
+
|
| 3 |
+
from harness.D import launch
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_launcher_imports():
|
| 7 |
+
assert callable(launch.main)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class _FakeRun:
|
| 11 |
+
rows = [{"id": 2}, {"id": 5}]
|
| 12 |
+
|
| 13 |
+
@staticmethod
|
| 14 |
+
def results_dir_for(*args, **kwargs):
|
| 15 |
+
return args[3]
|
| 16 |
+
|
| 17 |
+
@classmethod
|
| 18 |
+
def load_questions(cls, scene=None):
|
| 19 |
+
return list(cls.rows)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_launch_skips_scene_already_fully_answered(tmp_path, capsys, monkeypatch):
|
| 23 |
+
scene = "scene-d"
|
| 24 |
+
monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun)
|
| 25 |
+
|
| 26 |
+
scene_dir = tmp_path / scene
|
| 27 |
+
scene_dir.mkdir()
|
| 28 |
+
for row in _FakeRun.rows:
|
| 29 |
+
(scene_dir / f"{row['id']}.json").write_text("{}")
|
| 30 |
+
|
| 31 |
+
launch.launch("qwen3.5-2b", "explicit", [scene], results_dir=tmp_path)
|
| 32 |
+
|
| 33 |
+
output = capsys.readouterr().out
|
| 34 |
+
assert "skipped" in output
|
| 35 |
+
assert "DONE: 1 ok, 0 failed" in output
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch):
|
| 39 |
+
scene = "scene-d"
|
| 40 |
+
monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun)
|
| 41 |
+
scene_dir = tmp_path / scene
|
| 42 |
+
scene_dir.mkdir()
|
| 43 |
+
for row in _FakeRun.rows:
|
| 44 |
+
(scene_dir / f"{row['id']}.json").write_text("{}")
|
| 45 |
+
|
| 46 |
+
monkeypatch.setattr(launch, "visible_gpus", lambda: [])
|
| 47 |
+
monkeypatch.setattr(
|
| 48 |
+
launch.mp,
|
| 49 |
+
"get_context",
|
| 50 |
+
lambda *_: (_ for _ in ()).throw(
|
| 51 |
+
RuntimeError("rebuild correctly reached worker dispatch")
|
| 52 |
+
),
|
| 53 |
+
)
|
| 54 |
+
try:
|
| 55 |
+
launch.launch(
|
| 56 |
+
"qwen3.5-2b", "explicit", [scene], results_dir=tmp_path, rebuild=True
|
| 57 |
+
)
|
| 58 |
+
except RuntimeError as exc:
|
| 59 |
+
assert "rebuild correctly reached worker dispatch" in str(exc)
|
| 60 |
+
else:
|
| 61 |
+
raise AssertionError("expected rebuild to force scene into the pending path")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_scenes_is_subset_of_vsi_bench_scenes_with_ground_truth_coverage(monkeypatch):
|
| 65 |
+
monkeypatch.setattr("harness.A.launch.scenes", lambda: ["a", "b", "c"])
|
| 66 |
+
monkeypatch.setattr(launch, "ground_truth_scenes", lambda: ["b", "c", "z"])
|
| 67 |
+
assert launch.scenes() == ["b", "c"]
|
tests/test_D/test_prompts.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for harness/D/prompts.py -- ground-truth spatial-code-as-text prompt construction."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from harness.A.prompts import MCA_QUESTION_TYPES, NA_QUESTION_TYPES
|
| 8 |
+
from harness.D import prompts as code_prompts
|
| 9 |
+
|
| 10 |
+
_CODE = {
|
| 11 |
+
"objects": {"chair": {"count": 1}},
|
| 12 |
+
"room": {"floor area": "10.0 square meters"},
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_na_question_prompt_embeds_the_spatial_code_as_text_and_a_post_prompt():
|
| 17 |
+
prompt = code_prompts.build_prompt(_CODE, "object_counting", "How many chairs?")
|
| 18 |
+
assert prompt.startswith(code_prompts.PRE_PROMPT)
|
| 19 |
+
assert json.dumps(_CODE, indent=1) in prompt
|
| 20 |
+
assert prompt.endswith(code_prompts.NA_POST_PROMPT)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_mca_question_prompt_includes_options_and_matches_harness_a_post_prompt():
|
| 24 |
+
prompt = code_prompts.build_prompt(
|
| 25 |
+
_CODE, "object_rel_distance", "Which is closest?", ["A. sofa", "B. table"]
|
| 26 |
+
)
|
| 27 |
+
assert "Options:\nA. sofa\nB. table" in prompt
|
| 28 |
+
assert prompt.endswith(code_prompts.MCA_POST_PROMPT)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_mca_question_requires_options():
|
| 32 |
+
with pytest.raises(ValueError):
|
| 33 |
+
code_prompts.build_prompt(_CODE, "route_planning", "Which way?", None)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_unknown_question_type_rejected():
|
| 37 |
+
with pytest.raises(ValueError):
|
| 38 |
+
code_prompts.build_prompt(_CODE, "not_a_real_type", "?", None)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_no_frames_or_video_language_in_pre_prompt():
|
| 42 |
+
assert "frame" not in code_prompts.PRE_PROMPT.lower()
|
| 43 |
+
assert "video" not in code_prompts.PRE_PROMPT.lower()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@pytest.mark.parametrize("question_type", NA_QUESTION_TYPES)
|
| 47 |
+
def test_every_na_question_type_builds(question_type):
|
| 48 |
+
prompt = code_prompts.build_prompt(_CODE, question_type, "q?")
|
| 49 |
+
assert prompt.startswith(code_prompts.PRE_PROMPT)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@pytest.mark.parametrize("question_type", MCA_QUESTION_TYPES)
|
| 53 |
+
def test_every_mca_question_type_builds(question_type):
|
| 54 |
+
prompt = code_prompts.build_prompt(_CODE, question_type, "q?", ["A. x", "B. y"])
|
| 55 |
+
assert prompt.startswith(code_prompts.PRE_PROMPT)
|
tests/test_D/test_run.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for harness/D/run.py -- result-record shape and result-file writing."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
|
| 5 |
+
from harness import D
|
| 6 |
+
from harness.D import run as harness_run
|
| 7 |
+
|
| 8 |
+
_FAKE_ANSWER = {
|
| 9 |
+
"prompt_text": "<rendered chat template>",
|
| 10 |
+
"answer_text": "4",
|
| 11 |
+
"answer_raw": "<|im_start|>assistant\n4<|im_end|>",
|
| 12 |
+
"input_token_count": 2558,
|
| 13 |
+
"vision_input_shapes": {"mm_token_type_ids": [1, 2558]},
|
| 14 |
+
"output_token_ids": [19, 151645],
|
| 15 |
+
"output_token_count": 2,
|
| 16 |
+
"hit_token_limit": False,
|
| 17 |
+
"eos_token_ids": [151645],
|
| 18 |
+
"generation_seconds": 0.65,
|
| 19 |
+
"device": "cuda",
|
| 20 |
+
"dtype": "bfloat16",
|
| 21 |
+
"library_versions": {"transformers": "5.14.1", "torch": "2.13.0+cu130"},
|
| 22 |
+
"generation_config": {
|
| 23 |
+
"max_new_tokens": 16,
|
| 24 |
+
"do_sample": False,
|
| 25 |
+
"temperature": 0.0,
|
| 26 |
+
"top_p": None,
|
| 27 |
+
"top_k": None,
|
| 28 |
+
"enable_thinking": False,
|
| 29 |
+
},
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
_FAKE_ROW = {
|
| 33 |
+
"id": 7,
|
| 34 |
+
"scene_name": "scene0001_00",
|
| 35 |
+
"dataset": "scannet",
|
| 36 |
+
"question_type": "object_counting",
|
| 37 |
+
"question": "How many chairs?",
|
| 38 |
+
"options": None,
|
| 39 |
+
"ground_truth": "4",
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
_FAKE_CODE_INFO = {
|
| 43 |
+
"protocol": "extended",
|
| 44 |
+
"spatial_code_format": "explicit",
|
| 45 |
+
"spatial_code_path": "/workspace/data/spatial codes/ground truth/explicit/scene0001_00.json",
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_results_dir_for_matches_model_protocol_and_format_only():
|
| 50 |
+
root = harness_run.results_dir_for("qwen3.5-4b", "extended", "compact")
|
| 51 |
+
assert root == D.RESULTS_DIR / "qwen3.5-4b" / "code" / "extended" / "compact"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_results_dir_for_isolates_frames_and_truncated_budget_arms():
|
| 55 |
+
root = harness_run.results_dir_for(
|
| 56 |
+
"qwen3.5-4b",
|
| 57 |
+
"truncated/64",
|
| 58 |
+
"explicit",
|
| 59 |
+
frames=True,
|
| 60 |
+
frame_selection="uniform",
|
| 61 |
+
frame_count=32,
|
| 62 |
+
)
|
| 63 |
+
assert root == (
|
| 64 |
+
D.RESULTS_DIR
|
| 65 |
+
/ "qwen3.5-4b"
|
| 66 |
+
/ "code + frames"
|
| 67 |
+
/ "truncated"
|
| 68 |
+
/ "64"
|
| 69 |
+
/ "explicit"
|
| 70 |
+
/ "uniform"
|
| 71 |
+
/ "32"
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_build_record_describes_frames_plus_ground_truth_condition():
|
| 76 |
+
code_info = {
|
| 77 |
+
**_FAKE_CODE_INFO,
|
| 78 |
+
"protocol": "512",
|
| 79 |
+
"frames": True,
|
| 80 |
+
"frame_selection": "uniform",
|
| 81 |
+
"frame_count": 32,
|
| 82 |
+
"video_path": "/fake/scene.mp4",
|
| 83 |
+
"frame_indices": [0, 30],
|
| 84 |
+
"frame_timestamps": [0.0, 1.0],
|
| 85 |
+
}
|
| 86 |
+
record = harness_run._build_record(
|
| 87 |
+
_FAKE_ROW,
|
| 88 |
+
"full prompt text",
|
| 89 |
+
_FAKE_ANSWER,
|
| 90 |
+
"MRA:.5:.95:.05",
|
| 91 |
+
1.0,
|
| 92 |
+
"qwen3.5-4b",
|
| 93 |
+
"/root/models/qwen3.5-4b",
|
| 94 |
+
code_info,
|
| 95 |
+
)
|
| 96 |
+
assert record["condition"] == "512:explicit:frames:uniform:32"
|
| 97 |
+
assert record["frames"] is True
|
| 98 |
+
assert record["video_path"] == "/fake/scene.mp4"
|
| 99 |
+
assert record["frame_indices"] == [0, 30]
|
| 100 |
+
assert record["frame_timestamps_seconds"] == [0.0, 1.0]
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def test_results_dir_for_honors_explicit_override(tmp_path):
|
| 104 |
+
root = harness_run.results_dir_for("qwen3.5-4b", "base", "explicit", tmp_path)
|
| 105 |
+
assert root == tmp_path
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_build_record_preserves_every_field_untruncated():
|
| 109 |
+
record = harness_run._build_record(
|
| 110 |
+
_FAKE_ROW,
|
| 111 |
+
"full prompt text",
|
| 112 |
+
_FAKE_ANSWER,
|
| 113 |
+
"MRA:.5:.95:.05",
|
| 114 |
+
1.0,
|
| 115 |
+
"qwen3.5-4b",
|
| 116 |
+
"/root/models/qwen3.5-4b",
|
| 117 |
+
_FAKE_CODE_INFO,
|
| 118 |
+
)
|
| 119 |
+
assert record["question"] == "How many chairs?"
|
| 120 |
+
assert record["full_prompt"] == "full prompt text"
|
| 121 |
+
assert record["rendered_prompt"] == _FAKE_ANSWER["prompt_text"]
|
| 122 |
+
assert record["answer_given"] == "4"
|
| 123 |
+
assert record["spatial_code_format"] == "explicit"
|
| 124 |
+
assert record["spatial_code_path"] == _FAKE_CODE_INFO["spatial_code_path"]
|
| 125 |
+
# No depth/tracking/input_selection -- ground truth has no such axis. frames/
|
| 126 |
+
# frame_selection/frame_count/video_path/frame_indices/frame_timestamps_seconds DO
|
| 127 |
+
# exist on every record (the frames+ground-truth-code arm's fields), null here since
|
| 128 |
+
# _FAKE_CODE_INFO has no "frames" key -- same present-but-null pattern as
|
| 129 |
+
# reasoning_text on a base-protocol record.
|
| 130 |
+
assert record["condition"] == "extended:explicit"
|
| 131 |
+
assert record["protocol"] == "extended"
|
| 132 |
+
assert record["frames"] is False
|
| 133 |
+
assert record["frame_selection"] is None
|
| 134 |
+
assert record["frame_count"] is None
|
| 135 |
+
assert record["video_path"] is None
|
| 136 |
+
assert "input_selection" not in record
|
| 137 |
+
assert "depth" not in record
|
| 138 |
+
assert "tracking" not in record
|
| 139 |
+
assert record["metric"] == "MRA:.5:.95:.05"
|
| 140 |
+
assert record["score"] == 1.0
|
| 141 |
+
assert record["scene"] == "scene0001_00"
|
| 142 |
+
assert record["question_id"] == 7
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def test_write_question_result_writes_one_json_file_per_question(tmp_path):
|
| 146 |
+
path, record = harness_run.write_question_result(
|
| 147 |
+
_FAKE_ROW,
|
| 148 |
+
"full prompt text",
|
| 149 |
+
_FAKE_ANSWER,
|
| 150 |
+
"MRA:.5:.95:.05",
|
| 151 |
+
1.0,
|
| 152 |
+
"qwen3.5-4b",
|
| 153 |
+
"/root/models/qwen3.5-4b",
|
| 154 |
+
_FAKE_CODE_INFO,
|
| 155 |
+
results_dir=tmp_path,
|
| 156 |
+
)
|
| 157 |
+
assert path == tmp_path / "scene0001_00" / "7.json"
|
| 158 |
+
on_disk = json.loads(path.read_text())
|
| 159 |
+
assert on_disk == record
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def test_build_record_carries_reasoning_fields_when_forced():
|
| 163 |
+
extended_answer = {
|
| 164 |
+
**_FAKE_ANSWER,
|
| 165 |
+
"reasoning_text": "long reasoning about the spatial code",
|
| 166 |
+
"reasoning_raw": "long reasoning about the spatial code<|im_end|>",
|
| 167 |
+
"reasoning_token_ids": list(range(50)),
|
| 168 |
+
"reasoning_token_count": 50,
|
| 169 |
+
"reasoning_hit_limit": True,
|
| 170 |
+
"forced": True,
|
| 171 |
+
"forced_input_token_count": 2510,
|
| 172 |
+
}
|
| 173 |
+
record = harness_run._build_record(
|
| 174 |
+
_FAKE_ROW,
|
| 175 |
+
"full prompt text",
|
| 176 |
+
extended_answer,
|
| 177 |
+
"MRA:.5:.95:.05",
|
| 178 |
+
1.0,
|
| 179 |
+
"qwen3.5-4b",
|
| 180 |
+
"/root/models/qwen3.5-4b",
|
| 181 |
+
_FAKE_CODE_INFO,
|
| 182 |
+
)
|
| 183 |
+
assert record["reasoning_text"] == "long reasoning about the spatial code"
|
| 184 |
+
assert record["forced"] is True
|
| 185 |
+
assert record["forced_input_token_count"] == 2510
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def test_build_record_defaults_reasoning_fields_when_absent():
|
| 189 |
+
record = harness_run._build_record(
|
| 190 |
+
_FAKE_ROW,
|
| 191 |
+
"full prompt text",
|
| 192 |
+
_FAKE_ANSWER,
|
| 193 |
+
"MRA:.5:.95:.05",
|
| 194 |
+
1.0,
|
| 195 |
+
"qwen3.5-4b",
|
| 196 |
+
"/root/models/qwen3.5-4b",
|
| 197 |
+
_FAKE_CODE_INFO,
|
| 198 |
+
)
|
| 199 |
+
assert record["reasoning_token_count"] is None
|
| 200 |
+
assert record["forced"] is False
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def test_run_code_transform_hook_replaces_the_loaded_code(monkeypatch, tmp_path):
|
| 204 |
+
"""The corruption module's entry point: the hook's return value is what the
|
| 205 |
+
prompt is built from, and passing no hook keeps behavior identical."""
|
| 206 |
+
scene = "13c3e046d7"
|
| 207 |
+
seen = {}
|
| 208 |
+
|
| 209 |
+
def fake_load(scene_id, spatial_code_format):
|
| 210 |
+
return {"objects": {"chair": {"count": 1}}}, f"/fake/{scene_id}.json"
|
| 211 |
+
|
| 212 |
+
class FakeAdapter:
|
| 213 |
+
model_path = "/fake/model"
|
| 214 |
+
|
| 215 |
+
def answer_extended(self, frames, prompt, **kwargs):
|
| 216 |
+
seen["prompt"] = prompt
|
| 217 |
+
return {
|
| 218 |
+
"prompt_text": prompt,
|
| 219 |
+
"answer_text": "1",
|
| 220 |
+
"answer_raw": "1",
|
| 221 |
+
"input_token_count": 1,
|
| 222 |
+
"vision_input_shapes": {},
|
| 223 |
+
"output_token_ids": [1],
|
| 224 |
+
"output_token_count": 1,
|
| 225 |
+
"hit_token_limit": False,
|
| 226 |
+
"eos_token_ids": [1],
|
| 227 |
+
"generation_seconds": 0.0,
|
| 228 |
+
"device": "cpu",
|
| 229 |
+
"dtype": "float32",
|
| 230 |
+
"library_versions": {},
|
| 231 |
+
"generation_config": {},
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
monkeypatch.setattr(harness_run.spatial_codes, "load_spatial_code", fake_load)
|
| 235 |
+
replacement = {"objects": {"table": {"count": 9}}}
|
| 236 |
+
results = harness_run.run(
|
| 237 |
+
"qwen3.5-2b",
|
| 238 |
+
scene=scene,
|
| 239 |
+
adapter=FakeAdapter(),
|
| 240 |
+
write_results=False,
|
| 241 |
+
limit=1,
|
| 242 |
+
code_transform=lambda code, scene_id, fmt: replacement,
|
| 243 |
+
)
|
| 244 |
+
assert results
|
| 245 |
+
assert '"table"' in seen["prompt"]
|
| 246 |
+
assert '"chair"' not in seen["prompt"]
|
tests/test_D/test_spatial_codes.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for harness/D/spatial_codes.py -- loading on-disk ground-truth spatial codes."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from harness.D import spatial_codes
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_load_spatial_code_rejects_unknown_format():
|
| 11 |
+
with pytest.raises(ValueError):
|
| 12 |
+
spatial_codes.load_spatial_code("scene", "bogus")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_load_spatial_code_raises_clearly_when_missing(tmp_path, monkeypatch):
|
| 16 |
+
monkeypatch.setattr(
|
| 17 |
+
spatial_codes,
|
| 18 |
+
"ground_truth_spatial_code_path",
|
| 19 |
+
lambda *a, **k: str(tmp_path / "missing.json"),
|
| 20 |
+
)
|
| 21 |
+
with pytest.raises(FileNotFoundError):
|
| 22 |
+
spatial_codes.load_spatial_code("scene", "explicit")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_load_spatial_code_returns_dict_and_path(tmp_path, monkeypatch):
|
| 26 |
+
fixture = tmp_path / "scene1.json"
|
| 27 |
+
fixture.write_text(json.dumps({"objects": {}, "room": {}}))
|
| 28 |
+
monkeypatch.setattr(
|
| 29 |
+
spatial_codes, "ground_truth_spatial_code_path", lambda *a, **k: str(fixture)
|
| 30 |
+
)
|
| 31 |
+
code, path = spatial_codes.load_spatial_code("scene1", "compact")
|
| 32 |
+
assert code == {"objects": {}, "room": {}}
|
| 33 |
+
assert path == str(fixture)
|
tests/test_D/test_sweep.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for harness/D/sweep.py -- multi-config sweep planning."""
|
| 2 |
+
|
| 3 |
+
from harness.A import models as vlm_models
|
| 4 |
+
from harness.D import sweep
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_build_plan_covers_every_combination():
|
| 8 |
+
plan = sweep.build_plan(["qwen3.5-2b", "qwen3.5-4b"], ["explicit", "compact"])
|
| 9 |
+
assert len(plan) == 4
|
| 10 |
+
assert ("qwen3.5-2b", "explicit") in plan
|
| 11 |
+
assert ("qwen3.5-4b", "compact") in plan
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_build_plan_with_all_registered_models():
|
| 15 |
+
plan = sweep.build_plan(list(vlm_models.available_models()), ["explicit"])
|
| 16 |
+
assert len(plan) == len(vlm_models.available_models())
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_default_spatial_code_formats_cover_both_when_not_restricted():
|
| 20 |
+
# This session's execution-design decision: D sweeps both formats by default
|
| 21 |
+
# (unlike a hypothetical "winning cell only" design) since ground truth costs
|
| 22 |
+
# nothing extra to build across formats.
|
| 23 |
+
import argparse
|
| 24 |
+
|
| 25 |
+
parser = argparse.ArgumentParser()
|
| 26 |
+
parser.add_argument("--spatial-code-formats", default="all")
|
| 27 |
+
args = parser.parse_args([])
|
| 28 |
+
assert args.spatial_code_formats == "all"
|
tests/test_D/test_symbolic_eval.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for harness/D/symbolic_eval.py -- symbolic solver run directly on ground-truth
|
| 2 |
+
spatial codes, no VLM, written through symbolic.run's own writer into
|
| 3 |
+
results/symbolic/ground truth/<format>/... (not a separate results/D/... location)."""
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
|
| 7 |
+
from harness.D import symbolic_eval
|
| 8 |
+
|
| 9 |
+
_FAKE_CODE = {
|
| 10 |
+
"spatial code schema": {},
|
| 11 |
+
"objects": {
|
| 12 |
+
"chair": [
|
| 13 |
+
{
|
| 14 |
+
"3D oriented bounding box": {
|
| 15 |
+
"3D oriented bounding box center coordinates": [0, 0, 0.5],
|
| 16 |
+
"3D oriented bounding box dimensions": [1, 1, 1],
|
| 17 |
+
"3D oriented bounding box orientation unit vectors": [
|
| 18 |
+
[1, 0, 0],
|
| 19 |
+
[0, 1, 0],
|
| 20 |
+
[0, 0, 1],
|
| 21 |
+
],
|
| 22 |
+
},
|
| 23 |
+
"first visible time": 0.0,
|
| 24 |
+
}
|
| 25 |
+
]
|
| 26 |
+
},
|
| 27 |
+
"room": {"floor boundary polygons": []},
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _fake_load(scene_id, spatial_code_format):
|
| 32 |
+
return _FAKE_CODE, f"/fake/{scene_id}.json"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_run_answers_real_questions_for_a_real_ground_truth_scene(
|
| 36 |
+
tmp_path, monkeypatch
|
| 37 |
+
):
|
| 38 |
+
scene = "13c3e046d7"
|
| 39 |
+
monkeypatch.setattr(symbolic_eval.spatial_codes, "load_spatial_code", _fake_load)
|
| 40 |
+
|
| 41 |
+
results = symbolic_eval.run(
|
| 42 |
+
spatial_code_format="compact",
|
| 43 |
+
scene=scene,
|
| 44 |
+
results_dir=tmp_path,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
assert results
|
| 48 |
+
for record in results:
|
| 49 |
+
assert record["scene"] == scene
|
| 50 |
+
assert record["result_path"] is not None
|
| 51 |
+
|
| 52 |
+
written = list(tmp_path.rglob("*.json"))
|
| 53 |
+
assert len(written) == len(results)
|
| 54 |
+
native_record = json.loads(written[0].read_text())
|
| 55 |
+
assert native_record["model"] == "symbolic"
|
| 56 |
+
assert native_record["condition"] == "ground truth:compact"
|
| 57 |
+
assert native_record["scene"] == scene
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def test_run_selects_ground_truth_spatial_codes_when_writing(tmp_path, monkeypatch):
|
| 61 |
+
scene = "13c3e046d7"
|
| 62 |
+
monkeypatch.setattr(symbolic_eval.spatial_codes, "load_spatial_code", _fake_load)
|
| 63 |
+
called = {"select": False, "format": None}
|
| 64 |
+
|
| 65 |
+
def fake_select(spatial_code_format):
|
| 66 |
+
called["select"] = True
|
| 67 |
+
called["format"] = spatial_code_format
|
| 68 |
+
|
| 69 |
+
monkeypatch.setattr(
|
| 70 |
+
symbolic_eval.symbolic_run, "select_ground_truth_spatial_codes", fake_select
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
symbolic_eval.run(spatial_code_format="explicit", scene=scene, results_dir=tmp_path)
|
| 74 |
+
|
| 75 |
+
assert called["select"] is True
|
| 76 |
+
assert called["format"] == "explicit"
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_run_does_not_write_when_write_results_is_false(tmp_path, monkeypatch):
|
| 80 |
+
scene = "13c3e046d7"
|
| 81 |
+
monkeypatch.setattr(symbolic_eval.spatial_codes, "load_spatial_code", _fake_load)
|
| 82 |
+
called = {"select": False}
|
| 83 |
+
monkeypatch.setattr(
|
| 84 |
+
symbolic_eval.symbolic_run,
|
| 85 |
+
"select_ground_truth_spatial_codes",
|
| 86 |
+
lambda *a, **k: called.__setitem__("select", True),
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
results = symbolic_eval.run(
|
| 90 |
+
spatial_code_format="compact",
|
| 91 |
+
scene=scene,
|
| 92 |
+
results_dir=tmp_path,
|
| 93 |
+
write_results=False,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
assert called["select"] is False
|
| 97 |
+
assert results
|
| 98 |
+
for record in results:
|
| 99 |
+
assert record["result_path"] is None
|
| 100 |
+
assert list(tmp_path.rglob("*.json")) == []
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def test_run_forwards_results_dir_to_symbolic_writer(tmp_path, monkeypatch):
|
| 104 |
+
scene = "13c3e046d7"
|
| 105 |
+
monkeypatch.setattr(symbolic_eval.spatial_codes, "load_spatial_code", _fake_load)
|
| 106 |
+
seen = {}
|
| 107 |
+
|
| 108 |
+
def fake_write(scene_id, pq, code, results_dir=None):
|
| 109 |
+
seen["results_dir"] = results_dir
|
| 110 |
+
return tmp_path / "fake.json"
|
| 111 |
+
|
| 112 |
+
monkeypatch.setattr(symbolic_eval.symbolic_run, "write_question_result", fake_write)
|
| 113 |
+
|
| 114 |
+
symbolic_eval.run(spatial_code_format="compact", scene=scene, results_dir=tmp_path)
|
| 115 |
+
|
| 116 |
+
assert seen["results_dir"] == tmp_path
|
tests/test_E/__init__.py
ADDED
|
File without changes
|
tests/test_E/conftest.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared import setup for this test package."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 7 |
+
if str(ROOT) not in sys.path:
|
| 8 |
+
sys.path.insert(0, str(ROOT))
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def pytest_configure(config):
|
| 12 |
+
config.option.importmode = "importlib"
|
tests/test_E/test_E.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for harness/E package configuration."""
|
| 2 |
+
|
| 3 |
+
import importlib
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
from harness import E
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_blind_floor_reuses_harness_a_public_config():
|
| 10 |
+
assert E.PROTOCOLS == ("base", "extended")
|
| 11 |
+
assert "qwen3.5-2b" in E.MODEL_PATHS
|
| 12 |
+
assert E.RESULTS_DIR == Path("/root/results/E")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_results_dir_can_be_overridden_by_environment(monkeypatch, tmp_path):
|
| 16 |
+
monkeypatch.setenv("VSI_HARNESS_E_RESULTS_DIR", str(tmp_path / "E"))
|
| 17 |
+
reloaded = importlib.reload(E)
|
| 18 |
+
assert reloaded.RESULTS_DIR == tmp_path / "E"
|
| 19 |
+
monkeypatch.delenv("VSI_HARNESS_E_RESULTS_DIR")
|
| 20 |
+
importlib.reload(E)
|
tests/test_E/test_launch.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for harness/E/launch.py -- multi-GPU scene sharding for the blind floor."""
|
| 2 |
+
|
| 3 |
+
from harness.E import launch
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_launcher_imports():
|
| 7 |
+
assert callable(launch.main)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class _FakeRun:
|
| 11 |
+
rows = [{"id": 4}, {"id": 9}]
|
| 12 |
+
|
| 13 |
+
@staticmethod
|
| 14 |
+
def results_dir_for(model, protocol, results_dir=None):
|
| 15 |
+
return results_dir
|
| 16 |
+
|
| 17 |
+
@classmethod
|
| 18 |
+
def load_questions(cls, scene=None):
|
| 19 |
+
return list(cls.rows)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_launch_skips_scene_already_fully_answered(tmp_path, capsys, monkeypatch):
|
| 23 |
+
scene = "scene-e"
|
| 24 |
+
monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun)
|
| 25 |
+
|
| 26 |
+
scene_dir = tmp_path / scene
|
| 27 |
+
scene_dir.mkdir()
|
| 28 |
+
for row in _FakeRun.rows:
|
| 29 |
+
(scene_dir / f"{row['id']}.json").write_text("{}")
|
| 30 |
+
|
| 31 |
+
launch.launch("qwen3.5-2b", [scene], results_dir=tmp_path)
|
| 32 |
+
|
| 33 |
+
output = capsys.readouterr().out
|
| 34 |
+
assert "skipped" in output
|
| 35 |
+
assert "DONE: 1 ok, 0 failed" in output
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch):
|
| 39 |
+
scene = "scene-e"
|
| 40 |
+
monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun)
|
| 41 |
+
scene_dir = tmp_path / scene
|
| 42 |
+
scene_dir.mkdir()
|
| 43 |
+
for row in _FakeRun.rows:
|
| 44 |
+
(scene_dir / f"{row['id']}.json").write_text("{}")
|
| 45 |
+
|
| 46 |
+
monkeypatch.setattr(launch, "visible_gpus", lambda: [])
|
| 47 |
+
monkeypatch.setattr(
|
| 48 |
+
launch.mp,
|
| 49 |
+
"get_context",
|
| 50 |
+
lambda *_: (_ for _ in ()).throw(
|
| 51 |
+
RuntimeError("rebuild correctly reached worker dispatch")
|
| 52 |
+
),
|
| 53 |
+
)
|
| 54 |
+
try:
|
| 55 |
+
launch.launch("qwen3.5-2b", [scene], results_dir=tmp_path, rebuild=True)
|
| 56 |
+
except RuntimeError as exc:
|
| 57 |
+
assert "rebuild correctly reached worker dispatch" in str(exc)
|
| 58 |
+
else:
|
| 59 |
+
raise AssertionError("expected rebuild to force scene into the pending path")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_launch_protocols_use_separate_result_roots():
|
| 63 |
+
run = launch._load_run_module()
|
| 64 |
+
base = run.results_dir_for("qwen3.5-2b", "base")
|
| 65 |
+
extended = run.results_dir_for("qwen3.5-2b", "extended")
|
| 66 |
+
assert base != extended
|