AntonioJun commited on
Commit
e8055cf
·
verified ·
1 Parent(s): b952b59

Replace tests with local workspace contents

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tests/__init__.py +0 -0
  2. tests/conftest.py +48 -0
  3. tests/test_A/__init__.py +0 -0
  4. tests/test_A/conftest.py +12 -0
  5. tests/test_A/test_A.py +68 -0
  6. tests/test_A/test_frames.py +79 -0
  7. tests/test_A/test_init.py +62 -0
  8. tests/test_A/test_launch.py +90 -0
  9. tests/test_A/test_models.py +114 -0
  10. tests/test_A/test_prompts.py +57 -0
  11. tests/test_A/test_run.py +231 -0
  12. tests/test_A/test_sweep.py +69 -0
  13. tests/test_B/__init__.py +0 -0
  14. tests/test_B/conftest.py +12 -0
  15. tests/test_B/test_B.py +35 -0
  16. tests/test_B/test_init.py +35 -0
  17. tests/test_B/test_launch.py +85 -0
  18. tests/test_B/test_prompts.py +146 -0
  19. tests/test_B/test_run.py +191 -0
  20. tests/test_B/test_spatial_codes.py +48 -0
  21. tests/test_B/test_sweep.py +67 -0
  22. tests/test_C/__init__.py +0 -0
  23. tests/test_C/conftest.py +12 -0
  24. tests/test_C/test_C.py +27 -0
  25. tests/test_C/test_init.py +27 -0
  26. tests/test_C/test_launch.py +69 -0
  27. tests/test_C/test_prompts.py +70 -0
  28. tests/test_C/test_run.py +180 -0
  29. tests/test_C/test_sweep.py +67 -0
  30. tests/test_F/__init__.py +0 -0
  31. tests/test_F/conftest.py +12 -0
  32. tests/test_F/test_F.py +20 -0
  33. tests/test_F/test_launch.py +7 -0
  34. tests/test_F/test_run.py +19 -0
  35. tests/test_F/test_sweep.py +14 -0
  36. tests/test_analysis/__init__.py +0 -0
  37. tests/test_analysis/conftest.py +118 -0
  38. tests/test_analysis/test_A_reports.py +11 -0
  39. tests/test_analysis/test_B_reports.py +11 -0
  40. tests/test_analysis/test_C_reports.py +11 -0
  41. tests/test_analysis/test_F_reports.py +15 -0
  42. tests/test_analysis/test_analysis.py +12 -0
  43. tests/test_analysis/test_letters_reports.py +55 -0
  44. tests/test_backup.py +47 -0
  45. tests/test_encoder/conftest.py +13 -0
  46. tests/test_encoder/test_adapters.py +311 -0
  47. tests/test_encoder/test_config.py +44 -0
  48. tests/test_encoder/test_encoder.py +73 -0
  49. tests/test_encoder/test_geometric.py +387 -0
  50. tests/test_encoder/test_init.py +7 -0
tests/__init__.py ADDED
File without changes
tests/conftest.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Global test setup that keeps unit tests independent of optional native packages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib.util
6
+ import sys
7
+ import types
8
+ from pathlib import Path
9
+
10
+ ROOT = Path(__file__).resolve().parents[1]
11
+ if str(ROOT) not in sys.path:
12
+ sys.path.insert(0, str(ROOT))
13
+
14
+
15
+ class _FakeCapture:
16
+ def __init__(self, path):
17
+ self.path = path
18
+
19
+ def get(self, prop):
20
+ return 0.0
21
+
22
+ def release(self):
23
+ pass
24
+
25
+
26
+ if importlib.util.find_spec("cv2") is None and "cv2" not in sys.modules:
27
+ cv2 = types.ModuleType("cv2")
28
+ cv2.CAP_PROP_FPS = 5
29
+ cv2.INTER_NEAREST = 0
30
+ cv2.MORPH_CLOSE = 3
31
+ cv2.RETR_EXTERNAL = 0
32
+ cv2.RETR_CCOMP = 2
33
+ cv2.CHAIN_APPROX_SIMPLE = 0
34
+ cv2.GC_PR_BGD = 2
35
+ cv2.GC_PR_FGD = 3
36
+ cv2.GC_FGD = 1
37
+ cv2.GC_INIT_WITH_MASK = 1
38
+ cv2.VideoCapture = _FakeCapture
39
+ cv2.resize = lambda image, size, interpolation=None: image
40
+ cv2.erode = lambda image, kernel, iterations=1: image
41
+ cv2.dilate = lambda image, kernel, iterations=1: image
42
+ cv2.morphologyEx = lambda image, op, kernel: image
43
+ cv2.findContours = lambda image, mode, method: ([], None)
44
+ cv2.approxPolyDP = lambda contour, epsilon, closed: contour
45
+ cv2.contourArea = lambda contour: 0
46
+ cv2.imread = lambda path: None
47
+ cv2.grabCut = lambda *args, **kwargs: None
48
+ sys.modules["cv2"] = cv2
tests/test_A/__init__.py ADDED
File without changes
tests/test_A/conftest.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared import setup for harness.A tests."""
2
+
3
+ from pathlib import Path
4
+ import sys
5
+
6
+ ROOT = Path(__file__).resolve().parents[2]
7
+ if str(ROOT) not in sys.path:
8
+ sys.path.insert(0, str(ROOT))
9
+
10
+
11
+ def pytest_configure(config):
12
+ config.option.importmode = "importlib"
tests/test_A/test_A.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/A/__init__.py -- shared config constants."""
2
+
3
+ from argparse import ArgumentParser, Namespace
4
+ from pathlib import Path
5
+
6
+ import pytest
7
+
8
+ from harness import A
9
+
10
+
11
+ def test_thinking_mode_resolves_default_budgets():
12
+ args = Namespace(reasoning_budget=None, force_budget=None)
13
+ A.resolve_protocol_budgets(ArgumentParser(), args)
14
+ assert args.reasoning_budget == A.EXTENDED_MAX_NEW_TOKENS
15
+ assert args.force_budget == A.MAX_NEW_TOKENS
16
+
17
+
18
+ def test_explicit_budget_overrides_are_preserved():
19
+ args = Namespace(reasoning_budget=1024, force_budget=8)
20
+ A.resolve_protocol_budgets(ArgumentParser(), args)
21
+ assert args.reasoning_budget == 1024
22
+ assert args.force_budget == 8
23
+
24
+
25
+ @pytest.mark.parametrize("flag", ["reasoning_budget", "force_budget"])
26
+ def test_nonpositive_budget_overrides_are_rejected(flag):
27
+ args = Namespace(reasoning_budget=None, force_budget=None)
28
+ setattr(args, flag, 0)
29
+ with pytest.raises(SystemExit):
30
+ A.resolve_protocol_budgets(ArgumentParser(), args)
31
+
32
+
33
+ def test_generation_protocol_matches_vsibench_yaml():
34
+ # thinking-in-space/lmms_eval/tasks/vsibench/vsibench.yaml generation_kwargs.
35
+ assert A.MAX_NEW_TOKENS == 16
36
+ assert A.TEMPERATURE == 0.0
37
+ assert A.DO_SAMPLE is False
38
+
39
+
40
+ def test_thinking_generation_protocol():
41
+ assert A.EXTENDED_MAX_NEW_TOKENS == 2048
42
+ assert A.EXTENDED_MAX_NEW_TOKENS > A.MAX_NEW_TOKENS
43
+ assert isinstance(A.FORCE_ANSWER_PROMPT, str) and A.FORCE_ANSWER_PROMPT.strip()
44
+
45
+
46
+ def test_frame_selections_match_inference_vocabulary():
47
+ from inference import SAM3_FRAME_SELECTIONS
48
+
49
+ assert A.FRAME_SELECTIONS == SAM3_FRAME_SELECTIONS
50
+
51
+
52
+ def test_default_frame_selection_is_a_valid_selection():
53
+ assert A.DEFAULT_FRAME_SELECTION in A.FRAME_SELECTIONS
54
+
55
+
56
+ def test_model_paths_cover_every_registered_model():
57
+ assert set(A.MODEL_PATHS) == {
58
+ "qwen3.5-4b",
59
+ "qwen3.5-2b",
60
+ "internvl3.5-4b",
61
+ "internvl3.5-2b",
62
+ }
63
+ for path in A.MODEL_PATHS.values():
64
+ assert path.parent == A.MODELS_ROOT
65
+
66
+
67
+ def test_results_dir_defaults_under_root_results():
68
+ assert A.RESULTS_DIR == Path("/root/results/A")
tests/test_A/test_frames.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/A/frames.py -- uniform/selective frame sampling."""
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from harness.A import frames as frame_sampling
7
+
8
+
9
+ def test_sample_frames_rejects_unknown_selection(tmp_path):
10
+ video = tmp_path / "scene.mp4"
11
+ video.write_bytes(b"not a real video")
12
+ with pytest.raises(ValueError):
13
+ frame_sampling.sample_frames(str(video), 8, "random")
14
+
15
+
16
+ def test_sample_frames_rejects_nonpositive_frame_count(tmp_path):
17
+ video = tmp_path / "scene.mp4"
18
+ video.write_bytes(b"not a real video")
19
+ with pytest.raises(ValueError):
20
+ frame_sampling.sample_frames(str(video), 0, "uniform")
21
+
22
+
23
+ def test_sample_frames_rejects_missing_video(tmp_path):
24
+ with pytest.raises(FileNotFoundError):
25
+ frame_sampling.sample_frames(str(tmp_path / "missing.mp4"), 8, "uniform")
26
+
27
+
28
+ def test_sample_frames_returns_pil_images_in_order(tmp_path, monkeypatch):
29
+ video = tmp_path / "scene.mp4"
30
+ video.write_bytes(b"not a real video")
31
+ fake_frames = np.stack(
32
+ [np.full((4, 4, 3), value, dtype=np.uint8) for value in (10, 20, 30)]
33
+ )
34
+ monkeypatch.setattr(
35
+ frame_sampling,
36
+ "_sample_video_frames",
37
+ lambda path, count, selection: (fake_frames, np.array([0.0, 1.0, 2.0])),
38
+ )
39
+
40
+ class _UnreadableCapture:
41
+ def get(self, prop):
42
+ return 0.0
43
+
44
+ def release(self):
45
+ pass
46
+
47
+ monkeypatch.setattr(
48
+ frame_sampling.cv2, "VideoCapture", lambda path: _UnreadableCapture()
49
+ )
50
+ result, timestamps, indices = frame_sampling.sample_frames(str(video), 3, "uniform")
51
+ assert len(result) == 3
52
+ assert np.array(result[0])[0, 0, 0] == 10
53
+ assert np.array(result[2])[0, 0, 0] == 30
54
+ assert timestamps == [0.0, 1.0, 2.0]
55
+ # fps falls back to 1.0 for the fake (unreadable) video, so index == round(t * 1.0) == t.
56
+ assert indices == [0, 1, 2]
57
+
58
+
59
+ def test_sample_frames_derives_indices_from_real_fps(tmp_path, monkeypatch):
60
+ video = tmp_path / "scene.mp4"
61
+ video.write_bytes(b"not a real video")
62
+ fake_frames = np.stack([np.full((2, 2, 3), 1, dtype=np.uint8)] * 3)
63
+ monkeypatch.setattr(
64
+ frame_sampling,
65
+ "_sample_video_frames",
66
+ lambda path, count, selection: (fake_frames, np.array([0.0, 0.5, 1.0])),
67
+ )
68
+
69
+ class _FakeCapture:
70
+ def get(self, prop):
71
+ return 30.0
72
+
73
+ def release(self):
74
+ pass
75
+
76
+ monkeypatch.setattr(frame_sampling.cv2, "VideoCapture", lambda path: _FakeCapture())
77
+ _, timestamps, indices = frame_sampling.sample_frames(str(video), 3, "uniform")
78
+ assert timestamps == [0.0, 0.5, 1.0]
79
+ assert indices == [0, 15, 30]
tests/test_A/test_init.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/A/__init__.py -- shared config constants."""
2
+
3
+ from pathlib import Path
4
+
5
+ from harness import A
6
+
7
+
8
+ def test_generation_protocol_matches_vsibench_yaml():
9
+ # thinking-in-space/lmms_eval/tasks/vsibench/vsibench.yaml generation_kwargs.
10
+ assert A.MAX_NEW_TOKENS == 16
11
+ assert A.TEMPERATURE == 0.0
12
+ assert A.DO_SAMPLE is False
13
+
14
+
15
+ def test_thinking_generation_protocol():
16
+ assert A.EXTENDED_MAX_NEW_TOKENS == 2048
17
+ assert A.EXTENDED_MAX_NEW_TOKENS > A.MAX_NEW_TOKENS
18
+ assert isinstance(A.FORCE_ANSWER_PROMPT, str) and A.FORCE_ANSWER_PROMPT.strip()
19
+
20
+
21
+ def test_frame_selections_match_inference_vocabulary():
22
+ from inference import SAM3_FRAME_SELECTIONS
23
+
24
+ assert A.FRAME_SELECTIONS == SAM3_FRAME_SELECTIONS
25
+
26
+
27
+ def test_default_frame_selection_is_a_valid_selection():
28
+ assert A.DEFAULT_FRAME_SELECTION in A.FRAME_SELECTIONS
29
+
30
+
31
+ def test_model_paths_cover_every_registered_model():
32
+ assert set(A.MODEL_PATHS) == {
33
+ "qwen3.5-4b",
34
+ "qwen3.5-2b",
35
+ "internvl3.5-4b",
36
+ "internvl3.5-2b",
37
+ }
38
+ for path in A.MODEL_PATHS.values():
39
+ assert path.parent == A.MODELS_ROOT
40
+
41
+
42
+ def test_results_dir_defaults_under_root_results():
43
+ assert A.RESULTS_DIR == Path("/root/results/A")
44
+
45
+
46
+ def test_question_protocol_policy_is_hardcoded_by_group():
47
+ assert A.question_group("object_counting") == "numerical"
48
+ assert A.protocol_for_question("object_counting") == "base"
49
+ assert A.question_group("route_planning") == "multiple_choice"
50
+ assert A.protocol_for_question("route_planning") == "thinking"
51
+
52
+
53
+ def test_every_known_question_type_has_one_policy_group():
54
+ for question_type in A.NUMERICAL_QUESTION_TYPES:
55
+ assert (
56
+ A.protocol_for_question(question_type) == A.QUESTION_PROTOCOLS["numerical"]
57
+ )
58
+ for question_type in A.MULTIPLE_CHOICE_QUESTION_TYPES:
59
+ assert (
60
+ A.protocol_for_question(question_type)
61
+ == A.QUESTION_PROTOCOLS["multiple_choice"]
62
+ )
tests/test_A/test_launch.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/A/launch.py -- multi-GPU scene sharding across workers."""
2
+
3
+ import pytest
4
+
5
+ from harness.A import launch
6
+
7
+
8
+ def test_launcher_imports():
9
+ assert callable(launch.main)
10
+
11
+
12
+ def test_scenes_dedups_and_preserves_order(tmp_path, monkeypatch):
13
+ manifest = tmp_path / "questions.jsonl"
14
+ rows = [
15
+ '{"scene_name": "scene-a"}',
16
+ '{"scene_name": "scene-b"}',
17
+ '{"scene_name": "scene-a"}',
18
+ ]
19
+ manifest.write_text("\n".join(rows) + "\n")
20
+ monkeypatch.setattr(launch, "JSONL", manifest)
21
+ assert launch.scenes() == ["scene-a", "scene-b"]
22
+
23
+
24
+ class _FakeRun:
25
+ rows = [{"id": 1}, {"id": 2}]
26
+
27
+ @staticmethod
28
+ def results_dir_for(
29
+ model, protocol, frame_selection, frame_count, results_dir=None
30
+ ):
31
+ return results_dir
32
+
33
+ @classmethod
34
+ def load_questions(cls, scene=None):
35
+ return list(cls.rows)
36
+
37
+
38
+ def test_launch_skips_scene_already_fully_answered(tmp_path, capsys, monkeypatch):
39
+ scene = "scene-a"
40
+ monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun)
41
+
42
+ scene_dir = tmp_path / scene
43
+ scene_dir.mkdir()
44
+ for row in _FakeRun.rows:
45
+ (scene_dir / f"{row['id']}.json").write_text("{}")
46
+
47
+ launch.launch("qwen3.5-2b", "uniform", 16, [scene], results_dir=tmp_path)
48
+
49
+ output = capsys.readouterr().out
50
+ assert "skipped" in output
51
+ assert "DONE: 1 ok, 0 failed" in output
52
+
53
+
54
+ def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch):
55
+ scene = "scene-a"
56
+ monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun)
57
+ scene_dir = tmp_path / scene
58
+ scene_dir.mkdir()
59
+ for row in _FakeRun.rows:
60
+ (scene_dir / f"{row['id']}.json").write_text("{}")
61
+
62
+ monkeypatch.setattr(launch, "visible_gpus", lambda: [])
63
+
64
+ # Only assert it treats the scene as pending (doesn't take the all-skipped early
65
+ # return); actually spawning workers needs a real model/GPU, exercised by the live
66
+ # harness.A.launch smoke run instead of the unit suite.
67
+ monkeypatch.setattr(
68
+ launch.mp,
69
+ "get_context",
70
+ lambda *_: (_ for _ in ()).throw(
71
+ RuntimeError("rebuild correctly reached worker dispatch")
72
+ ),
73
+ )
74
+ try:
75
+ launch.launch(
76
+ "qwen3.5-2b", "uniform", 16, [scene], results_dir=tmp_path, rebuild=True
77
+ )
78
+ except RuntimeError as exc:
79
+ assert "rebuild correctly reached worker dispatch" in str(exc)
80
+ else:
81
+ raise AssertionError("expected rebuild to force scene into the pending path")
82
+
83
+
84
+ def test_launch_rejects_scene_with_no_questions(monkeypatch, tmp_path):
85
+ class EmptyRun(_FakeRun):
86
+ rows = []
87
+
88
+ monkeypatch.setattr(launch, "_load_run_module", lambda: EmptyRun)
89
+ with pytest.raises(ValueError, match="no questions found"):
90
+ launch.launch("qwen3.5-2b", "uniform", 16, ["missing"], results_dir=tmp_path)
tests/test_A/test_models.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/A/models.py -- VLM adapter registry and prompt assembly.
2
+
3
+ Deliberately excludes any test that loads real model weights or calls .generate() --
4
+ those require the GPU and downloaded checkpoints and are exercised via harness.A.run
5
+ smoke runs instead, not the unit suite.
6
+ """
7
+
8
+ import numpy as np
9
+ import pytest
10
+
11
+ from harness import A
12
+ from harness.A import models as vlm_models
13
+
14
+
15
+ def test_all_four_models_are_registered():
16
+ assert vlm_models.available_models() == (
17
+ "internvl3.5-2b",
18
+ "internvl3.5-4b",
19
+ "qwen3.5-2b",
20
+ "qwen3.5-4b",
21
+ )
22
+
23
+
24
+ def test_get_adapter_binds_the_correct_checkpoint_path():
25
+ adapter = vlm_models.get_adapter("qwen3.5-4b")
26
+ assert adapter.model_path == A.MODEL_PATHS["qwen3.5-4b"]
27
+ assert isinstance(adapter, vlm_models.QwenVLAdapter)
28
+
29
+
30
+ def test_get_adapter_returns_the_right_class_per_model():
31
+ assert isinstance(vlm_models.get_adapter("qwen3.5-2b"), vlm_models.QwenVLAdapter)
32
+ assert isinstance(
33
+ vlm_models.get_adapter("internvl3.5-4b"), vlm_models.InternVLAdapter
34
+ )
35
+
36
+
37
+ def test_get_adapter_rejects_unknown_model():
38
+ with pytest.raises(KeyError):
39
+ vlm_models.get_adapter("not-a-real-model")
40
+
41
+
42
+ def test_internvl_adapter_disables_per_frame_tiling():
43
+ # Otherwise InternVL's default per-image dynamic tiling (~3300 tokens/frame) blows
44
+ # past this checkpoint's 40960-token context window at just 16 frames.
45
+ assert vlm_models.InternVLAdapter.chat_template_kwargs == {"crop_to_patches": False}
46
+
47
+
48
+ def test_numbered_content_labels_every_frame_in_order():
49
+ frames = ["frame0", "frame1", "frame2"]
50
+ content = vlm_models._numbered_content(frames, "What is in the room?")
51
+ assert content[0] == {"type": "text", "text": "Frame 1:"}
52
+ assert content[1] == {"type": "image", "image": "frame0"}
53
+ assert content[-1] == {"type": "text", "text": "What is in the room?"}
54
+ image_items = [item for item in content if item["type"] == "image"]
55
+ assert [item["image"] for item in image_items] == frames
56
+
57
+
58
+ def test_numbered_content_handles_zero_frames():
59
+ content = vlm_models._numbered_content([], "question only")
60
+ assert content == [{"type": "text", "text": "question only"}]
61
+
62
+
63
+ def test_adapter_answer_before_load_model_raises():
64
+ adapter = vlm_models.get_adapter("qwen3.5-2b")
65
+ with pytest.raises(RuntimeError):
66
+ adapter.answer(["frame"], "question")
67
+
68
+
69
+ def test_adapter_answer_extended_before_load_model_raises():
70
+ adapter = vlm_models.get_adapter("qwen3.5-2b")
71
+ with pytest.raises(RuntimeError):
72
+ adapter.answer_extended(["frame"], "question")
73
+
74
+
75
+ def test_every_adapter_implements_answer_extended():
76
+ for model in vlm_models.available_models():
77
+ adapter = vlm_models.get_adapter(model)
78
+ assert callable(adapter.answer_extended)
79
+
80
+
81
+ def test_decode_new_tokens_preserves_clean_and_raw_text():
82
+ adapter = vlm_models.get_adapter("qwen3.5-2b")
83
+
84
+ class Processor:
85
+ def decode(self, token_ids, skip_special_tokens):
86
+ if skip_special_tokens:
87
+ return "step one, step two, answer B"
88
+ return "<think>step one, step two</think>B<eos>"
89
+
90
+ adapter.processor = Processor()
91
+ token_ids, hit_limit, text, raw = adapter._decode_new_tokens(
92
+ np.array([[10, 11, 21, 22, 2]]), 2, 2048, [2]
93
+ )
94
+ assert token_ids == [21, 22, 2]
95
+ assert hit_limit is False
96
+ assert text == "step one, step two, answer B"
97
+ assert raw == "<think>step one, step two</think>B<eos>"
98
+
99
+
100
+ def test_unload_clears_model_and_processor():
101
+ adapter = vlm_models.get_adapter("qwen3.5-2b")
102
+ adapter.model = object()
103
+ adapter.processor = object()
104
+ adapter.unload()
105
+ assert adapter.model is None
106
+ assert adapter.processor is None
107
+
108
+
109
+ def test_native_video_content_uses_one_video_item():
110
+ content = vlm_models._numbered_content("/data/scene.mp4", "What is in the room?")
111
+ assert content == [
112
+ {"type": "video", "video": "/data/scene.mp4"},
113
+ {"type": "text", "text": "What is in the room?"},
114
+ ]
tests/test_A/test_prompts.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/A/prompts.py -- VSI-Bench prompt construction."""
2
+
3
+ import pytest
4
+
5
+ from harness.A import prompts as vsi_prompts
6
+
7
+
8
+ def test_na_question_prompt_matches_vsibench_protocol():
9
+ prompt = vsi_prompts.build_prompt("object_counting", "How many chairs?")
10
+ assert prompt == (
11
+ "These are frames of a video.\n"
12
+ "How many chairs?\n"
13
+ "Please answer the question using a single word or phrase."
14
+ )
15
+
16
+
17
+ def test_mca_question_prompt_matches_vsibench_protocol():
18
+ prompt = vsi_prompts.build_prompt(
19
+ "object_rel_distance", "Which is closest?", ["A. sofa", "B. table"]
20
+ )
21
+ assert prompt == (
22
+ "These are frames of a video.\n"
23
+ "Which is closest?\n"
24
+ "Options:\nA. sofa\nB. table\n"
25
+ "Answer with the option's letter from the given choices directly."
26
+ )
27
+
28
+
29
+ def test_mca_question_requires_options():
30
+ with pytest.raises(ValueError):
31
+ vsi_prompts.build_prompt("route_planning", "Which way?", None)
32
+
33
+
34
+ def test_unknown_question_type_rejected():
35
+ with pytest.raises(ValueError):
36
+ vsi_prompts.build_prompt("not_a_real_type", "?", None)
37
+
38
+
39
+ @pytest.mark.parametrize("question_type", vsi_prompts.NA_QUESTION_TYPES)
40
+ def test_every_na_question_type_builds_without_options(question_type):
41
+ prompt = vsi_prompts.build_prompt(question_type, "q?")
42
+ assert prompt.startswith(vsi_prompts.PRE_PROMPT)
43
+ assert vsi_prompts.STEP_BY_STEP_REASONING_PROMPT in prompt
44
+ assert prompt.endswith(vsi_prompts.NA_POST_PROMPT)
45
+
46
+
47
+ @pytest.mark.parametrize("question_type", vsi_prompts.MCA_QUESTION_TYPES)
48
+ def test_every_mca_question_type_builds_with_options(question_type):
49
+ prompt = vsi_prompts.build_prompt(question_type, "q?", ["A. x", "B. y"])
50
+ assert prompt.startswith(vsi_prompts.PRE_PROMPT)
51
+ assert vsi_prompts.STEP_BY_STEP_REASONING_PROMPT in prompt
52
+ assert prompt.endswith(vsi_prompts.MCA_POST_PROMPT)
53
+
54
+
55
+ def test_video_prompt_names_native_video():
56
+ prompt = vsi_prompts.build_prompt("object_counting", "How many chairs?", video=True)
57
+ assert prompt.startswith("This is a video.\n")
tests/test_A/test_run.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/A/run.py -- question loading, scoring, and result-file writing."""
2
+
3
+ import json
4
+
5
+ import pytest
6
+
7
+ from harness import A
8
+ from harness.A import run as harness_run
9
+
10
+ _FAKE_ANSWER = {
11
+ "prompt_text": "<rendered chat template>",
12
+ "answer_text": "4",
13
+ "answer_raw": "<|im_start|>assistant\n4<|im_end|>",
14
+ "input_token_count": 123,
15
+ "vision_input_shapes": {"pixel_values": [512, 1536]},
16
+ "output_token_ids": [19, 151645],
17
+ "output_token_count": 2,
18
+ "hit_token_limit": False,
19
+ "eos_token_ids": [151645],
20
+ "generation_seconds": 1.234,
21
+ "device": "cuda",
22
+ "dtype": "bfloat16",
23
+ "library_versions": {"transformers": "5.14.1", "torch": "2.13.0+cu130"},
24
+ "generation_config": {
25
+ "max_new_tokens": 16,
26
+ "do_sample": False,
27
+ "temperature": 0.0,
28
+ "top_p": None,
29
+ "top_k": None,
30
+ },
31
+ }
32
+
33
+ _FAKE_ROW = {
34
+ "id": 7,
35
+ "scene_name": "scene0001_00",
36
+ "dataset": "scannet",
37
+ "question_type": "object_counting",
38
+ "question": "How many chairs?",
39
+ "options": None,
40
+ "ground_truth": "4",
41
+ }
42
+
43
+ _FAKE_FRAME_INFO = {
44
+ "protocol": "base",
45
+ "video_path": "/root/data/VSI-Bench/scannet/scene0001_00.mp4",
46
+ "frame_timestamps": [0.0, 1.0, 2.0],
47
+ "frame_indices": [0, 30, 60],
48
+ "frame_selection": "uniform",
49
+ "frame_count": 16,
50
+ }
51
+
52
+
53
+ def test_load_questions_reads_every_row(tmp_path):
54
+ jsonl = tmp_path / "test.jsonl"
55
+ jsonl.write_text(
56
+ "\n".join(
57
+ json.dumps({"id": i, "scene_name": f"scene{i}", "question": "q"})
58
+ for i in range(3)
59
+ )
60
+ )
61
+ rows = harness_run.load_questions(jsonl)
62
+ assert [r["id"] for r in rows] == [0, 1, 2]
63
+
64
+
65
+ def test_load_questions_filters_by_scene(tmp_path):
66
+ jsonl = tmp_path / "test.jsonl"
67
+ jsonl.write_text(
68
+ "\n".join(
69
+ json.dumps({"id": i, "scene_name": "a" if i < 2 else "b", "question": "q"})
70
+ for i in range(4)
71
+ )
72
+ )
73
+ rows = harness_run.load_questions(jsonl, scene="b")
74
+ assert [r["id"] for r in rows] == [2, 3]
75
+
76
+
77
+ def test_load_questions_respects_limit(tmp_path):
78
+ jsonl = tmp_path / "test.jsonl"
79
+ jsonl.write_text(
80
+ "\n".join(
81
+ json.dumps({"id": i, "scene_name": "a", "question": "q"}) for i in range(5)
82
+ )
83
+ )
84
+ rows = harness_run.load_questions(jsonl, limit=2)
85
+ assert [r["id"] for r in rows] == [0, 1]
86
+
87
+
88
+ def test_scalar_score_returns_metric_name_and_value():
89
+ doc = {"question_type": "object_counting", "ground_truth": "4"}
90
+ score_doc = harness_run.vsi_official_eval.vsibench_process_results(doc, ["4"])[
91
+ "vsibench_score"
92
+ ]
93
+ metric_name, value = harness_run._scalar_score("object_counting", score_doc)
94
+ assert metric_name == "MRA:.5:.95:.05"
95
+ assert value == 1.0
96
+
97
+
98
+ def test_scalar_score_rejects_unknown_question_type():
99
+ with pytest.raises(ValueError):
100
+ harness_run._scalar_score("not_a_real_type", {})
101
+
102
+
103
+ def test_results_dir_for_matches_established_dimension_nesting():
104
+ root = harness_run.results_dir_for("qwen3.5-4b", "base", "selective", 32)
105
+ assert root == A.RESULTS_DIR / "qwen3.5-4b" / "selective" / "32"
106
+
107
+
108
+ def test_results_dir_for_keeps_protocols_together():
109
+ base = harness_run.results_dir_for("qwen3.5-4b", "base", "selective", 32)
110
+ extended = harness_run.results_dir_for("qwen3.5-4b", "thinking", "selective", 32)
111
+ assert base == extended
112
+
113
+
114
+ def test_results_dir_for_honors_explicit_override(tmp_path):
115
+ assert (
116
+ harness_run.results_dir_for("qwen3.5-4b", "base", "uniform", 16, tmp_path)
117
+ == tmp_path
118
+ )
119
+
120
+
121
+ def test_build_record_preserves_every_field_untruncated():
122
+ record = harness_run._build_record(
123
+ _FAKE_ROW,
124
+ "full prompt text",
125
+ _FAKE_ANSWER,
126
+ "MRA:.5:.95:.05",
127
+ 1.0,
128
+ "qwen3.5-4b",
129
+ "/root/models/qwen3.5-4b",
130
+ _FAKE_FRAME_INFO,
131
+ )
132
+ assert record["question"] == "How many chairs?"
133
+ assert record["full_prompt"] == "full prompt text"
134
+ assert record["rendered_prompt"] == _FAKE_ANSWER["prompt_text"]
135
+ assert record["answer_given"] == "4"
136
+ assert record["answer_raw"] == _FAKE_ANSWER["answer_raw"]
137
+ assert record["output_token_ids"] == [19, 151645]
138
+ assert record["output_token_count"] == 2
139
+ assert record["hit_token_limit"] is False
140
+ assert record["generation_config"] == _FAKE_ANSWER["generation_config"]
141
+ assert record["frame_timestamps_seconds"] == [0.0, 1.0, 2.0]
142
+ assert record["frame_indices"] == [0, 30, 60]
143
+ assert record["video_path"] == _FAKE_FRAME_INFO["video_path"]
144
+ assert record["device"] == "cuda"
145
+ assert record["dtype"] == "bfloat16"
146
+ assert record["library_versions"] == _FAKE_ANSWER["library_versions"]
147
+ assert record["vision_input_shapes"] == {"pixel_values": [512, 1536]}
148
+ assert record["generation_seconds"] == 1.234
149
+ assert record["metric"] == "MRA:.5:.95:.05"
150
+ assert record["score"] == 1.0
151
+ assert record["scene"] == "scene0001_00"
152
+ assert record["question_id"] == 7
153
+
154
+
155
+ def test_write_question_result_writes_one_json_file_per_question(tmp_path):
156
+ path, record = harness_run.write_question_result(
157
+ _FAKE_ROW,
158
+ "full prompt text",
159
+ _FAKE_ANSWER,
160
+ "MRA:.5:.95:.05",
161
+ 1.0,
162
+ "qwen3.5-4b",
163
+ "/root/models/qwen3.5-4b",
164
+ _FAKE_FRAME_INFO,
165
+ results_dir=tmp_path,
166
+ )
167
+ assert path == tmp_path / "scene0001_00" / "7.json"
168
+ on_disk = json.loads(path.read_text())
169
+ assert on_disk == record
170
+
171
+
172
+ def test_build_record_defaults_reasoning_fields_when_not_extended():
173
+ record = harness_run._build_record(
174
+ _FAKE_ROW,
175
+ "full prompt text",
176
+ _FAKE_ANSWER,
177
+ "MRA:.5:.95:.05",
178
+ 1.0,
179
+ "qwen3.5-4b",
180
+ "/root/models/qwen3.5-4b",
181
+ _FAKE_FRAME_INFO,
182
+ )
183
+ assert record["reasoning_text"] is None
184
+ assert record["forced"] is False
185
+ assert record["forced_input_token_count"] is None
186
+
187
+
188
+ def test_build_record_carries_reasoning_fields_when_extended():
189
+ extended_answer = {
190
+ **_FAKE_ANSWER,
191
+ "reasoning_text": "long reasoning about the scene",
192
+ "reasoning_raw": "long reasoning about the scene<|im_end|>",
193
+ "reasoning_token_ids": list(range(50)),
194
+ "reasoning_token_count": 50,
195
+ "reasoning_hit_limit": True,
196
+ "forced": True,
197
+ "forced_input_token_count": 2510,
198
+ }
199
+ record = harness_run._build_record(
200
+ _FAKE_ROW,
201
+ "full prompt text",
202
+ extended_answer,
203
+ "MRA:.5:.95:.05",
204
+ 1.0,
205
+ "qwen3.5-4b",
206
+ "/root/models/qwen3.5-4b",
207
+ _FAKE_FRAME_INFO,
208
+ )
209
+ assert record["reasoning_text"] == "long reasoning about the scene"
210
+ assert record["reasoning_raw"] == "long reasoning about the scene<|im_end|>"
211
+ assert record["reasoning_token_ids"] == list(range(50))
212
+ assert record["reasoning_token_count"] == 50
213
+ assert record["reasoning_hit_limit"] is True
214
+ assert record["forced"] is True
215
+ assert record["forced_input_token_count"] == 2510
216
+
217
+
218
+ def test_video_results_use_video_branch():
219
+ assert (
220
+ harness_run.results_dir_for("qwen3.5-4b", "thinking", "video", None)
221
+ == A.RESULTS_DIR / "qwen3.5-4b" / "video"
222
+ )
223
+
224
+
225
+ def test_video_record_has_no_frame_count_in_condition():
226
+ info = dict(_FAKE_FRAME_INFO, frame_selection="video", frame_count=None)
227
+ record = harness_run._build_record(
228
+ _FAKE_ROW, "prompt", _FAKE_ANSWER, "metric", 1.0, "qwen3.5-4b", "/model", info
229
+ )
230
+ assert record["condition"] == "base:video"
231
+ assert record["frame_count"] is None
tests/test_A/test_sweep.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/A/sweep.py -- multi-config sweep planning."""
2
+
3
+ import pytest
4
+
5
+ from harness.A import models as vlm_models
6
+ from harness.A import sweep
7
+
8
+
9
+ def test_parse_csv_choice_splits_and_dedups():
10
+ result = sweep._parse_csv_choice(
11
+ "uniform,selective,uniform", ("uniform", "selective"), "--x"
12
+ )
13
+ assert result == ["uniform", "selective"]
14
+
15
+
16
+ def test_parse_csv_choice_expands_all():
17
+ result = sweep._parse_csv_choice("all", ("uniform", "selective"), "--x")
18
+ assert result == ["uniform", "selective"]
19
+
20
+
21
+ def test_parse_csv_choice_rejects_unknown_value():
22
+ with pytest.raises(ValueError):
23
+ sweep._parse_csv_choice("uniform,bogus", ("uniform", "selective"), "--x")
24
+
25
+
26
+ def test_parse_csv_choice_rejects_empty():
27
+ with pytest.raises(ValueError):
28
+ sweep._parse_csv_choice("", ("uniform", "selective"), "--x")
29
+
30
+
31
+ def test_parse_frame_counts_splits_and_dedups():
32
+ assert sweep._parse_frame_counts("16,32,64,32") == [16, 32, 64]
33
+
34
+
35
+ def test_parse_frame_counts_rejects_nonpositive():
36
+ with pytest.raises(ValueError):
37
+ sweep._parse_frame_counts("16,0,64")
38
+
39
+
40
+ def test_parse_frame_counts_rejects_non_integer():
41
+ with pytest.raises(ValueError):
42
+ sweep._parse_frame_counts("16,abc")
43
+
44
+
45
+ def test_build_plan_covers_every_combination():
46
+ plan = sweep.build_plan(
47
+ ["qwen3.5-2b", "qwen3.5-4b"], ["uniform", "selective"], [16, 32]
48
+ )
49
+ assert len(plan) == 2 * 2 * 2
50
+ assert set(plan) == {
51
+ ("qwen3.5-2b", "uniform", 16),
52
+ ("qwen3.5-2b", "uniform", 32),
53
+ ("qwen3.5-2b", "selective", 16),
54
+ ("qwen3.5-2b", "selective", 32),
55
+ ("qwen3.5-4b", "uniform", 16),
56
+ ("qwen3.5-4b", "uniform", 32),
57
+ ("qwen3.5-4b", "selective", 16),
58
+ ("qwen3.5-4b", "selective", 32),
59
+ }
60
+
61
+
62
+ def test_build_plan_orders_by_frame_count_first():
63
+ plan = sweep.build_plan(["qwen3.5-2b"], ["uniform"], [64, 16, 32])
64
+ assert [frame_count for _model, _selection, frame_count in plan] == [16, 32, 64]
65
+
66
+
67
+ def test_build_plan_with_all_registered_models():
68
+ plan = sweep.build_plan(list(vlm_models.available_models()), ["uniform"], [16])
69
+ assert len(plan) == len(vlm_models.available_models())
tests/test_B/__init__.py ADDED
File without changes
tests/test_B/conftest.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared import setup for harness.B tests."""
2
+
3
+ from pathlib import Path
4
+ import sys
5
+
6
+ ROOT = Path(__file__).resolve().parents[2]
7
+ if str(ROOT) not in sys.path:
8
+ sys.path.insert(0, str(ROOT))
9
+
10
+
11
+ def pytest_configure(config):
12
+ config.option.importmode = "importlib"
tests/test_B/test_B.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/B/__init__.py -- shared config constants."""
2
+
3
+ from pathlib import Path
4
+
5
+ from harness import A, B
6
+
7
+
8
+ def test_spatial_code_formats_is_explicit_only():
9
+ assert B.SPATIAL_CODE_FORMATS == ("explicit",)
10
+ assert B.DEFAULT_SPATIAL_CODE_FORMAT in B.SPATIAL_CODE_FORMATS
11
+
12
+
13
+ def test_input_selections_match_harness_a_vocabulary():
14
+ assert B.INPUT_SELECTIONS == A.FRAME_SELECTIONS
15
+ assert B.DEFAULT_INPUT_SELECTION in B.INPUT_SELECTIONS
16
+
17
+
18
+ def test_reuses_harness_a_model_paths_and_generation_protocol():
19
+ assert B.MODEL_PATHS is A.MODEL_PATHS
20
+ assert B.MAX_NEW_TOKENS == A.MAX_NEW_TOKENS
21
+ assert B.DO_SAMPLE == A.DO_SAMPLE
22
+ assert B.TEMPERATURE == A.TEMPERATURE
23
+
24
+
25
+ def test_results_dir_defaults_under_root_results():
26
+ assert B.RESULTS_DIR == Path("/root/results/B")
27
+
28
+
29
+ def test_depth_and_tracking_reuse_encoder_config_vocabulary():
30
+ from encoder.config import DEPTH_VARIANTS, TRACKING_MODES
31
+
32
+ assert B.DEPTH_VARIANTS == DEPTH_VARIANTS
33
+ assert B.TRACKING_MODES == TRACKING_MODES
34
+ assert B.DEFAULT_DEPTH in B.DEPTH_VARIANTS
35
+ assert B.DEFAULT_TRACKING in B.TRACKING_MODES
tests/test_B/test_init.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/B/__init__.py -- shared config constants."""
2
+
3
+ from pathlib import Path
4
+
5
+ from harness import A, B
6
+
7
+
8
+ def test_spatial_code_formats_is_explicit_only():
9
+ assert B.SPATIAL_CODE_FORMATS == ("explicit",)
10
+ assert B.DEFAULT_SPATIAL_CODE_FORMAT in B.SPATIAL_CODE_FORMATS
11
+
12
+
13
+ def test_input_selections_match_harness_a_vocabulary():
14
+ assert B.INPUT_SELECTIONS == A.FRAME_SELECTIONS
15
+ assert B.DEFAULT_INPUT_SELECTION in B.INPUT_SELECTIONS
16
+
17
+
18
+ def test_reuses_harness_a_model_paths_and_generation_protocol():
19
+ assert B.MODEL_PATHS is A.MODEL_PATHS
20
+ assert B.MAX_NEW_TOKENS == A.MAX_NEW_TOKENS
21
+ assert B.DO_SAMPLE == A.DO_SAMPLE
22
+ assert B.TEMPERATURE == A.TEMPERATURE
23
+
24
+
25
+ def test_results_dir_defaults_under_root_results():
26
+ assert B.RESULTS_DIR == Path("/root/results/B")
27
+
28
+
29
+ def test_depth_and_tracking_reuse_encoder_config_vocabulary():
30
+ from encoder.config import DEPTH_VARIANTS, TRACKING_MODES
31
+
32
+ assert B.DEPTH_VARIANTS == DEPTH_VARIANTS
33
+ assert B.TRACKING_MODES == TRACKING_MODES
34
+ assert B.DEFAULT_DEPTH in B.DEPTH_VARIANTS
35
+ assert B.DEFAULT_TRACKING in B.TRACKING_MODES
tests/test_B/test_launch.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/B/launch.py -- multi-GPU scene sharding across workers."""
2
+
3
+ import pytest
4
+
5
+ from harness.B import launch
6
+
7
+
8
+ def test_launcher_imports():
9
+ assert callable(launch.main)
10
+
11
+
12
+ class _FakeRun:
13
+ rows = [{"id": 1}, {"id": 3}]
14
+
15
+ @staticmethod
16
+ def results_dir_for(*args, **kwargs):
17
+ return args[-1]
18
+
19
+ @classmethod
20
+ def load_questions(cls, scene=None):
21
+ return list(cls.rows)
22
+
23
+
24
+ def test_launch_skips_scene_already_fully_answered(tmp_path, capsys, monkeypatch):
25
+ scene = "scene-b"
26
+ monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun)
27
+
28
+ scene_dir = tmp_path / scene
29
+ scene_dir.mkdir()
30
+ for row in _FakeRun.rows:
31
+ (scene_dir / f"{row['id']}.json").write_text("{}")
32
+
33
+ launch.launch(
34
+ "qwen3.5-2b", "explicit", "selective", 64, [scene], results_dir=tmp_path
35
+ )
36
+
37
+ output = capsys.readouterr().out
38
+ assert "skipped" in output
39
+ assert "DONE: 1 ok, 0 failed" in output
40
+
41
+
42
+ def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch):
43
+ scene = "scene-b"
44
+ monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun)
45
+ scene_dir = tmp_path / scene
46
+ scene_dir.mkdir()
47
+ for row in _FakeRun.rows:
48
+ (scene_dir / f"{row['id']}.json").write_text("{}")
49
+
50
+ monkeypatch.setattr(launch, "visible_gpus", lambda: [])
51
+ monkeypatch.setattr(
52
+ launch.mp,
53
+ "get_context",
54
+ lambda *_: (_ for _ in ()).throw(
55
+ RuntimeError("rebuild correctly reached worker dispatch")
56
+ ),
57
+ )
58
+ try:
59
+ launch.launch(
60
+ "qwen3.5-2b",
61
+ "explicit",
62
+ "selective",
63
+ 64,
64
+ [scene],
65
+ results_dir=tmp_path,
66
+ rebuild=True,
67
+ )
68
+ except RuntimeError as exc:
69
+ assert "rebuild correctly reached worker dispatch" in str(exc)
70
+ else:
71
+ raise AssertionError("expected rebuild to force scene into the pending path")
72
+
73
+
74
+ def test_launch_rejects_question_id_filter_that_matches_nothing(monkeypatch, tmp_path):
75
+ monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun)
76
+ with pytest.raises(ValueError, match="no questions found"):
77
+ launch.launch(
78
+ "qwen3.5-2b",
79
+ "explicit",
80
+ "selective",
81
+ 64,
82
+ ["scene-b"],
83
+ results_dir=tmp_path,
84
+ question_ids={999},
85
+ )
tests/test_B/test_prompts.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/B/prompts.py -- 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.B 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._question_legend("object_counting"))
19
+ projected = code_prompts._project_for_question(
20
+ _CODE, "object_counting", "How many chairs?"
21
+ )
22
+ assert json.dumps(projected, indent=1) in prompt
23
+ assert prompt.endswith(code_prompts.NA_POST_PROMPT)
24
+
25
+
26
+ def test_mca_question_prompt_includes_options_and_matches_harness_a_post_prompt():
27
+ prompt = code_prompts.build_prompt(
28
+ _CODE, "object_rel_distance", "Which is closest?", ["A. sofa", "B. table"]
29
+ )
30
+ assert "Options:\nA. sofa\nB. table" in prompt
31
+ assert prompt.endswith(code_prompts.MCA_POST_PROMPT)
32
+
33
+
34
+ def test_mca_question_requires_options():
35
+ with pytest.raises(ValueError):
36
+ code_prompts.build_prompt(_CODE, "route_planning", "Which way?", None)
37
+
38
+
39
+ def test_unknown_question_type_rejected():
40
+ with pytest.raises(ValueError):
41
+ code_prompts.build_prompt(_CODE, "not_a_real_type", "?", None)
42
+
43
+
44
+ def test_no_frames_language_in_pre_prompt():
45
+ # B has no video frames -- the context line must not claim otherwise.
46
+ assert "frame" not in code_prompts.PRE_PROMPT.lower()
47
+
48
+
49
+ @pytest.mark.parametrize("question_type", NA_QUESTION_TYPES)
50
+ def test_every_na_question_type_builds(question_type):
51
+ prompt = code_prompts.build_prompt(_CODE, question_type, "q?")
52
+ assert prompt.startswith(code_prompts._question_legend(question_type))
53
+
54
+
55
+ @pytest.mark.parametrize("question_type", MCA_QUESTION_TYPES)
56
+ def test_every_mca_question_type_builds(question_type):
57
+ prompt = code_prompts.build_prompt(_CODE, question_type, "q?", ["A. x", "B. y"])
58
+ assert prompt.startswith(code_prompts._question_legend(question_type))
59
+
60
+
61
+ _RICH_CODE = {
62
+ "spatial code schema": {"version": 2},
63
+ "objects": {
64
+ "chair": {
65
+ "count": 2,
66
+ "instances": [{
67
+ "longest_dimension_meters": 0.8,
68
+ "position": {"floor_x_meters": 1.0},
69
+ "irrelevant": "drop me",
70
+ }],
71
+ },
72
+ "table": {"count": 1, "instances": []},
73
+ },
74
+ "room": {"floor_area_square_meters": 12.5, "outline": [1, 2]},
75
+ "closest_classes_from": {"chair": {"table": {"distance_meters": 1.2}}},
76
+ "appearance_order": ["chair", "table"],
77
+ "camera_trajectory": {"waypoints": [1]},
78
+ }
79
+
80
+
81
+ def test_counting_projection_keeps_only_counts_for_every_class():
82
+ projected = code_prompts._project_for_question(
83
+ _RICH_CODE, "object_counting", "How many chairs?"
84
+ )
85
+ assert projected == {
86
+ "objects": {"chair": {"count": 2}, "table": {"count": 1}}
87
+ }
88
+
89
+
90
+ def test_size_projection_keeps_only_instance_dimensions():
91
+ projected = code_prompts._project_for_question(
92
+ _RICH_CODE, "object_size_estimation", "How large is the chair?"
93
+ )
94
+ assert projected == {
95
+ "objects": {
96
+ "chair": {"instances": [{"longest_dimension_meters": 0.8}]},
97
+ "table": {"instances": []},
98
+ }
99
+ }
100
+
101
+
102
+ def test_room_projection_keeps_only_floor_area():
103
+ projected = code_prompts._project_for_question(
104
+ _RICH_CODE, "room_size_estimation", "How large is the room?"
105
+ )
106
+ assert projected == {"room": {"floor_area_square_meters": 12.5}}
107
+
108
+
109
+ @pytest.mark.parametrize(
110
+ "question_type", ["object_abs_distance", "object_rel_distance"]
111
+ )
112
+ def test_distance_projections_keep_only_the_complete_distance_matrix(question_type):
113
+ projected = code_prompts._project_for_question(
114
+ _RICH_CODE, question_type, "distance?", ["A. x", "B. y"]
115
+ )
116
+ assert projected == {
117
+ "closest_classes_from": _RICH_CODE["closest_classes_from"]
118
+ }
119
+
120
+
121
+ @pytest.mark.parametrize(
122
+ "question_type",
123
+ [
124
+ "object_rel_direction_easy",
125
+ "object_rel_direction_medium",
126
+ "object_rel_direction_hard",
127
+ "route_planning",
128
+ ],
129
+ )
130
+ def test_direction_and_route_projections_keep_only_positions(question_type):
131
+ projected = code_prompts._project_for_question(
132
+ _RICH_CODE, question_type, "direction?", ["A. x", "B. y"]
133
+ )
134
+ assert projected == {
135
+ "objects": {
136
+ "chair": {"instances": [{"position": {"floor_x_meters": 1.0}}]},
137
+ "table": {"instances": []},
138
+ }
139
+ }
140
+
141
+
142
+ def test_appearance_projection_keeps_only_appearance_order():
143
+ projected = code_prompts._project_for_question(
144
+ _RICH_CODE, "obj_appearance_order", "which appeared first?", ["A. x"]
145
+ )
146
+ assert projected == {"appearance_order": ["chair", "table"]}
tests/test_B/test_run.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/B/run.py -- result-record shape and result-file writing."""
2
+
3
+ import json
4
+
5
+ from harness import B
6
+ from harness.B 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": "thinking",
44
+ "spatial_code_format": "explicit",
45
+ "input_selection": "selective",
46
+ "frame_count": 64,
47
+ "depth": "metric",
48
+ "tracking": "tracking",
49
+ "spatial_code_path": "/workspace/data/spatial codes/.../scene0001_00.json",
50
+ }
51
+
52
+
53
+ def test_results_dir_for_matches_established_dimension_nesting():
54
+ root = harness_run.results_dir_for(
55
+ "qwen3.5-4b", "thinking", "explicit", "metric", "tracking", "uniform", 32
56
+ )
57
+ assert root == (
58
+ B.RESULTS_DIR
59
+ / "qwen3.5-4b"
60
+ / "explicit"
61
+ / "metric"
62
+ / "tracking"
63
+ / "uniform"
64
+ / "32"
65
+ )
66
+
67
+
68
+ def test_results_dir_for_keeps_protocols_together():
69
+ base = harness_run.results_dir_for(
70
+ "qwen3.5-4b", "base", "explicit", "metric", "tracking", "uniform", 32
71
+ )
72
+ extended = harness_run.results_dir_for(
73
+ "qwen3.5-4b", "thinking", "explicit", "metric", "tracking", "uniform", 32
74
+ )
75
+ assert base == extended
76
+
77
+
78
+ def test_results_dir_for_honors_explicit_override(tmp_path):
79
+ root = harness_run.results_dir_for(
80
+ "qwen3.5-4b",
81
+ "base",
82
+ "explicit",
83
+ "relative",
84
+ "no tracking",
85
+ "selective",
86
+ 16,
87
+ tmp_path,
88
+ )
89
+ assert root == tmp_path
90
+
91
+
92
+ def test_build_record_preserves_every_field_untruncated():
93
+ record = harness_run._build_record(
94
+ _FAKE_ROW,
95
+ "full prompt text",
96
+ _FAKE_ANSWER,
97
+ "MRA:.5:.95:.05",
98
+ 1.0,
99
+ "qwen3.5-4b",
100
+ "/root/models/qwen3.5-4b",
101
+ _FAKE_CODE_INFO,
102
+ )
103
+ assert record["question"] == "How many chairs?"
104
+ assert record["full_prompt"] == "full prompt text"
105
+ assert record["rendered_prompt"] == _FAKE_ANSWER["prompt_text"]
106
+ assert record["answer_given"] == "4"
107
+ assert record["answer_raw"] == _FAKE_ANSWER["answer_raw"]
108
+ assert record["spatial_code_format"] == "explicit"
109
+ assert record["input_selection"] == "selective"
110
+ assert record["frame_count"] == 64
111
+ assert record["depth"] == "metric"
112
+ assert record["tracking"] == "tracking"
113
+ assert record["spatial_code_path"] == _FAKE_CODE_INFO["spatial_code_path"]
114
+ assert record["condition"] == "thinking:explicit:metric:tracking:selective:64"
115
+ assert record["protocol"] == "thinking"
116
+ assert record["vision_input_shapes"] == {"mm_token_type_ids": [1, 2558]}
117
+ assert record["generation_config"] == _FAKE_ANSWER["generation_config"]
118
+ assert record["metric"] == "MRA:.5:.95:.05"
119
+ assert record["score"] == 1.0
120
+ assert record["scene"] == "scene0001_00"
121
+ assert record["question_id"] == 7
122
+ # No frame-provenance fields -- B has no video frames.
123
+ assert "frame_selection" not in record
124
+ assert "video_path" not in record
125
+ assert "frame_indices" not in record
126
+
127
+
128
+ def test_write_question_result_writes_one_json_file_per_question(tmp_path):
129
+ path, record = harness_run.write_question_result(
130
+ _FAKE_ROW,
131
+ "full prompt text",
132
+ _FAKE_ANSWER,
133
+ "MRA:.5:.95:.05",
134
+ 1.0,
135
+ "qwen3.5-4b",
136
+ "/root/models/qwen3.5-4b",
137
+ _FAKE_CODE_INFO,
138
+ results_dir=tmp_path,
139
+ )
140
+ assert path == tmp_path / "scene0001_00" / "7.json"
141
+ on_disk = json.loads(path.read_text())
142
+ assert on_disk == record
143
+
144
+
145
+ def test_build_record_carries_reasoning_fields_when_forced():
146
+ extended_answer = {
147
+ **_FAKE_ANSWER,
148
+ "reasoning_text": "long reasoning about the spatial code",
149
+ "reasoning_raw": "long reasoning about the spatial code<|im_end|>",
150
+ "reasoning_token_ids": list(range(50)),
151
+ "reasoning_token_count": 50,
152
+ "reasoning_hit_limit": True,
153
+ "forced": True,
154
+ "forced_input_token_count": 2510,
155
+ }
156
+ record = harness_run._build_record(
157
+ _FAKE_ROW,
158
+ "full prompt text",
159
+ extended_answer,
160
+ "MRA:.5:.95:.05",
161
+ 1.0,
162
+ "qwen3.5-4b",
163
+ "/root/models/qwen3.5-4b",
164
+ _FAKE_CODE_INFO,
165
+ )
166
+ assert record["reasoning_text"] == "long reasoning about the spatial code"
167
+ assert record["reasoning_raw"] == "long reasoning about the spatial code<|im_end|>"
168
+ assert record["reasoning_token_ids"] == list(range(50))
169
+ assert record["reasoning_token_count"] == 50
170
+ assert record["reasoning_hit_limit"] is True
171
+ assert record["forced"] is True
172
+ assert record["forced_input_token_count"] == 2510
173
+
174
+
175
+
176
+ def test_video_results_use_video_branch():
177
+ assert (
178
+ harness_run.results_dir_for(
179
+ "qwen3.5-4b", "thinking", "explicit", "metric", "tracking", "video", None
180
+ )
181
+ == B.RESULTS_DIR / "qwen3.5-4b" / "explicit" / "metric" / "tracking" / "video"
182
+ )
183
+
184
+
185
+ def test_video_record_has_no_frame_count_in_condition():
186
+ info = dict(_FAKE_CODE_INFO, input_selection="video", frame_count=None)
187
+ record = harness_run._build_record(
188
+ _FAKE_ROW, "prompt", _FAKE_ANSWER, "metric", 1.0, "qwen3.5-4b", "/model", info
189
+ )
190
+ assert record["condition"] == "thinking:explicit:metric:tracking:video"
191
+ assert record["frame_count"] is None
tests/test_B/test_spatial_codes.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/B/spatial_codes.py -- loading on-disk spatial codes as plain JSON."""
2
+
3
+ import json
4
+
5
+ import pytest
6
+
7
+ from harness.B 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(
13
+ "scene", "metric", "selective", "tracking", 64, "bogus"
14
+ )
15
+
16
+
17
+ def test_load_spatial_code_raises_clearly_when_missing(tmp_path, monkeypatch):
18
+ monkeypatch.setattr(
19
+ spatial_codes,
20
+ "spatial_code_path",
21
+ lambda *a, **k: str(tmp_path / "missing.json"),
22
+ )
23
+ with pytest.raises(FileNotFoundError):
24
+ spatial_codes.load_spatial_code(
25
+ "scene", "metric", "selective", "tracking", 64, "explicit"
26
+ )
27
+
28
+
29
+ def test_load_spatial_code_returns_dict_and_path(tmp_path, monkeypatch):
30
+ fixture = tmp_path / "13c3e046d7.json"
31
+ fixture.write_text(json.dumps({"objects": {}, "room": {}}))
32
+ monkeypatch.setattr(
33
+ spatial_codes, "spatial_code_path", lambda *a, **k: str(fixture)
34
+ )
35
+ code, path = spatial_codes.load_spatial_code(
36
+ "13c3e046d7", "metric", "selective", "tracking", 64, "explicit"
37
+ )
38
+ assert code == {"objects": {}, "room": {}}
39
+ assert path == str(fixture)
40
+
41
+
42
+ def test_spatial_code_path_uses_tracking_frames_hierarchy():
43
+ path = spatial_codes.spatial_code_path(
44
+ "scene-a", "metric", "selective", "tracking", 64, "explicit"
45
+ )
46
+ assert path.endswith(
47
+ "data/spatial codes/sam3+depth-anything-3/tracking/frames/selective/64/explicit/scene-a.json"
48
+ )
tests/test_B/test_sweep.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/B/sweep.py -- multi-config sweep planning."""
2
+
3
+ import pytest
4
+
5
+ from harness.A import models as vlm_models
6
+ from harness.B import sweep
7
+
8
+
9
+ def test_build_plan_covers_every_combination():
10
+ plan = sweep.build_plan(
11
+ ["qwen3.5-2b", "qwen3.5-4b"],
12
+ ["explicit"],
13
+ ["uniform", "selective"],
14
+ [16, 32],
15
+ ["metric"],
16
+ ["tracking"],
17
+ )
18
+ assert len(plan) == 2 * 1 * 2 * 2
19
+ assert ("qwen3.5-2b", "explicit", "metric", "tracking", "uniform", 16) in plan
20
+ assert ("qwen3.5-4b", "explicit", "metric", "tracking", "selective", 32) in plan
21
+
22
+
23
+ def test_build_plan_sweeps_depth_and_tracking_too():
24
+ plan = sweep.build_plan(
25
+ ["qwen3.5-2b"],
26
+ ["explicit"],
27
+ ["uniform"],
28
+ [16],
29
+ ["metric", "relative"],
30
+ ["tracking", "no tracking"],
31
+ )
32
+ assert len(plan) == 4
33
+ assert ("qwen3.5-2b", "explicit", "relative", "no tracking", "uniform", 16) in plan
34
+
35
+
36
+ def test_build_plan_orders_by_frame_count_first():
37
+ plan = sweep.build_plan(
38
+ ["qwen3.5-2b"],
39
+ ["explicit"],
40
+ ["uniform"],
41
+ [64, 16, 32],
42
+ ["metric"],
43
+ ["tracking"],
44
+ )
45
+ assert [frame_count for *_rest, frame_count in plan] == [16, 32, 64]
46
+
47
+
48
+ def test_build_plan_with_all_registered_models():
49
+ plan = sweep.build_plan(
50
+ list(vlm_models.available_models()),
51
+ ["explicit"],
52
+ ["uniform"],
53
+ [16],
54
+ ["metric"],
55
+ ["tracking"],
56
+ )
57
+ assert len(plan) == len(vlm_models.available_models())
58
+
59
+
60
+ def test_sweep_parser_rejects_unknown_depth():
61
+ with pytest.raises(ValueError):
62
+ sweep._parse_csv_choice("bogus", sweep.DEPTH_VARIANTS, "--depths")
63
+
64
+
65
+ def test_sweep_parser_rejects_unknown_tracking():
66
+ with pytest.raises(ValueError):
67
+ sweep._parse_csv_choice("bogus", sweep.TRACKING_MODES, "--trackings")
tests/test_C/__init__.py ADDED
File without changes
tests/test_C/conftest.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared import setup for harness.C tests."""
2
+
3
+ from pathlib import Path
4
+ import sys
5
+
6
+ ROOT = Path(__file__).resolve().parents[2]
7
+ if str(ROOT) not in sys.path:
8
+ sys.path.insert(0, str(ROOT))
9
+
10
+
11
+ def pytest_configure(config):
12
+ config.option.importmode = "importlib"
tests/test_C/test_C.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/C/__init__.py -- shared config constants."""
2
+
3
+ from pathlib import Path
4
+
5
+ from harness import A, B, C
6
+
7
+
8
+ def test_input_selections_are_one_shared_vocabulary_with_a_and_b():
9
+ assert B.INPUT_SELECTIONS == A.FRAME_SELECTIONS
10
+
11
+
12
+ def test_reuses_harness_a_model_paths_and_generation_protocol():
13
+ assert C.MODEL_PATHS is A.MODEL_PATHS
14
+ assert C.MAX_NEW_TOKENS == A.MAX_NEW_TOKENS
15
+ assert C.DO_SAMPLE == A.DO_SAMPLE
16
+ assert C.TEMPERATURE == A.TEMPERATURE
17
+
18
+
19
+ def test_results_dir_defaults_under_root_results():
20
+ assert C.RESULTS_DIR == Path("/root/results/C")
21
+
22
+
23
+ def test_depth_and_tracking_reuse_encoder_config_vocabulary():
24
+ from encoder.config import DEPTH_VARIANTS, TRACKING_MODES
25
+
26
+ assert C.DEPTH_VARIANTS == DEPTH_VARIANTS
27
+ assert C.TRACKING_MODES == TRACKING_MODES
tests/test_C/test_init.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/C/__init__.py -- shared config constants."""
2
+
3
+ from pathlib import Path
4
+
5
+ from harness import A, B, C
6
+
7
+
8
+ def test_input_selections_are_one_shared_vocabulary_with_a_and_b():
9
+ assert B.INPUT_SELECTIONS == A.FRAME_SELECTIONS
10
+
11
+
12
+ def test_reuses_harness_a_model_paths_and_generation_protocol():
13
+ assert C.MODEL_PATHS is A.MODEL_PATHS
14
+ assert C.MAX_NEW_TOKENS == A.MAX_NEW_TOKENS
15
+ assert C.DO_SAMPLE == A.DO_SAMPLE
16
+ assert C.TEMPERATURE == A.TEMPERATURE
17
+
18
+
19
+ def test_results_dir_defaults_under_root_results():
20
+ assert C.RESULTS_DIR == Path("/root/results/C")
21
+
22
+
23
+ def test_depth_and_tracking_reuse_encoder_config_vocabulary():
24
+ from encoder.config import DEPTH_VARIANTS, TRACKING_MODES
25
+
26
+ assert C.DEPTH_VARIANTS == DEPTH_VARIANTS
27
+ assert C.TRACKING_MODES == TRACKING_MODES
tests/test_C/test_launch.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/C/launch.py -- multi-GPU scene sharding across workers."""
2
+
3
+ from harness.C import launch
4
+
5
+
6
+ def test_launcher_imports():
7
+ assert callable(launch.main)
8
+
9
+
10
+ class _FakeRun:
11
+ rows = [{"id": 1}, {"id": 2}]
12
+
13
+ @staticmethod
14
+ def results_dir_for(*args, **kwargs):
15
+ return args[-1]
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-c"
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(
32
+ "qwen3.5-2b", "explicit", "selective", 64, [scene], results_dir=tmp_path
33
+ )
34
+
35
+ output = capsys.readouterr().out
36
+ assert "skipped" in output
37
+ assert "DONE: 1 ok, 0 failed" in output
38
+
39
+
40
+ def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch):
41
+ scene = "scene-c"
42
+ monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun)
43
+ scene_dir = tmp_path / scene
44
+ scene_dir.mkdir()
45
+ for row in _FakeRun.rows:
46
+ (scene_dir / f"{row['id']}.json").write_text("{}")
47
+
48
+ monkeypatch.setattr(launch, "visible_gpus", lambda: [])
49
+ monkeypatch.setattr(
50
+ launch.mp,
51
+ "get_context",
52
+ lambda *_: (_ for _ in ()).throw(
53
+ RuntimeError("rebuild correctly reached worker dispatch")
54
+ ),
55
+ )
56
+ try:
57
+ launch.launch(
58
+ "qwen3.5-2b",
59
+ "explicit",
60
+ "selective",
61
+ 64,
62
+ [scene],
63
+ results_dir=tmp_path,
64
+ rebuild=True,
65
+ )
66
+ except RuntimeError as exc:
67
+ assert "rebuild correctly reached worker dispatch" in str(exc)
68
+ else:
69
+ raise AssertionError("expected rebuild to force scene into the pending path")
tests/test_C/test_prompts.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/C/prompts.py -- combined frames+spatial-code 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.B import prompts as code_prompts
9
+ from harness.C import prompts as combined_prompts
10
+
11
+ _CODE = {
12
+ "objects": {"chair": {"count": 1}},
13
+ "room": {"floor area": "10.0 square meters"},
14
+ }
15
+
16
+
17
+ def test_pre_prompt_mentions_both_frames_and_spatial_code():
18
+ lowered = combined_prompts.FRAMES_NOTE.lower()
19
+ assert "frame" in lowered
20
+ assert "spatial code" in lowered
21
+
22
+
23
+ def test_na_question_prompt_layout_is_context_then_code_then_question_then_post_prompt():
24
+ prompt = combined_prompts.build_prompt(_CODE, "object_counting", "How many chairs?")
25
+ context_pos = prompt.find(combined_prompts.FRAMES_NOTE)
26
+ projected = code_prompts._project_for_question(
27
+ _CODE, "object_counting", "How many chairs?"
28
+ )
29
+ code_pos = prompt.find(json.dumps(projected, indent=1))
30
+ question_pos = prompt.find("How many chairs?")
31
+ post_pos = prompt.find(code_prompts.NA_POST_PROMPT)
32
+ assert context_pos == 0
33
+ assert context_pos < code_pos < question_pos < post_pos
34
+
35
+
36
+ def test_mca_question_prompt_includes_options_and_post_prompt():
37
+ prompt = combined_prompts.build_prompt(
38
+ _CODE, "object_rel_distance", "Which is closest?", ["A. sofa", "B. table"]
39
+ )
40
+ assert "Options:\nA. sofa\nB. table" in prompt
41
+ assert prompt.endswith(code_prompts.MCA_POST_PROMPT)
42
+
43
+
44
+ def test_mca_question_requires_options():
45
+ with pytest.raises(ValueError):
46
+ combined_prompts.build_prompt(_CODE, "route_planning", "Which way?", None)
47
+
48
+
49
+ def test_unknown_question_type_rejected():
50
+ with pytest.raises(ValueError):
51
+ combined_prompts.build_prompt(_CODE, "not_a_real_type", "?", None)
52
+
53
+
54
+ @pytest.mark.parametrize("question_type", NA_QUESTION_TYPES)
55
+ def test_every_na_question_type_builds(question_type):
56
+ prompt = combined_prompts.build_prompt(_CODE, question_type, "q?")
57
+ assert prompt.startswith(combined_prompts.FRAMES_NOTE)
58
+
59
+
60
+ @pytest.mark.parametrize("question_type", MCA_QUESTION_TYPES)
61
+ def test_every_mca_question_type_builds(question_type):
62
+ prompt = combined_prompts.build_prompt(_CODE, question_type, "q?", ["A. x", "B. y"])
63
+ assert prompt.startswith(combined_prompts.FRAMES_NOTE)
64
+
65
+
66
+ def test_video_prompt_names_native_video():
67
+ prompt = combined_prompts.build_prompt(
68
+ _CODE, "object_counting", "How many chairs?", video=True
69
+ )
70
+ assert prompt.startswith("This is a video.\n")
tests/test_C/test_run.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/C/run.py -- result-record shape and result-file writing."""
2
+
3
+ import json
4
+
5
+ from harness import C
6
+ from harness.C 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": 22205,
13
+ "vision_input_shapes": {"pixel_values": [76800, 1536], "image_grid_thw": [64, 3]},
14
+ "output_token_ids": [19, 151645],
15
+ "output_token_count": 2,
16
+ "hit_token_limit": False,
17
+ "eos_token_ids": [151645],
18
+ "generation_seconds": 5.6,
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_SOURCE_INFO = {
43
+ "protocol": "thinking",
44
+ "spatial_code_format": "explicit",
45
+ "input_selection": "selective",
46
+ "frame_count": 64,
47
+ "depth": "metric",
48
+ "tracking": "tracking",
49
+ "spatial_code_path": "/workspace/data/spatial codes/.../scene0001_00.json",
50
+ "video_path": "/root/data/VSI-Bench/scannet/scene0001_00.mp4",
51
+ "frame_indices": [0, 30, 60],
52
+ "frame_timestamps": [0.0, 1.0, 2.0],
53
+ }
54
+
55
+
56
+ def test_results_dir_for_matches_established_dimension_nesting():
57
+ root = harness_run.results_dir_for(
58
+ "qwen3.5-4b", "thinking", "explicit", "metric", "tracking", "uniform", 32
59
+ )
60
+ assert root == (
61
+ C.RESULTS_DIR
62
+ / "qwen3.5-4b"
63
+ / "explicit"
64
+ / "metric"
65
+ / "tracking"
66
+ / "uniform"
67
+ / "32"
68
+ )
69
+
70
+
71
+ def test_results_dir_for_honors_explicit_override(tmp_path):
72
+ root = harness_run.results_dir_for(
73
+ "qwen3.5-4b",
74
+ "base",
75
+ "explicit",
76
+ "relative",
77
+ "no tracking",
78
+ "selective",
79
+ 16,
80
+ tmp_path,
81
+ )
82
+ assert root == tmp_path
83
+
84
+
85
+ def test_build_record_carries_both_frame_and_spatial_code_provenance():
86
+ record = harness_run._build_record(
87
+ _FAKE_ROW,
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
+ _FAKE_SOURCE_INFO,
95
+ )
96
+ # Spatial-code provenance (shared with harness.B).
97
+ assert record["spatial_code_format"] == "explicit"
98
+ assert record["input_selection"] == "selective"
99
+ assert record["frame_count"] == 64
100
+ assert record["depth"] == "metric"
101
+ assert record["tracking"] == "tracking"
102
+ assert record["spatial_code_path"] == _FAKE_SOURCE_INFO["spatial_code_path"]
103
+ # Frame provenance (shared with harness.A).
104
+ assert record["video_path"] == _FAKE_SOURCE_INFO["video_path"]
105
+ assert record["frame_indices"] == [0, 30, 60]
106
+ assert record["frame_timestamps_seconds"] == [0.0, 1.0, 2.0]
107
+ # Question/answer fields, same shape as A and B.
108
+ assert record["question"] == "How many chairs?"
109
+ assert record["answer_given"] == "4"
110
+ assert record["vision_input_shapes"] == _FAKE_ANSWER["vision_input_shapes"]
111
+ assert record["condition"] == "extended:explicit:metric:tracking:selective:64"
112
+ assert record["protocol"] == "thinking"
113
+ assert record["score"] == 1.0
114
+
115
+
116
+ def test_write_question_result_writes_one_json_file_per_question(tmp_path):
117
+ path, record = harness_run.write_question_result(
118
+ _FAKE_ROW,
119
+ "full prompt text",
120
+ _FAKE_ANSWER,
121
+ "MRA:.5:.95:.05",
122
+ 1.0,
123
+ "qwen3.5-4b",
124
+ "/root/models/qwen3.5-4b",
125
+ _FAKE_SOURCE_INFO,
126
+ results_dir=tmp_path,
127
+ )
128
+ assert path == tmp_path / "scene0001_00" / "7.json"
129
+ on_disk = json.loads(path.read_text())
130
+ assert on_disk == record
131
+
132
+
133
+ def test_build_record_carries_reasoning_fields_when_forced():
134
+ extended_answer = {
135
+ **_FAKE_ANSWER,
136
+ "reasoning_text": "long reasoning about the frames and spatial code",
137
+ "reasoning_raw": "long reasoning about the frames and spatial code<|im_end|>",
138
+ "reasoning_token_ids": list(range(50)),
139
+ "reasoning_token_count": 50,
140
+ "reasoning_hit_limit": True,
141
+ "forced": True,
142
+ "forced_input_token_count": 22300,
143
+ }
144
+ record = harness_run._build_record(
145
+ _FAKE_ROW,
146
+ "full prompt text",
147
+ extended_answer,
148
+ "MRA:.5:.95:.05",
149
+ 1.0,
150
+ "qwen3.5-4b",
151
+ "/root/models/qwen3.5-4b",
152
+ _FAKE_SOURCE_INFO,
153
+ )
154
+ assert (
155
+ record["reasoning_text"] == "long reasoning about the frames and spatial code"
156
+ )
157
+ assert record["reasoning_raw"] == "long reasoning about the frames and spatial code<|im_end|>"
158
+ assert record["reasoning_token_ids"] == list(range(50))
159
+ assert record["reasoning_token_count"] == 50
160
+ assert record["reasoning_hit_limit"] is True
161
+ assert record["forced"] is True
162
+ assert record["forced_input_token_count"] == 22300
163
+
164
+
165
+ def test_video_results_use_video_branch():
166
+ assert (
167
+ harness_run.results_dir_for(
168
+ "qwen3.5-4b", "thinking", "explicit", "metric", "tracking", "video", None
169
+ )
170
+ == C.RESULTS_DIR / "qwen3.5-4b" / "explicit" / "metric" / "tracking" / "video"
171
+ )
172
+
173
+
174
+ def test_video_record_has_no_frame_count_in_condition():
175
+ info = dict(_FAKE_SOURCE_INFO, input_selection="video", frame_count=None)
176
+ record = harness_run._build_record(
177
+ _FAKE_ROW, "prompt", _FAKE_ANSWER, "metric", 1.0, "qwen3.5-4b", "/model", info
178
+ )
179
+ assert record["condition"] == "thinking:explicit:metric:tracking:video"
180
+ assert record["frame_count"] is None
tests/test_C/test_sweep.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/C/sweep.py -- multi-config sweep planning."""
2
+
3
+ import pytest
4
+
5
+ from harness.A import models as vlm_models
6
+ from harness.C import sweep
7
+
8
+
9
+ def test_build_plan_covers_every_combination():
10
+ plan = sweep.build_plan(
11
+ ["qwen3.5-2b", "qwen3.5-4b"],
12
+ ["explicit"],
13
+ ["uniform", "selective"],
14
+ [16, 32],
15
+ ["metric"],
16
+ ["tracking"],
17
+ )
18
+ assert len(plan) == 2 * 1 * 2 * 2
19
+ assert ("qwen3.5-2b", "explicit", "metric", "tracking", "uniform", 16) in plan
20
+ assert ("qwen3.5-4b", "explicit", "metric", "tracking", "selective", 32) in plan
21
+
22
+
23
+ def test_build_plan_sweeps_depth_and_tracking_too():
24
+ plan = sweep.build_plan(
25
+ ["qwen3.5-2b"],
26
+ ["explicit"],
27
+ ["uniform"],
28
+ [16],
29
+ ["metric", "relative"],
30
+ ["tracking", "no tracking"],
31
+ )
32
+ assert len(plan) == 4
33
+ assert ("qwen3.5-2b", "explicit", "relative", "no tracking", "uniform", 16) in plan
34
+
35
+
36
+ def test_build_plan_orders_by_frame_count_first():
37
+ plan = sweep.build_plan(
38
+ ["qwen3.5-2b"],
39
+ ["explicit"],
40
+ ["uniform"],
41
+ [64, 16, 32],
42
+ ["metric"],
43
+ ["tracking"],
44
+ )
45
+ assert [frame_count for *_rest, frame_count in plan] == [16, 32, 64]
46
+
47
+
48
+ def test_build_plan_with_all_registered_models():
49
+ plan = sweep.build_plan(
50
+ list(vlm_models.available_models()),
51
+ ["explicit"],
52
+ ["uniform"],
53
+ [16],
54
+ ["metric"],
55
+ ["tracking"],
56
+ )
57
+ assert len(plan) == len(vlm_models.available_models())
58
+
59
+
60
+ def test_sweep_parser_rejects_unknown_depth():
61
+ with pytest.raises(ValueError):
62
+ sweep._parse_csv_choice("bogus", sweep.DEPTH_VARIANTS, "--depths")
63
+
64
+
65
+ def test_sweep_parser_rejects_unknown_tracking():
66
+ with pytest.raises(ValueError):
67
+ sweep._parse_csv_choice("bogus", sweep.TRACKING_MODES, "--trackings")
tests/test_F/__init__.py ADDED
File without changes
tests/test_F/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_F/test_F.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/F package configuration."""
2
+
3
+ import importlib
4
+ from pathlib import Path
5
+
6
+ from harness import F
7
+
8
+
9
+ def test_sources_and_default_are_declared():
10
+ assert F.SOURCES == ("perceived",)
11
+ assert F.DEFAULT_SOURCE == "perceived"
12
+ assert F.RESULTS_DIR == Path("/root/results/F")
13
+
14
+
15
+ def test_results_dir_can_be_overridden_by_environment(monkeypatch, tmp_path):
16
+ monkeypatch.setenv("VSI_HARNESS_F_RESULTS_DIR", str(tmp_path / "F"))
17
+ reloaded = importlib.reload(F)
18
+ assert reloaded.RESULTS_DIR == tmp_path / "F"
19
+ monkeypatch.delenv("VSI_HARNESS_F_RESULTS_DIR")
20
+ importlib.reload(F)
tests/test_F/test_launch.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Tests for harness/F/launch.py."""
2
+
3
+ from harness.F import launch
4
+
5
+
6
+ def test_launch_entrypoint_exposes_run_main():
7
+ assert callable(launch.main)
tests/test_F/test_run.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from harness import F
3
+ from harness.F import run
4
+
5
+
6
+ def test_results_default_under_root():
7
+ assert F.RESULTS_DIR == Path("/root/results/F")
8
+
9
+
10
+ def test_perceived_layout_contains_every_input_axis():
11
+ assert run.results_dir_for(
12
+ "perceived", "explicit", "metric", "tracking", "uniform", 32
13
+ ) == Path("/root/results/F/perceived/metric/tracking/uniform/32/explicit")
14
+
15
+
16
+ def test_video_results_use_video_branch():
17
+ assert run.results_dir_for(
18
+ "perceived", "explicit", "metric", "tracking", "video", None
19
+ ) == Path("/root/results/F/perceived/metric/tracking/video/explicit")
tests/test_F/test_sweep.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for harness/F/sweep.py -- CLI cartesian product wiring."""
2
+
3
+ import pytest
4
+
5
+ from harness.F import sweep
6
+
7
+
8
+ def test_csv_expands_all_dedups_and_rejects_unknowns():
9
+ assert sweep._csv("all", ("a", "b")) == ["a", "b"]
10
+ assert sweep._csv("b,a,b", ("a", "b")) == ["b", "a"]
11
+ with pytest.raises(ValueError, match="unknown values"):
12
+ sweep._csv("c", ("a", "b"))
13
+
14
+
tests/test_analysis/__init__.py ADDED
File without changes
tests/test_analysis/conftest.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared fixtures and helpers for report-export tests."""
2
+
3
+ import json
4
+ import tempfile
5
+ import unittest
6
+ from pathlib import Path
7
+ from analysis.letters_reports import (
8
+ analyze_modular,
9
+ export_reports,
10
+ load_profile as load,
11
+ )
12
+
13
+
14
+ def vlm(letter, qid=1, score=1.0, protocol="base", model="m", frames=32):
15
+ r = {
16
+ "model": model,
17
+ "protocol": protocol,
18
+ "condition": protocol,
19
+ "question_id": qid,
20
+ "scene": "s",
21
+ "dataset": "d",
22
+ "question_type": "count",
23
+ "score": score,
24
+ "frame_count": frames,
25
+ "input_token_count": 10,
26
+ "output_token_count": 2,
27
+ "generation_seconds": 1.0,
28
+ "answer_given": "x",
29
+ "full_prompt": "p",
30
+ }
31
+ if letter == "A":
32
+ r["frame_selection"] = "uniform"
33
+ elif letter in "BC":
34
+ r.update(
35
+ input_selection="uniform",
36
+ spatial_code_format="explicit",
37
+ depth="metric",
38
+ tracking="tracking",
39
+ )
40
+ return r
41
+
42
+
43
+ def put(root, relative, record):
44
+ p = root / relative
45
+ p.parent.mkdir(parents=True, exist_ok=True)
46
+ p.write_text(json.dumps(record))
47
+ return p
48
+
49
+
50
+ class ReportTestCase(unittest.TestCase):
51
+ def setUp(self):
52
+ self.temp = tempfile.TemporaryDirectory()
53
+ self.root = Path(self.temp.name)
54
+
55
+ def tearDown(self):
56
+ self.temp.cleanup()
57
+
58
+ def directory(self, letter, records):
59
+ d = self.root / letter
60
+ d.mkdir()
61
+ for i, r in enumerate(records):
62
+ put(d, f"{i}.json", r)
63
+ return d
64
+
65
+ def symbolic(self, future=False):
66
+ d = self.root / ("F_future" if future else "F")
67
+ d.mkdir(exist_ok=True)
68
+ prefix = (
69
+ "perceived/metric/tracking/uniform/32/explicit"
70
+ if future
71
+ else "metric/tracking/uniform/32/explicit"
72
+ )
73
+ put(
74
+ d,
75
+ f"{prefix}/s/1.json",
76
+ {
77
+ "model": "symbolic",
78
+ "condition": "metric:tracking:uniform:32:explicit",
79
+ "question_id": 1,
80
+ "scene": "s",
81
+ "dataset": "d",
82
+ "question_type": "count",
83
+ "score": 1.0,
84
+ "spatial_code_format": "explicit",
85
+ "depth": "metric",
86
+ "tracking": "tracking",
87
+ "input": "uniform",
88
+ "number_of_frames": 32,
89
+ },
90
+ )
91
+ return d
92
+
93
+ def ground_truth_symbolic(self):
94
+ d = self.root / "F"
95
+ d.mkdir()
96
+ put(
97
+ d,
98
+ "ground truth/explicit/s/1.json",
99
+ {
100
+ "model": "symbolic",
101
+ "condition": "ground truth:explicit",
102
+ "question_id": 1,
103
+ "scene": "s",
104
+ "dataset": "d",
105
+ "question_type": "count",
106
+ "score": 1.0,
107
+ "spatial_code_format": "explicit",
108
+ },
109
+ )
110
+ return d
111
+
112
+ def analyze(self, letters, dirs, pairs=(), protocols=("base",)):
113
+ profiles = {l: load(l) for l in letters}
114
+ per, combined = analyze_modular(
115
+ {l: dirs[l] for l in letters}, profiles, protocols, pairs
116
+ )
117
+ paths = export_reports(per, combined, self.root / "reports")
118
+ return per, combined, {p.name for p in paths}
tests/test_analysis/test_A_reports.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tests.test_analysis.conftest import ReportTestCase, vlm
2
+ from analysis import A_reports
3
+
4
+
5
+ class TestAReports(ReportTestCase):
6
+ def test_A_report_and_controlled_frame_comparison(self):
7
+ d = self.directory("A", [vlm("A", frames=32), vlm("A", frames=64)])
8
+ result = A_reports.generate(d, ["base"], self.root / "reports")
9
+ self.assertEqual(result["path"].name, "A_report.json")
10
+ self.assertEqual(len(result["report"]["cells"]), 2)
11
+ self.assertEqual(len(result["report"]["within_harness_comparisons"]), 1)
tests/test_analysis/test_B_reports.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tests.test_analysis.conftest import ReportTestCase, vlm
2
+ from analysis import B_reports
3
+
4
+
5
+ class TestBReports(ReportTestCase):
6
+ def test_B_report_contains_spatial_cell(self):
7
+ result = B_reports.generate(
8
+ self.directory("B", [vlm("B")]), ["base"], self.root / "reports"
9
+ )
10
+ self.assertEqual(result["path"].name, "B_report.json")
11
+ self.assertEqual(len(result["report"]["cells"]), 1)
tests/test_analysis/test_C_reports.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tests.test_analysis.conftest import ReportTestCase, vlm
2
+ from analysis import C_reports
3
+
4
+
5
+ class TestCReports(ReportTestCase):
6
+ def test_C_report_is_exported(self):
7
+ result = C_reports.generate(
8
+ self.directory("C", [vlm("C")]), ["base"], self.root / "reports"
9
+ )
10
+ self.assertEqual(result["path"].name, "C_report.json")
11
+ self.assertEqual(len(result["report"]["cells"]), 1)
tests/test_analysis/test_F_reports.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tests.test_analysis.conftest import ReportTestCase
2
+ from analysis import F_reports
3
+
4
+
5
+ class TestFReports(ReportTestCase):
6
+ def test_F_legacy_and_future_perceived_layouts(self):
7
+ for future in (False, True):
8
+ result = F_reports.generate(
9
+ self.symbolic(future),
10
+ (),
11
+ self.root / ("future" if future else "legacy"),
12
+ )
13
+ self.assertEqual(result["path"].name, "F_report.json")
14
+ cell = next(iter(result["report"]["cells"].values()))
15
+ self.assertEqual(cell["identity"]["source"], "perceived")
tests/test_analysis/test_analysis.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from tests.test_analysis.conftest import ReportTestCase, vlm
3
+ from analysis.letters_reports import load_profile as load
4
+
5
+
6
+ class TestAnalysisDirectory(ReportTestCase):
7
+ def test_arbitrary_subset_exports_letter_and_combined_files(self):
8
+ dirs = {l: self.directory(l, [vlm(l)]) for l in "AC"}
9
+ _, _, names = self.analyze("AC", dirs)
10
+ self.assertEqual(names, {"A_report.json", "C_report.json", "AC_report.json"})
11
+ for name in names:
12
+ json.loads((self.root / "reports" / name).read_text())
tests/test_analysis/test_letters_reports.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tests.test_analysis.conftest import ReportTestCase, vlm
2
+ from analysis import letters_reports
3
+
4
+
5
+ class TestLettersReports(ReportTestCase):
6
+ def test_arbitrary_subset_and_combined_name(self):
7
+ cells = {l: self.directory(l, [vlm(l)]) for l in "AC"}
8
+ result = letters_reports.generate(
9
+ cells, ["base"], output_dir=self.root / "reports"
10
+ )
11
+ self.assertEqual(
12
+ {p.name for p in result["paths"]},
13
+ {"A_report.json", "C_report.json", "AC_report.json"},
14
+ )
15
+
16
+ def test_folded_statistical_and_solver_helpers(self):
17
+ self.assertEqual(
18
+ letters_reports.holm_bonferroni({"a": 0.01, "b": 0.04, "c": 0.03}),
19
+ {"a": 0.03, "c": 0.06, "b": 0.06},
20
+ )
21
+ a = [{"question_id": 1, "score": 1.0}, {"question_id": 2, "score": 0.0}]
22
+ b = [{"question_id": 1, "score": 1.0}, {"question_id": 2, "score": 1.0}]
23
+ overlap = letters_reports.solved_set_overlap({"A": a, "B": b})
24
+ self.assertEqual(overlap["pairs"]["A|B"]["only_B"], 1)
25
+ vlm = [
26
+ {"question_id": 1, "question_type": "count", "score": 0.0},
27
+ {"question_id": 2, "question_type": "count", "score": 1.0},
28
+ ]
29
+ solver = [{"question_id": 1, "score": 1.0}, {"question_id": 2, "score": 0.0}]
30
+ split = letters_reports.sufficiency_decomposition(vlm, solver)
31
+ self.assertEqual(split["certified"]["vlm_wrong"], 1)
32
+
33
+ def test_pair_restriction(self):
34
+ cells = {l: self.directory(l, [vlm(l)]) for l in "ABC"}
35
+ result = letters_reports.generate(
36
+ cells, ["base"], ["A:B"], self.root / "reports"
37
+ )
38
+ self.assertTrue(
39
+ all(
40
+ v["letters"] == ("A", "B")
41
+ for v in result["combined_report"]["cross_harness_comparisons"].values()
42
+ )
43
+ )
44
+
45
+ def test_manifest_generated_at_is_deterministic_by_default(self):
46
+ cells = {"A": self.directory("A", [vlm("A")])}
47
+ first = letters_reports.generate(cells, ["base"], output_dir=self.root / "r1")
48
+ second = letters_reports.generate(cells, ["base"], output_dir=self.root / "r2")
49
+ self.assertEqual(
50
+ first["letter_reports"]["A"]["manifest"]["generated_at"], "reproducible"
51
+ )
52
+ self.assertEqual(
53
+ first["letter_reports"]["A"]["manifest"],
54
+ second["letter_reports"]["A"]["manifest"],
55
+ )
tests/test_backup.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for backup.py -- target resolution and dry-run behavior without network."""
2
+
3
+ import pytest
4
+
5
+ import backup
6
+
7
+
8
+ def test_resolve_targets_expands_all_without_uploading_unknowns():
9
+ assert backup._resolve_targets("A") == ["A"]
10
+ assert backup._resolve_targets("all") == list(backup.TARGETS)
11
+ with pytest.raises(ValueError, match="unknown target"):
12
+ backup._resolve_targets("missing")
13
+
14
+
15
+ def test_local_paths_keep_results_under_results_host(monkeypatch, tmp_path):
16
+ workspace = tmp_path / "workspace"
17
+ host = tmp_path / "host"
18
+ monkeypatch.setattr(backup, "WORKSPACE_ROOT", workspace)
19
+ monkeypatch.setattr(backup, "RESULTS_HOST_ROOT", host)
20
+
21
+ assert backup._local_path("results/A") == host / "results/A"
22
+ assert backup._local_path("harness") == workspace / "harness"
23
+
24
+
25
+ def test_backup_dry_run_skips_empty_targets_and_never_imports_hub(
26
+ monkeypatch, tmp_path, capsys
27
+ ):
28
+ workspace = tmp_path / "workspace"
29
+ host = tmp_path / "host"
30
+ (workspace / "harness").mkdir(parents=True)
31
+ (workspace / "harness" / "run.py").write_text("# source\n")
32
+ monkeypatch.setattr(backup, "WORKSPACE_ROOT", workspace)
33
+ monkeypatch.setattr(backup, "RESULTS_HOST_ROOT", host)
34
+ monkeypatch.setattr(backup, "TARGETS", {"code": ["harness"], "A": ["results/A"]})
35
+
36
+ uploaded = backup.backup("owner/dataset", "all", dry_run=True)
37
+
38
+ assert uploaded == ["code"]
39
+ output = capsys.readouterr().out
40
+ assert "[A] skipped" in output
41
+ assert "would upload" in output
42
+ assert str(workspace / "harness") in output
43
+
44
+
45
+ def test_target_root_rejects_mixed_workspace_and_results_roots():
46
+ with pytest.raises(ValueError, match="mixes incompatible"):
47
+ backup._target_root(["results/A", "tests"])
tests/test_encoder/conftest.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared import setup for encoder tests."""
2
+
3
+ from pathlib import Path
4
+ import sys
5
+
6
+ ROOT = Path(__file__).resolve().parents[2]
7
+ for path in (ROOT, ROOT / "encoder"):
8
+ if str(path) not in sys.path:
9
+ sys.path.insert(0, str(path))
10
+
11
+
12
+ def pytest_configure(config):
13
+ config.option.importmode = "importlib"
tests/test_encoder/test_adapters.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for encoder/adapters.py -- model-output adapters and canonical geometry validation."""
2
+
3
+ import gzip
4
+ import pickle
5
+ import sys
6
+ import types
7
+
8
+ import numpy as np
9
+ import pytest
10
+
11
+ from encoder import adapters
12
+
13
+
14
+ def test_registry_decodes_native_segvggt_dictionary(tmp_path, monkeypatch):
15
+ torch = pytest.importorskip("torch")
16
+ evaluation = types.ModuleType("eval.instance_eval_common")
17
+ evaluation.predict_by_feat_instance = lambda *args, **kwargs: (
18
+ torch.tensor([[1, 0, 0, 0], [0, 1, 0, 0]], dtype=torch.bool),
19
+ torch.tensor([0, 2]),
20
+ torch.ones(2),
21
+ )
22
+ pose = types.ModuleType("segvggt.utils.pose_enc")
23
+ pose.pose_encoding_to_extri_intri = lambda value, size: (
24
+ torch.cat(
25
+ [
26
+ torch.eye(3).reshape(1, 1, 3, 3),
27
+ torch.zeros(1, 1, 3, 1),
28
+ ],
29
+ dim=-1,
30
+ ),
31
+ torch.eye(3).reshape(1, 1, 3, 3),
32
+ )
33
+ monkeypatch.setitem(sys.modules, "eval.instance_eval_common", evaluation)
34
+ monkeypatch.setitem(sys.modules, "segvggt.utils.pose_enc", pose)
35
+
36
+ path = tmp_path / "scene.pt"
37
+ torch.save(
38
+ {
39
+ "world_points": torch.zeros(1, 1, 2, 2, 3),
40
+ "instance_maps": torch.zeros(1, 2, 1, 2, 2),
41
+ "instance_labels": torch.zeros(1, 2, 4),
42
+ "pose_enc": torch.zeros(1, 1, 9),
43
+ },
44
+ path,
45
+ )
46
+ result = adapters.adapt("segvggt", path=path)
47
+ assert list(result["instances"]) == ["chair"]
48
+ assert result["instances"]["chair"][0]["n"] == 1
49
+
50
+
51
+ def _scene():
52
+ return {
53
+ "instances": {"chair": [{"pts": [[0, 0, 0]], "best_pts": [[0, 0, 0]]}]},
54
+ "stats": {"chair": {"raw": 1, "merged": 1, "peak": 1}},
55
+ "scene_pts": [[0, 0, 0]],
56
+ "cameras": None,
57
+ }
58
+
59
+
60
+ def test_validate_normalizes_canonical_geometry():
61
+ result = adapters.validate(_scene())
62
+ instance = result["instances"]["chair"][0]
63
+ assert instance["pts"].shape == (1, 3)
64
+ assert instance["frames"] == set()
65
+ assert instance["n"] == 1
66
+
67
+
68
+ @pytest.mark.parametrize(
69
+ ("scene", "error"),
70
+ [
71
+ ([], TypeError),
72
+ ({"instances": {}}, ValueError),
73
+ (
74
+ {"instances": {"chair": [{"pts": [1, 2, 3]}]}, "scene_pts": [[0, 0, 0]]},
75
+ ValueError,
76
+ ),
77
+ ],
78
+ )
79
+ def test_validate_rejects_invalid_geometry(scene, error):
80
+ with pytest.raises(error):
81
+ adapters.validate(scene)
82
+
83
+
84
+ def test_validate_identifies_empty_scene():
85
+ with pytest.raises(adapters.EmptySceneError, match="no instances"):
86
+ adapters.validate({"instances": {}})
87
+
88
+
89
+ def test_adapt_segvggt_reads_flat_npz(tmp_path):
90
+ path = tmp_path / "scene.npz"
91
+ world = np.array([[[[0, 0, 1], [1, 0, 1]]]], np.float32)
92
+ masks = np.array([[[[True, False]]]])
93
+ np.savez(
94
+ path,
95
+ world_points=world,
96
+ instance_masks=masks,
97
+ labels=np.array(["chair"], dtype=object),
98
+ frame_times=np.array([0], np.float32),
99
+ )
100
+
101
+ result = adapters.adapt_segvggt(path=str(path))
102
+
103
+ instance = result["instances"]["chair"][0]
104
+ assert list(result["instances"]) == ["chair"]
105
+ assert instance["frames"] == {0}
106
+ assert result["stats"]["chair"] == {"raw": 1, "merged": 1, "peak": 1}
107
+
108
+
109
+ def test_adapt_segvggt_requires_existing_cache(tmp_path):
110
+ with pytest.raises(FileNotFoundError, match="raw cache does not exist"):
111
+ adapters.adapt_segvggt(path=str(tmp_path / "missing.npz"))
112
+
113
+
114
+ def test_adapter_owned_raw_cache_locations(tmp_path, monkeypatch):
115
+ seen = {}
116
+ raw_path = tmp_path / "segvggt" / "scene1.pt"
117
+ raw_path.parent.mkdir()
118
+ raw_path.touch()
119
+
120
+ def fake_segvggt(path):
121
+ seen["segvggt"] = str(path)
122
+ return {
123
+ "world_points": np.zeros((1, 1, 1, 3), np.float32),
124
+ "instance_masks": np.ones((1, 1, 1, 1), bool),
125
+ "labels": np.array(["chair"], dtype=object),
126
+ "camera_positions": np.zeros((1, 3), np.float32),
127
+ }
128
+
129
+ monkeypatch.setattr(adapters, "_decode_segvggt_raw", fake_segvggt)
130
+ adapters.adapt_segvggt(root=str(tmp_path), scene="scene1")
131
+ assert seen["segvggt"] == str(raw_path)
132
+
133
+
134
+ def test_fusion_adapter_resolves_two_native_model_directories(tmp_path, monkeypatch):
135
+ seen = {}
136
+ depth = np.ones((1, 1, 1), np.float32)
137
+ intr = np.eye(3, dtype=np.float32)[None]
138
+ c2w = np.eye(4, dtype=np.float32)[None]
139
+
140
+ def fake_da3(path):
141
+ seen["da3"] = str(path)
142
+ return depth, intr, c2w, None
143
+
144
+ def fake_sam3(path):
145
+ seen["sam3"] = str(path)
146
+ return {"object": {0: {0: np.ones((1, 1), bool)}}}
147
+
148
+ monkeypatch.setattr(adapters, "_load_native_da3", fake_da3)
149
+ monkeypatch.setattr(adapters, "_load_native_sam3", fake_sam3)
150
+ adapters.adapt_sam3_depth_anything_3(root=str(tmp_path), scene="scene1")
151
+ assert seen == {
152
+ "da3": str(tmp_path / "depth-anything-3" / "scene1.pkl"),
153
+ "sam3": str(tmp_path / "sam3" / "scene1.pt"),
154
+ }
155
+
156
+
157
+ def test_adapters_default_to_root_data_caches(monkeypatch, tmp_path):
158
+ monkeypatch.delenv("VSI_CACHE_ROOT", raising=False)
159
+ seen = {}
160
+
161
+ def fake_da3(path):
162
+ seen["da3"] = str(path)
163
+ return (
164
+ np.ones((1, 1, 1), np.float32),
165
+ np.eye(3, dtype=np.float32)[None],
166
+ np.eye(4, dtype=np.float32)[None],
167
+ None,
168
+ )
169
+
170
+ def fake_sam3(path):
171
+ seen["sam3"] = str(path)
172
+ return {"object": {0: {0: np.ones((1, 1), bool)}}}
173
+
174
+ monkeypatch.setattr(adapters, "_load_native_da3", fake_da3)
175
+ monkeypatch.setattr(adapters, "_load_native_sam3", fake_sam3)
176
+ adapters.adapt_sam3_depth_anything_3(scene="scene1")
177
+ assert seen == {
178
+ "da3": "/root/data/caches/depth-anything-3/scene1.pkl",
179
+ "sam3": "/root/data/caches/sam3/scene1.pt",
180
+ }
181
+
182
+
183
+ def test_adapt_segvggt_rejects_missing_npz_fields(tmp_path):
184
+ path = tmp_path / "broken.npz"
185
+ np.savez(path, labels=np.array(["chair"], dtype=object))
186
+ with pytest.raises(KeyError):
187
+ adapters.adapt_segvggt(path=str(path))
188
+
189
+
190
+ def test_adapt_sam3_depth_anything_3_decodes_masks_and_backprojects(tmp_path):
191
+ da3_path = tmp_path / "scene.da3.npz"
192
+ depth = np.full((1, 2, 2), 2.0, np.float32)
193
+ intrinsics = np.eye(3, dtype=np.float32)[None]
194
+ poses = np.eye(4, dtype=np.float32)[None]
195
+ np.savez(
196
+ da3_path,
197
+ depth=depth,
198
+ intr=intrinsics,
199
+ c2w=poses,
200
+ frame_times=np.array([1.5], np.float32),
201
+ )
202
+ mask = np.array([[True, False], [False, True]])
203
+ packed = {"chair": {0: {7: (np.packbits(mask), mask.shape)}}}
204
+ mask_path = tmp_path / "scene.sam3.pkl.gz"
205
+ with gzip.open(mask_path, "wb") as cache:
206
+ pickle.dump(packed, cache)
207
+
208
+ result = adapters.adapt_sam3_depth_anything_3(
209
+ da3_path=str(da3_path), sam3_path=str(mask_path)
210
+ )
211
+
212
+ instance = result["instances"]["chair"][0]
213
+ assert instance["frames"] == {0}
214
+ assert instance["first_time"] == pytest.approx(1.5)
215
+ np.testing.assert_allclose(instance["pts"], [[0, 0, 2], [2, 2, 2]])
216
+ assert result["stats"]["chair"] == {"raw": 1, "merged": 1, "peak": 1}
217
+ assert result["raw_inputs"]["per"]["chair"][0][7].dtype == bool
218
+
219
+
220
+ def test_backproject_resizes_sam3_mask_to_da3_depth_shape():
221
+ depth = np.full((2, 2), 2.0, np.float32)
222
+ mask = np.zeros((4, 4), bool)
223
+ mask[0, 0] = True
224
+ mask[2, 2] = True
225
+
226
+ points, confidence = adapters._backproject(
227
+ depth,
228
+ np.eye(3, dtype=np.float32),
229
+ np.eye(4, dtype=np.float32),
230
+ mask,
231
+ )
232
+
233
+ assert confidence is None
234
+ np.testing.assert_allclose(points, [[0, 0, 2], [2, 2, 2]])
235
+
236
+
237
+ def test_native_sam3_decodes_prompt_keyed_independent_frames(monkeypatch):
238
+ responses = {"chair": [{"masks": np.array([[[1, 0], [0, 0]]], dtype=np.uint8)}, {}]}
239
+ monkeypatch.setitem(
240
+ sys.modules,
241
+ "torch",
242
+ types.SimpleNamespace(load=lambda *args, **kwargs: responses),
243
+ )
244
+ result = adapters._load_native_sam3("scene.pt")
245
+ assert result["chair"][0][0].dtype == bool
246
+ assert result["chair"][1] == {}
247
+
248
+
249
+ def test_native_sam3_preserves_tracked_object_ids(monkeypatch):
250
+ responses = [{"out_obj_ids": np.array([7]), "out_binary_masks": np.ones((1, 2, 2))}]
251
+ monkeypatch.setitem(
252
+ sys.modules,
253
+ "torch",
254
+ types.SimpleNamespace(load=lambda *args, **kwargs: responses),
255
+ )
256
+ monkeypatch.setenv("VSI_SAM3_PROMPT", "chair")
257
+ result = adapters._load_native_sam3("scene.pt")
258
+ assert list(result["chair"][0]) == [7]
259
+
260
+
261
+ def test_native_sam3_decodes_lossless_tracking_cache(monkeypatch):
262
+ responses = {
263
+ "chair": {
264
+ "start_session": {"session_id": "session"},
265
+ "add_prompt": {"is_success": True},
266
+ "stream": [
267
+ {
268
+ "frame_index": 3,
269
+ "stream_metadata": "preserved",
270
+ "outputs": {
271
+ "out_obj_ids": np.array([7]),
272
+ "out_binary_masks": np.ones((1, 2, 2), bool),
273
+ },
274
+ }
275
+ ],
276
+ "close_session": {"is_success": True},
277
+ }
278
+ }
279
+ monkeypatch.setitem(
280
+ sys.modules,
281
+ "torch",
282
+ types.SimpleNamespace(load=lambda *args, **kwargs: responses),
283
+ )
284
+
285
+ result = adapters._load_native_sam3("scene.pt")
286
+
287
+ assert list(result["chair"][3]) == [7]
288
+
289
+
290
+ def test_spatial_code_format_validation():
291
+ assert adapters.validate_spatial_code_format("compact") == "compact"
292
+ assert adapters.validate_spatial_code_format("explicit") == "explicit"
293
+ with pytest.raises(ValueError, match="unknown spatial-code format"):
294
+ adapters.validate_spatial_code_format("unknown")
295
+
296
+
297
+ def test_native_fusion_times_are_measured_in_seconds(monkeypatch):
298
+ monkeypatch.setattr(adapters, "FPS", 4.0)
299
+ monkeypatch.setattr(
300
+ adapters,
301
+ "_load_native_da3",
302
+ lambda path: (
303
+ np.ones((3, 1, 1), np.float32),
304
+ np.repeat(np.eye(3, dtype=np.float32)[None], 3, axis=0),
305
+ np.repeat(np.eye(4, dtype=np.float32)[None], 3, axis=0),
306
+ None,
307
+ ),
308
+ )
309
+ monkeypatch.setattr(adapters, "_load_native_sam3", lambda path: {})
310
+ *_, frame_times, _ = adapters._load_fusion_inputs("scene.pkl", "scene.pt")
311
+ np.testing.assert_allclose(frame_times, [0.0, 0.25, 0.5])
tests/test_encoder/test_config.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for encoder/config.py -- cache and spatial-code path helpers."""
2
+
3
+ import pytest
4
+
5
+ from encoder import config
6
+
7
+
8
+ def test_encoder_paths_mirror_all_dimensions(tmp_path, monkeypatch):
9
+ monkeypatch.setattr(config, "CACHE_ROOT", tmp_path / "caches")
10
+ monkeypatch.setattr(config, "CODES_ROOT", tmp_path / "codes")
11
+ assert config.cache_file("scene", "metric", "uniform", "no tracking", 64).endswith(
12
+ "no tracking/frames/uniform/64/scene.pkl.gz"
13
+ )
14
+ assert config.da3_cache_file("scene", "relative", "uniform", 32).endswith(
15
+ "depth-anything-3/relative/frames/uniform/32/scene.pkl"
16
+ )
17
+ assert config.video_da3_cache_file("scene").endswith(
18
+ "depth-anything-3/metric/video/scene.npz"
19
+ )
20
+ assert config.video_da3_cache_file("scene", "relative").endswith(
21
+ "depth-anything-3/relative/video/scene.npz"
22
+ )
23
+ assert config.video_sam3_cache_file("scene").endswith(
24
+ "sam3/no tracking/video/scene.pkl.gz"
25
+ )
26
+ assert config.video_sam3_cache_file("scene", "tracking").endswith(
27
+ "sam3/tracking/video/scene.pkl.gz"
28
+ )
29
+ assert config.spatial_code_path(
30
+ "scene", "metric", "selective", "tracking", 64
31
+ ).endswith("tracking/frames/selective/64/explicit/scene.json")
32
+ assert config.spatial_code_path(
33
+ "scene", "relative", "uniform", "no tracking", 96, "compact"
34
+ ).endswith("no tracking/frames/uniform/96/compact/scene.json")
35
+ assert config.spatial_code_path(
36
+ "scene", "metric", config.VIDEO_INPUT_SELECTION, "no tracking", None, "explicit"
37
+ ).endswith("no tracking/video/explicit/scene.json")
38
+
39
+
40
+ def test_encoder_paths_reject_unknown_spatial_code_format():
41
+ with pytest.raises(ValueError, match="unknown spatial-code format"):
42
+ config.spatial_code_path(
43
+ "scene", "metric", "uniform", "tracking", 32, "unknown"
44
+ )
tests/test_encoder/test_encoder.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for encoder/geometric.py's low-level geometry primitives (backprojection,
2
+ direction/turn classification, distance, centroid/extent math)."""
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ import geometric
8
+
9
+
10
+ def test_backproject_frame_applies_intrinsics_pose_and_confidence():
11
+ depth = np.array([[2.0, 2.0], [2.0, np.nan]], np.float32)
12
+ mask = np.ones((2, 2), bool)
13
+ intrinsics = np.eye(3, dtype=np.float32)
14
+ pose = np.eye(4, dtype=np.float32)
15
+ pose[0, 3] = 1.0
16
+ confidence = np.array([[0.9, 0.8], [0.1, 1.0]], np.float32)
17
+
18
+ points, kept_confidence = geometric.backproject_frame(
19
+ depth, intrinsics, pose, mask, confidence, conf_thr=0.5, return_conf=True
20
+ )
21
+
22
+ np.testing.assert_allclose(points, [[1.0, 0.0, 2.0], [3.0, 0.0, 2.0]])
23
+ np.testing.assert_allclose(kept_confidence, [0.9, 0.8])
24
+
25
+
26
+ def test_backproject_frame_returns_typed_empty_array():
27
+ points = geometric.backproject_frame(
28
+ np.zeros((2, 2), np.float32), np.eye(3), np.eye(4), np.ones((2, 2), bool)
29
+ )
30
+ assert points.shape == (0, 3)
31
+ assert points.dtype == np.float32
32
+
33
+
34
+ def test_relative_direction_modes():
35
+ origin = np.array([0.0, 0.0, 0.0])
36
+ forward = np.array([0.0, 1.0, 0.0])
37
+ front_left = np.array([-1.0, 1.0, 0.0])
38
+ up = np.array([0.0, 0.0, 1.0])
39
+ assert (
40
+ geometric.answer_rel_direction(origin, forward, front_left, up, 2)
41
+ == "front-left"
42
+ )
43
+ assert (
44
+ geometric.answer_rel_direction(origin, forward, front_left, up, 2, "medium")
45
+ == "left"
46
+ )
47
+ assert geometric.answer_rel_direction(origin, origin, front_left, up, 2) is None
48
+
49
+
50
+ def test_closest_distance_uses_point_cloud_distance():
51
+ first = [{"pts": np.array([[0.0, 0.0, 0.0]], np.float32), "n": 1}]
52
+ second = [{"pts": np.array([[0.0, 3.0, 4.0]], np.float32), "n": 1}]
53
+ assert geometric.answer_closest_distance(first, second) == pytest.approx(5.0)
54
+
55
+
56
+ def test_robust_centroid_extent_returns_sorted_dimensions():
57
+ points = np.array(
58
+ [[x, y, z] for x in (-2.0, 2.0) for y in (-1.0, 1.0) for z in (-0.5, 0.5)],
59
+ np.float32,
60
+ )
61
+ centroid, longest, dimensions = geometric.robust_centroid_extent(points, up_axis=2)
62
+ np.testing.assert_allclose(centroid, [0.0, 0.0, 0.0])
63
+ assert longest > 3.0
64
+ assert np.all(dimensions[:-1] >= dimensions[1:])
65
+
66
+
67
+ def test_depth_edges_handles_small_and_discontinuous_frames():
68
+ small = np.ones((5, 5), np.float32)
69
+ assert not geometric.depth_edges(small, np.ones_like(small, bool)).any()
70
+ depth = np.ones((20, 20), np.float32)
71
+ depth[:, 10:] = 10.0
72
+ edges = geometric.depth_edges(depth, np.ones_like(depth, bool))
73
+ assert edges[:, 9:11].any()
tests/test_encoder/test_geometric.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for encoder/geometric.py -- spatial-code schema construction and derivation."""
2
+
3
+ import json
4
+ import re
5
+
6
+ import numpy as np
7
+
8
+ import geometric
9
+
10
+
11
+ def test_dump_spatial_code(tmp_path):
12
+ path = tmp_path / "scene.json"
13
+ geometric.dump_spatial_code({"objects": {}, "appearance order": []}, path)
14
+ assert path.exists()
15
+ assert '"appearance order"' in path.read_text()
16
+
17
+
18
+ def test_raw_bundle_dispatches_to_explicit_derivation(monkeypatch):
19
+ expected = (
20
+ {
21
+ "spatial code schema": geometric.EXPLICIT_SPATIAL_CODE_SCHEMA,
22
+ "objects": {},
23
+ "room": {"floor area": "0.0 square meters"},
24
+ "closest classes distance meters from": {},
25
+ "appearance order": [],
26
+ },
27
+ {},
28
+ {},
29
+ 1,
30
+ np.array([0, 1, 0], dtype=np.float32),
31
+ 0.0,
32
+ )
33
+ seen = {}
34
+
35
+ def fake(scene):
36
+ seen["scene"] = scene
37
+ return expected
38
+
39
+ monkeypatch.setattr(geometric, "build_explicit_spatial_code", fake)
40
+ raw = {
41
+ "depth": np.ones((1, 2, 2), np.float32),
42
+ "intr": np.eye(3, dtype=np.float32)[None],
43
+ "c2w": np.eye(4, dtype=np.float32)[None],
44
+ "conf": None,
45
+ "ftimes": np.array([0.0], np.float32),
46
+ "per": {"chair": {}},
47
+ }
48
+ scene = {"raw_inputs": raw}
49
+ assert geometric.build_spatial_code(scene) is expected
50
+ assert seen["scene"] is scene
51
+
52
+
53
+ def test_explicit_is_a_derivation_of_compact(monkeypatch):
54
+ """build_explicit_spatial_code() must always build compact FIRST and derive from it --
55
+ not measure geometry independently."""
56
+ compact_expected = (
57
+ {
58
+ "spatial code schema": geometric.COMPACT_SPATIAL_CODE_SCHEMA,
59
+ "objects": {},
60
+ "room": {},
61
+ },
62
+ {},
63
+ {},
64
+ 1,
65
+ np.array([0, 1, 0], dtype=np.float32),
66
+ None,
67
+ )
68
+ seen = {}
69
+
70
+ def fake_compact(scene):
71
+ seen["scene"] = scene
72
+ return compact_expected
73
+
74
+ monkeypatch.setattr(geometric, "build_compact_spatial_code", fake_compact)
75
+ scene = {"raw_inputs": None}
76
+ code, *_ = geometric.build_explicit_spatial_code(scene)
77
+ assert seen["scene"] is scene
78
+ assert code["objects"] == {}
79
+
80
+
81
+ def test_exact_math_is_integrated_into_geometric_module():
82
+ assert callable(geometric.build_explicit_spatial_code)
83
+ assert callable(geometric.dump_spatial_code)
84
+ assert not hasattr(geometric, "_reference")
85
+
86
+
87
+ def test_position_reader_accepts_current_and_legacy_formatting():
88
+ assert geometric.pos3(
89
+ {
90
+ "position": {
91
+ "x coordinate": "1.25 meters",
92
+ "y coordinate": "-2.0 meters",
93
+ "height above floor": "0.5 meters",
94
+ }
95
+ }
96
+ ) == [1.25, -2.0, 0.5]
97
+ assert geometric.pos3(
98
+ {
99
+ "position": {
100
+ "floor_x_meters": 1.25,
101
+ "floor_y_meters": -2.0,
102
+ "height_above_floor_meters": 0.5,
103
+ }
104
+ }
105
+ ) == [1.25, -2.0, 0.5]
106
+
107
+
108
+ def test_floor_level_v1_v2_math_is_shared(monkeypatch):
109
+ points = np.array([[0, 0, z] for z in [0, 0, 0, 1, 10]], np.float32)
110
+ gravity = np.array([0, 0, 1], np.float32)
111
+ monkeypatch.delenv("VSI_CODE_V2", raising=False)
112
+ v1 = geometric._floor_level(points, gravity)
113
+ monkeypatch.setenv("VSI_CODE_V2", "1")
114
+ v2 = geometric._floor_level(points, gravity)
115
+ assert 0 <= v1 < 0.2
116
+ assert v2 == 0.0
117
+
118
+
119
+ METERS = re.compile(r"^-?\d+(?:\.\d+)? meters$")
120
+ SQUARE_METERS = re.compile(r"^\d+(?:\.\d+)? square meters$")
121
+
122
+
123
+ def _schema_instance(x, y, z, size, first_time=0.0):
124
+ pts = np.array(
125
+ [
126
+ [x - size / 2, y, z],
127
+ [x + size / 2, y, z],
128
+ [x, y - size / 2, z],
129
+ [x, y + size / 2, z],
130
+ ],
131
+ dtype=np.float32,
132
+ )
133
+ return {
134
+ "pts": pts,
135
+ "best_pts": pts,
136
+ "n": len(pts),
137
+ "nframes": 1,
138
+ "first_time": first_time,
139
+ "frames": {0},
140
+ }
141
+
142
+
143
+ def _schema_scene():
144
+ chair = _schema_instance(0.0, 0.0, 0.5, 0.8, first_time=0.0)
145
+ table = _schema_instance(1.0, 0.0, 0.7, 1.2, first_time=1.0)
146
+ floor = np.array(
147
+ [[x, y, 0.0] for x in np.linspace(-1, 2, 5) for y in np.linspace(-1, 1, 5)],
148
+ dtype=np.float32,
149
+ )
150
+ return {
151
+ "instances": {"chair": [chair], "table": [table]},
152
+ "stats": {"chair": {"peak": 1}, "table": {"peak": 3}},
153
+ "scene_pts": np.concatenate([chair["pts"], table["pts"], floor], axis=0),
154
+ "cameras": None,
155
+ }
156
+
157
+
158
+ def test_spatial_code_matches_reference_schema():
159
+ code, *_ = geometric.build_spatial_code(_schema_scene())
160
+ assert list(code) == [
161
+ "spatial code schema",
162
+ "objects",
163
+ "room",
164
+ "closest classes distance meters from",
165
+ "appearance order",
166
+ ]
167
+ assert code["spatial code schema"] == geometric.EXPLICIT_SPATIAL_CODE_SCHEMA
168
+ assert code["appearance order"] == ["chair", "table"]
169
+ assert SQUARE_METERS.match(code["room"]["floor area"])
170
+ for class_data in code["objects"].values():
171
+ assert set(class_data) == {"count", "instances"}
172
+ assert class_data["count"] == len(class_data["instances"])
173
+ for instance in class_data["instances"]:
174
+ assert set(instance) == {"position", "longest dimension"}
175
+ assert set(instance["position"]) == {
176
+ "x coordinate",
177
+ "y coordinate",
178
+ "height above floor",
179
+ }
180
+ assert all(METERS.match(value) for value in instance["position"].values())
181
+ assert METERS.match(instance["longest dimension"])
182
+ assert code["objects"]["table"]["count"] == 1
183
+ chair_to_table = code["closest classes distance meters from"]["chair"]["table"]
184
+ assert set(chair_to_table) == {"distance", "closeness rank"}
185
+ assert METERS.match(chair_to_table["distance"])
186
+ assert chair_to_table["closeness rank"] == 1
187
+
188
+
189
+ def test_dumped_json_preserves_schema(tmp_path):
190
+ code, *_ = geometric.build_spatial_code(_schema_scene())
191
+ path = tmp_path / "scene.json"
192
+ geometric.dump_spatial_code(code, path)
193
+ assert json.loads(path.read_text()) == code
194
+
195
+
196
+ def test_compact_spatial_code_exposes_only_reusable_primitives():
197
+ code, *_ = geometric.build_spatial_code(_schema_scene(), "compact")
198
+ assert list(code) == ["spatial code schema", "objects", "room"]
199
+ assert set(code["objects"]) == {"chair", "table"}
200
+ assert len(code["objects"]["chair"]) == 1
201
+ instance = code["objects"]["chair"][0]
202
+ assert set(instance) == {"3D oriented bounding box", "first visible time"}
203
+ box = instance["3D oriented bounding box"]
204
+ assert set(box) == {
205
+ "3D oriented bounding box center coordinates",
206
+ "3D oriented bounding box dimensions",
207
+ "3D oriented bounding box orientation unit vectors",
208
+ }
209
+ assert len(box["3D oriented bounding box center coordinates"]) == 3
210
+ assert len(box["3D oriented bounding box dimensions"]) == 3
211
+ orientation = np.asarray(
212
+ box["3D oriented bounding box orientation unit vectors"], dtype=np.float64
213
+ )
214
+ np.testing.assert_allclose(orientation @ orientation.T, np.eye(3), atol=0.02)
215
+ assert instance["first visible time"] == 0.0
216
+ polygons = code["room"]["floor boundary polygons"]
217
+ assert len(polygons) == 1
218
+ assert len(polygons[0]["outer boundary coordinates"]) >= 3
219
+ for hole in polygons[0]["interior hole boundary coordinates"]:
220
+ assert len(hole) >= 3
221
+ assert all(len(coordinate) == 2 for coordinate in hole)
222
+ assert "closest classes distance meters from" not in code
223
+ assert "appearance order" not in code
224
+
225
+
226
+ def test_explicit_spatial_code_remains_the_default():
227
+ default, *_ = geometric.build_spatial_code(_schema_scene())
228
+ code, *_ = geometric.build_spatial_code(_schema_scene(), "explicit")
229
+ assert default == code
230
+
231
+
232
+ def test_compact_spatial_code_merges_revisit_instances_and_keeps_earliest_time():
233
+ scene = _schema_scene()
234
+ revisit = dict(scene["instances"]["chair"][0])
235
+ revisit.update({"frames": {1}, "first_time": -1.0})
236
+ scene["instances"]["chair"].append(revisit)
237
+ scene["stats"]["chair"] = {"raw": 2, "merged": 2, "peak": 1}
238
+
239
+ code, instances, *_ = geometric.build_spatial_code(scene, "compact")
240
+
241
+ assert len(instances["chair"]) == 1
242
+ assert len(code["objects"]["chair"]) == 1
243
+ assert code["objects"]["chair"][0]["first visible time"] == -1.0
244
+
245
+
246
+ def test_compact_oriented_box_uses_accumulated_instance_points():
247
+ xs = np.linspace(-2.0, 2.0, 80)
248
+ points = np.stack([xs, np.zeros_like(xs), np.full_like(xs, 0.5)], axis=1)
249
+ instance = {
250
+ "pts": points.astype(np.float32),
251
+ "best_pts": points[38:42].astype(np.float32),
252
+ "conf": None,
253
+ }
254
+
255
+ box = geometric._compact_oriented_box(
256
+ instance,
257
+ np.array([1.0, 0.0, 0.0]),
258
+ np.array([0.0, 1.0, 0.0]),
259
+ np.array([0.0, 0.0, 1.0]),
260
+ 0.0,
261
+ )
262
+
263
+ assert max(box["3D oriented bounding box dimensions"]) > 3.5
264
+
265
+
266
+ def test_compact_floor_boundaries_preserve_disconnected_regions():
267
+ first = np.array(
268
+ [[x, y, 0.0] for x in np.linspace(0, 1, 11) for y in np.linspace(0, 1, 11)]
269
+ )
270
+ second = np.array(
271
+ [[x, y, 0.0] for x in np.linspace(5, 6, 11) for y in np.linspace(0, 1, 11)]
272
+ )
273
+
274
+ polygons = geometric._compact_floor_boundary_polygons(
275
+ np.concatenate([first, second]),
276
+ np.array([1.0, 0.0, 0.0]),
277
+ np.array([0.0, 1.0, 0.0]),
278
+ )
279
+
280
+ assert len(polygons) == 2
281
+ assert all(len(polygon["outer boundary coordinates"]) >= 3 for polygon in polygons)
282
+
283
+
284
+ def test_compact_spatial_code_suppresses_co_visible_duplicate_tracks():
285
+ points = np.array(
286
+ [[x, y, z] for x in (-0.5, 0.5) for y in (-0.5, 0.5) for z in (0.0, 1.0)],
287
+ dtype=np.float32,
288
+ )
289
+ first = {
290
+ "pts": points,
291
+ "best_pts": points,
292
+ "observations": [points],
293
+ "frames": {0},
294
+ "n": len(points),
295
+ "nframes": 1,
296
+ "first_time": 0.0,
297
+ }
298
+ second = dict(first)
299
+ second.update({"pts": points + 0.01, "best_pts": points + 0.01})
300
+ scene = {
301
+ "instances": {"chair": [first, second]},
302
+ "stats": {"chair": {"raw": 2, "merged": 2, "peak": 2}},
303
+ "scene_pts": np.concatenate([points, points + 0.01]),
304
+ "cameras": None,
305
+ }
306
+
307
+ code, instances, *_ = geometric.build_spatial_code(scene, "compact")
308
+
309
+ assert len(instances["chair"]) == 1
310
+ assert len(code["objects"]["chair"]) == 1
311
+
312
+
313
+ def test_compact_oriented_box_combines_observation_extents_by_consensus():
314
+ narrow_x = np.linspace(-1.0, 1.0, 80)
315
+ wide_x = np.linspace(-2.0, 2.0, 80)
316
+ narrow = np.stack(
317
+ [narrow_x, np.zeros_like(narrow_x), np.full_like(narrow_x, 0.5)], axis=1
318
+ ).astype(np.float32)
319
+ wide = np.stack(
320
+ [wide_x, np.zeros_like(wide_x), np.full_like(wide_x, 0.5)], axis=1
321
+ ).astype(np.float32)
322
+ instance = {
323
+ "pts": np.concatenate([narrow, wide]),
324
+ "best_pts": narrow,
325
+ "observations": [narrow, wide],
326
+ "conf": None,
327
+ }
328
+
329
+ box = geometric._compact_oriented_box(
330
+ instance,
331
+ np.array([1.0, 0.0, 0.0]),
332
+ np.array([0.0, 1.0, 0.0]),
333
+ np.array([0.0, 0.0, 1.0]),
334
+ 0.0,
335
+ )
336
+
337
+ # The LONGEST axis recovers the fullest observed extent (the wide view's full 4.0 span),
338
+ # not the cross-observation consensus -- a partial view underestimates true length, so the
339
+ # object is at least as long as the fullest clean view saw (see _compact_oriented_box's
340
+ # length-axis decoupling). Width/depth stay on the robust consensus.
341
+ assert 3.9 < max(box["3D oriented bounding box dimensions"]) <= 4.0
342
+
343
+
344
+ def test_compact_instances_keep_peak_co_visible_hypotheses_by_evidence():
345
+ scene = _schema_scene()
346
+ weak = _schema_instance(4.0, 0.0, 0.5, 0.8, first_time=-1.0)
347
+ weak.update({"n": 4, "nframes": 1, "frames": {2}})
348
+ strong = scene["instances"]["chair"][0]
349
+ strong.update({"n": 40, "nframes": 3, "frames": {0, 1, 2}})
350
+ scene["instances"]["chair"] = [weak, strong]
351
+ scene["stats"]["chair"] = {"raw": 2, "merged": 2, "peak": 1}
352
+
353
+ code, instances, *_ = geometric.build_spatial_code(scene, "compact")
354
+
355
+ assert len(instances["chair"]) == 1
356
+ assert instances["chair"][0]["nframes"] == 3
357
+ assert instances["chair"][0]["first_time"] == -1.0
358
+ assert len(code["objects"]["chair"]) == 1
359
+
360
+
361
+ def test_compact_oriented_box_rejects_one_inconsistent_observation():
362
+ ordinary = np.stack(
363
+ [
364
+ np.linspace(-1.0, 1.0, 80),
365
+ np.zeros(80),
366
+ np.full(80, 0.5),
367
+ ],
368
+ axis=1,
369
+ ).astype(np.float32)
370
+ outlier = ordinary.copy()
371
+ outlier[:, 0] *= 20
372
+ instance = {
373
+ "pts": np.concatenate([ordinary] * 4 + [outlier]),
374
+ "best_pts": ordinary,
375
+ "observations": [ordinary] * 4 + [outlier],
376
+ "conf": None,
377
+ }
378
+
379
+ box = geometric._compact_oriented_box(
380
+ instance,
381
+ np.array([1.0, 0.0, 0.0]),
382
+ np.array([0.0, 1.0, 0.0]),
383
+ np.array([0.0, 0.0, 1.0]),
384
+ 0.0,
385
+ )
386
+
387
+ assert max(box["3D oriented bounding box dimensions"]) < 3.0
tests/test_encoder/test_init.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Tests for encoder package importability."""
2
+
3
+ import encoder
4
+
5
+
6
+ def test_encoder_package_imports_without_data_or_checkpoints():
7
+ assert encoder.__doc__ == "Spatial-code encoder package."