diff --git a/tests/__init__.py b/tests/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/tests/conftest.py b/tests/conftest.py deleted file mode 100644 index b3e6dee61311f2de0e466b631d7d133c0c3c98fe..0000000000000000000000000000000000000000 --- a/tests/conftest.py +++ /dev/null @@ -1,48 +0,0 @@ -"""Global test setup that keeps unit tests independent of optional native packages.""" - -from __future__ import annotations - -import importlib.util -import sys -import types -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - - -class _FakeCapture: - def __init__(self, path): - self.path = path - - def get(self, prop): - return 0.0 - - def release(self): - pass - - -if importlib.util.find_spec("cv2") is None and "cv2" not in sys.modules: - cv2 = types.ModuleType("cv2") - cv2.CAP_PROP_FPS = 5 - cv2.INTER_NEAREST = 0 - cv2.MORPH_CLOSE = 3 - cv2.RETR_EXTERNAL = 0 - cv2.RETR_CCOMP = 2 - cv2.CHAIN_APPROX_SIMPLE = 0 - cv2.GC_PR_BGD = 2 - cv2.GC_PR_FGD = 3 - cv2.GC_FGD = 1 - cv2.GC_INIT_WITH_MASK = 1 - cv2.VideoCapture = _FakeCapture - cv2.resize = lambda image, size, interpolation=None: image - cv2.erode = lambda image, kernel, iterations=1: image - cv2.dilate = lambda image, kernel, iterations=1: image - cv2.morphologyEx = lambda image, op, kernel: image - cv2.findContours = lambda image, mode, method: ([], None) - cv2.approxPolyDP = lambda contour, epsilon, closed: contour - cv2.contourArea = lambda contour: 0 - cv2.imread = lambda path: None - cv2.grabCut = lambda *args, **kwargs: None - sys.modules["cv2"] = cv2 diff --git a/tests/test_A/__init__.py b/tests/test_A/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/tests/test_A/conftest.py b/tests/test_A/conftest.py deleted file mode 100644 index 9b2e5b391443b0e130a6ef1a62715ad5dac8a90d..0000000000000000000000000000000000000000 --- a/tests/test_A/conftest.py +++ /dev/null @@ -1,12 +0,0 @@ -"""Shared import setup for harness.A tests.""" - -from pathlib import Path -import sys - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - - -def pytest_configure(config): - config.option.importmode = "importlib" diff --git a/tests/test_A/test_A.py b/tests/test_A/test_A.py deleted file mode 100644 index 9d1a579272dc908d5b01d46c0ba68782fb354ee0..0000000000000000000000000000000000000000 --- a/tests/test_A/test_A.py +++ /dev/null @@ -1,68 +0,0 @@ -"""Tests for harness/A/__init__.py -- shared config constants.""" - -from argparse import ArgumentParser, Namespace -from pathlib import Path - -import pytest - -from harness import A - - -def test_thinking_mode_resolves_default_budgets(): - args = Namespace(extended=True, reasoning_budget=None, force_budget=None) - A.resolve_protocol_budgets(ArgumentParser(), args) - assert args.reasoning_budget == A.EXTENDED_MAX_NEW_TOKENS - assert args.force_budget == A.MAX_NEW_TOKENS - - -def test_base_mode_keeps_budgets_unset_without_budget_flags(): - args = Namespace(extended=False, reasoning_budget=None, force_budget=None) - A.resolve_protocol_budgets(ArgumentParser(), args) - assert args.reasoning_budget is None - assert args.force_budget is None - - -@pytest.mark.parametrize("flag", ["reasoning_budget", "force_budget"]) -def test_base_mode_rejects_thinking_budget_flags(flag): - args = Namespace(extended=False, reasoning_budget=None, force_budget=None) - setattr(args, flag, 8) - with pytest.raises(SystemExit): - A.resolve_protocol_budgets(ArgumentParser(), args) - - -def test_generation_protocol_matches_vsibench_yaml(): - # thinking-in-space/lmms_eval/tasks/vsibench/vsibench.yaml generation_kwargs. - assert A.MAX_NEW_TOKENS == 16 - assert A.TEMPERATURE == 0.0 - assert A.DO_SAMPLE is False - - -def test_thinking_generation_protocol(): - assert A.EXTENDED_MAX_NEW_TOKENS == 2048 - assert A.EXTENDED_MAX_NEW_TOKENS > A.MAX_NEW_TOKENS - assert isinstance(A.FORCE_ANSWER_PROMPT, str) and A.FORCE_ANSWER_PROMPT.strip() - - -def test_frame_selections_match_inference_vocabulary(): - from inference import SAM3_FRAME_SELECTIONS - - assert A.FRAME_SELECTIONS == SAM3_FRAME_SELECTIONS - - -def test_default_frame_selection_is_a_valid_selection(): - assert A.DEFAULT_FRAME_SELECTION in A.FRAME_SELECTIONS - - -def test_model_paths_cover_every_registered_model(): - assert set(A.MODEL_PATHS) == { - "qwen3.5-4b", - "qwen3.5-2b", - "internvl3.5-4b", - "internvl3.5-2b", - } - for path in A.MODEL_PATHS.values(): - assert path.parent == A.MODELS_ROOT - - -def test_results_dir_defaults_under_root_results(): - assert A.RESULTS_DIR == Path("/root/results/A") diff --git a/tests/test_A/test_frames.py b/tests/test_A/test_frames.py deleted file mode 100644 index 72483e70c8437eb054776910c046d9b4e119356b..0000000000000000000000000000000000000000 --- a/tests/test_A/test_frames.py +++ /dev/null @@ -1,79 +0,0 @@ -"""Tests for harness/A/frames.py -- uniform/selective frame sampling.""" - -import numpy as np -import pytest - -from harness.A import frames as frame_sampling - - -def test_sample_frames_rejects_unknown_selection(tmp_path): - video = tmp_path / "scene.mp4" - video.write_bytes(b"not a real video") - with pytest.raises(ValueError): - frame_sampling.sample_frames(str(video), 8, "random") - - -def test_sample_frames_rejects_nonpositive_frame_count(tmp_path): - video = tmp_path / "scene.mp4" - video.write_bytes(b"not a real video") - with pytest.raises(ValueError): - frame_sampling.sample_frames(str(video), 0, "uniform") - - -def test_sample_frames_rejects_missing_video(tmp_path): - with pytest.raises(FileNotFoundError): - frame_sampling.sample_frames(str(tmp_path / "missing.mp4"), 8, "uniform") - - -def test_sample_frames_returns_pil_images_in_order(tmp_path, monkeypatch): - video = tmp_path / "scene.mp4" - video.write_bytes(b"not a real video") - fake_frames = np.stack( - [np.full((4, 4, 3), value, dtype=np.uint8) for value in (10, 20, 30)] - ) - monkeypatch.setattr( - frame_sampling, - "_sample_video_frames", - lambda path, count, selection: (fake_frames, np.array([0.0, 1.0, 2.0])), - ) - - class _UnreadableCapture: - def get(self, prop): - return 0.0 - - def release(self): - pass - - monkeypatch.setattr( - frame_sampling.cv2, "VideoCapture", lambda path: _UnreadableCapture() - ) - result, timestamps, indices = frame_sampling.sample_frames(str(video), 3, "uniform") - assert len(result) == 3 - assert np.array(result[0])[0, 0, 0] == 10 - assert np.array(result[2])[0, 0, 0] == 30 - assert timestamps == [0.0, 1.0, 2.0] - # fps falls back to 1.0 for the fake (unreadable) video, so index == round(t * 1.0) == t. - assert indices == [0, 1, 2] - - -def test_sample_frames_derives_indices_from_real_fps(tmp_path, monkeypatch): - video = tmp_path / "scene.mp4" - video.write_bytes(b"not a real video") - fake_frames = np.stack([np.full((2, 2, 3), 1, dtype=np.uint8)] * 3) - monkeypatch.setattr( - frame_sampling, - "_sample_video_frames", - lambda path, count, selection: (fake_frames, np.array([0.0, 0.5, 1.0])), - ) - - class _FakeCapture: - def get(self, prop): - return 30.0 - - def release(self): - pass - - monkeypatch.setattr(frame_sampling.cv2, "VideoCapture", lambda path: _FakeCapture()) - _, timestamps, indices = frame_sampling.sample_frames(str(video), 3, "uniform") - assert timestamps == [0.0, 0.5, 1.0] - assert indices == [0, 15, 30] diff --git a/tests/test_A/test_init.py b/tests/test_A/test_init.py deleted file mode 100644 index 7b7253493822d2434abdccdcbf41bacdc68b0430..0000000000000000000000000000000000000000 --- a/tests/test_A/test_init.py +++ /dev/null @@ -1,60 +0,0 @@ -"""Tests for harness/A/__init__.py -- shared config constants.""" - -from harness import A - - -def test_generation_protocol_matches_vsibench_yaml(): - # thinking-in-space/lmms_eval/tasks/vsibench/vsibench.yaml generation_kwargs. - assert A.MAX_NEW_TOKENS == 16 - assert A.TEMPERATURE == 0.0 - assert A.DO_SAMPLE is False - - -def test_thinking_generation_protocol(): - assert A.EXTENDED_MAX_NEW_TOKENS == 2048 - assert A.EXTENDED_MAX_NEW_TOKENS > A.MAX_NEW_TOKENS - assert isinstance(A.FORCE_ANSWER_PROMPT, str) and A.FORCE_ANSWER_PROMPT.strip() - - -def test_frame_selections_match_inference_vocabulary(): - from inference import SAM3_FRAME_SELECTIONS - - assert A.FRAME_SELECTIONS == SAM3_FRAME_SELECTIONS - - -def test_default_frame_selection_is_a_valid_selection(): - assert A.DEFAULT_FRAME_SELECTION in A.FRAME_SELECTIONS - - -def test_model_paths_cover_every_registered_model(): - assert set(A.MODEL_PATHS) == { - "qwen3.5-4b", - "qwen3.5-2b", - "internvl3.5-4b", - "internvl3.5-2b", - } - for path in A.MODEL_PATHS.values(): - assert path.parent == A.MODELS_ROOT - - -def test_results_dir_defaults_under_workspace_results(): - assert A.RESULTS_DIR == A.WORKSPACE_ROOT / "results" / "A" - - -def test_question_protocol_policy_is_hardcoded_by_group(): - assert A.question_group("object_counting") == "numerical" - assert A.protocol_for_question("object_counting") == "base" - assert A.question_group("route_planning") == "multiple_choice" - assert A.protocol_for_question("route_planning") == "thinking" - - -def test_every_known_question_type_has_one_policy_group(): - for question_type in A.NUMERICAL_QUESTION_TYPES: - assert ( - A.protocol_for_question(question_type) == A.QUESTION_PROTOCOLS["numerical"] - ) - for question_type in A.MULTIPLE_CHOICE_QUESTION_TYPES: - assert ( - A.protocol_for_question(question_type) - == A.QUESTION_PROTOCOLS["multiple_choice"] - ) diff --git a/tests/test_A/test_launch.py b/tests/test_A/test_launch.py deleted file mode 100644 index a324b60ddafd730667795b914b85b9b9a3dc0952..0000000000000000000000000000000000000000 --- a/tests/test_A/test_launch.py +++ /dev/null @@ -1,90 +0,0 @@ -"""Tests for harness/A/launch.py -- multi-GPU scene sharding across workers.""" - -import pytest - -from harness.A import launch - - -def test_launcher_imports(): - assert callable(launch.main) - - -def test_scenes_dedups_and_preserves_order(tmp_path, monkeypatch): - manifest = tmp_path / "questions.jsonl" - rows = [ - '{"scene_name": "scene-a"}', - '{"scene_name": "scene-b"}', - '{"scene_name": "scene-a"}', - ] - manifest.write_text("\n".join(rows) + "\n") - monkeypatch.setattr(launch, "JSONL", manifest) - assert launch.scenes() == ["scene-a", "scene-b"] - - -class _FakeRun: - rows = [{"id": 1}, {"id": 2}] - - @staticmethod - def results_dir_for( - model, protocol, frame_selection, frame_count, results_dir=None - ): - return results_dir - - @classmethod - def load_questions(cls, scene=None): - return list(cls.rows) - - -def test_launch_skips_scene_already_fully_answered(tmp_path, capsys, monkeypatch): - scene = "scene-a" - monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) - - scene_dir = tmp_path / scene - scene_dir.mkdir() - for row in _FakeRun.rows: - (scene_dir / f"{row['id']}.json").write_text("{}") - - launch.launch("qwen3.5-2b", "uniform", 16, [scene], results_dir=tmp_path) - - output = capsys.readouterr().out - assert "skipped" in output - assert "DONE: 1 ok, 0 failed" in output - - -def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch): - scene = "scene-a" - monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) - scene_dir = tmp_path / scene - scene_dir.mkdir() - for row in _FakeRun.rows: - (scene_dir / f"{row['id']}.json").write_text("{}") - - monkeypatch.setattr(launch, "visible_gpus", lambda: []) - - # Only assert it treats the scene as pending (doesn't take the all-skipped early - # return); actually spawning workers needs a real model/GPU, exercised by the live - # harness.A.launch smoke run instead of the unit suite. - monkeypatch.setattr( - launch.mp, - "get_context", - lambda *_: (_ for _ in ()).throw( - RuntimeError("rebuild correctly reached worker dispatch") - ), - ) - try: - launch.launch( - "qwen3.5-2b", "uniform", 16, [scene], results_dir=tmp_path, rebuild=True - ) - except RuntimeError as exc: - assert "rebuild correctly reached worker dispatch" in str(exc) - else: - raise AssertionError("expected rebuild to force scene into the pending path") - - -def test_launch_rejects_scene_with_no_questions(monkeypatch, tmp_path): - class EmptyRun(_FakeRun): - rows = [] - - monkeypatch.setattr(launch, "_load_run_module", lambda: EmptyRun) - with pytest.raises(ValueError, match="no questions found"): - launch.launch("qwen3.5-2b", "uniform", 16, ["missing"], results_dir=tmp_path) diff --git a/tests/test_A/test_models.py b/tests/test_A/test_models.py deleted file mode 100644 index 0331c260adf20ccf1d4c6a5a3c41d5a273b966db..0000000000000000000000000000000000000000 --- a/tests/test_A/test_models.py +++ /dev/null @@ -1,94 +0,0 @@ -"""Tests for harness/A/models.py -- VLM adapter registry and prompt assembly. - -Deliberately excludes any test that loads real model weights or calls .generate() -- -those require the GPU and downloaded checkpoints and are exercised via harness.A.run -smoke runs instead, not the unit suite. -""" - -import pytest - -from harness import A -from harness.A import models as vlm_models - - -def test_all_three_models_are_registered(): - assert vlm_models.available_models() == ( - "internvl3.5-2b", - "internvl3.5-4b", - "qwen3.5-2b", - "qwen3.5-4b", - ) - - -def test_get_adapter_binds_the_correct_checkpoint_path(): - adapter = vlm_models.get_adapter("qwen3.5-4b") - assert adapter.model_path == A.MODEL_PATHS["qwen3.5-4b"] - assert isinstance(adapter, vlm_models.QwenVLAdapter) - - -def test_get_adapter_returns_the_right_class_per_model(): - assert isinstance(vlm_models.get_adapter("qwen3.5-2b"), vlm_models.QwenVLAdapter) - assert isinstance( - vlm_models.get_adapter("internvl3.5-4b"), vlm_models.InternVLAdapter - ) - - -def test_get_adapter_rejects_unknown_model(): - with pytest.raises(KeyError): - vlm_models.get_adapter("not-a-real-model") - - -def test_internvl_adapter_disables_per_frame_tiling(): - # Otherwise InternVL's default per-image dynamic tiling (~3300 tokens/frame) blows - # past this checkpoint's 40960-token context window at just 16 frames. - assert vlm_models.InternVLAdapter.chat_template_kwargs == {"crop_to_patches": False} - - -def test_numbered_content_labels_every_frame_in_order(): - frames = ["frame0", "frame1", "frame2"] - content = vlm_models._numbered_content(frames, "What is in the room?") - assert content[0] == {"type": "text", "text": "Frame 1:"} - assert content[1] == {"type": "image", "image": "frame0"} - assert content[-1] == {"type": "text", "text": "What is in the room?"} - image_items = [item for item in content if item["type"] == "image"] - assert [item["image"] for item in image_items] == frames - - -def test_numbered_content_handles_zero_frames(): - content = vlm_models._numbered_content([], "question only") - assert content == [{"type": "text", "text": "question only"}] - - -def test_adapter_answer_before_load_model_raises(): - adapter = vlm_models.get_adapter("qwen3.5-2b") - with pytest.raises(RuntimeError): - adapter.answer(["frame"], "question") - - -def test_adapter_answer_extended_before_load_model_raises(): - adapter = vlm_models.get_adapter("qwen3.5-2b") - with pytest.raises(RuntimeError): - adapter.answer_extended(["frame"], "question") - - -def test_every_adapter_implements_answer_extended(): - for model in vlm_models.available_models(): - adapter = vlm_models.get_adapter(model) - assert callable(adapter.answer_extended) - - -def test_unload_clears_model_and_processor(): - adapter = vlm_models.get_adapter("qwen3.5-2b") - adapter.model = object() - adapter.processor = object() - adapter.unload() - assert adapter.model is None - assert adapter.processor is None - - -def test_native_video_content_uses_one_video_item(): - content = vlm_models._numbered_content("/data/scene.mp4", "What is in the room?") - assert content == [ - {"type": "video", "video": "/data/scene.mp4"}, - {"type": "text", "text": "What is in the room?"}, - ] diff --git a/tests/test_A/test_prompts.py b/tests/test_A/test_prompts.py deleted file mode 100644 index 48a01d6e607b610581d5d241ae66f29899d0301d..0000000000000000000000000000000000000000 --- a/tests/test_A/test_prompts.py +++ /dev/null @@ -1,55 +0,0 @@ -"""Tests for harness/A/prompts.py -- VSI-Bench prompt construction.""" - -import pytest - -from harness.A import prompts as vsi_prompts - - -def test_na_question_prompt_matches_vsibench_protocol(): - prompt = vsi_prompts.build_prompt("object_counting", "How many chairs?") - assert prompt == ( - "These are frames of a video.\n" - "How many chairs?\n" - "Please answer the question using a single word or phrase." - ) - - -def test_mca_question_prompt_matches_vsibench_protocol(): - prompt = vsi_prompts.build_prompt( - "object_rel_distance", "Which is closest?", ["A. sofa", "B. table"] - ) - assert prompt == ( - "These are frames of a video.\n" - "Which is closest?\n" - "Options:\nA. sofa\nB. table\n" - "Answer with the option's letter from the given choices directly." - ) - - -def test_mca_question_requires_options(): - with pytest.raises(ValueError): - vsi_prompts.build_prompt("route_planning", "Which way?", None) - - -def test_unknown_question_type_rejected(): - with pytest.raises(ValueError): - vsi_prompts.build_prompt("not_a_real_type", "?", None) - - -@pytest.mark.parametrize("question_type", vsi_prompts.NA_QUESTION_TYPES) -def test_every_na_question_type_builds_without_options(question_type): - prompt = vsi_prompts.build_prompt(question_type, "q?") - assert prompt.startswith(vsi_prompts.PRE_PROMPT) - assert prompt.endswith(vsi_prompts.NA_POST_PROMPT) - - -@pytest.mark.parametrize("question_type", vsi_prompts.MCA_QUESTION_TYPES) -def test_every_mca_question_type_builds_with_options(question_type): - prompt = vsi_prompts.build_prompt(question_type, "q?", ["A. x", "B. y"]) - assert prompt.startswith(vsi_prompts.PRE_PROMPT) - assert prompt.endswith(vsi_prompts.MCA_POST_PROMPT) - - -def test_video_prompt_names_native_video(): - prompt = vsi_prompts.build_prompt("object_counting", "How many chairs?", video=True) - assert prompt.startswith("This is a video.\n") diff --git a/tests/test_A/test_run.py b/tests/test_A/test_run.py deleted file mode 100644 index cb45adbd3fc9d4f485851fdaed5f819396291312..0000000000000000000000000000000000000000 --- a/tests/test_A/test_run.py +++ /dev/null @@ -1,229 +0,0 @@ -"""Tests for harness/A/run.py -- question loading, scoring, and result-file writing.""" - -import json - -import pytest - -from harness import A -from harness.A import run as harness_run - -_FAKE_ANSWER = { - "prompt_text": "", - "answer_text": "4", - "answer_raw": "<|im_start|>assistant\n4<|im_end|>", - "input_token_count": 123, - "vision_input_shapes": {"pixel_values": [512, 1536]}, - "output_token_ids": [19, 151645], - "output_token_count": 2, - "hit_token_limit": False, - "eos_token_ids": [151645], - "generation_seconds": 1.234, - "device": "cuda", - "dtype": "bfloat16", - "library_versions": {"transformers": "5.14.1", "torch": "2.13.0+cu130"}, - "generation_config": { - "max_new_tokens": 16, - "do_sample": False, - "temperature": 0.0, - "top_p": None, - "top_k": None, - }, -} - -_FAKE_ROW = { - "id": 7, - "scene_name": "scene0001_00", - "dataset": "scannet", - "question_type": "object_counting", - "question": "How many chairs?", - "options": None, - "ground_truth": "4", -} - -_FAKE_FRAME_INFO = { - "protocol": "base", - "video_path": "/root/data/VSI-Bench/scannet/scene0001_00.mp4", - "frame_timestamps": [0.0, 1.0, 2.0], - "frame_indices": [0, 30, 60], - "frame_selection": "uniform", - "frame_count": 16, -} - - -def test_load_questions_reads_every_row(tmp_path): - jsonl = tmp_path / "test.jsonl" - jsonl.write_text( - "\n".join( - json.dumps({"id": i, "scene_name": f"scene{i}", "question": "q"}) - for i in range(3) - ) - ) - rows = harness_run.load_questions(jsonl) - assert [r["id"] for r in rows] == [0, 1, 2] - - -def test_load_questions_filters_by_scene(tmp_path): - jsonl = tmp_path / "test.jsonl" - jsonl.write_text( - "\n".join( - json.dumps({"id": i, "scene_name": "a" if i < 2 else "b", "question": "q"}) - for i in range(4) - ) - ) - rows = harness_run.load_questions(jsonl, scene="b") - assert [r["id"] for r in rows] == [2, 3] - - -def test_load_questions_respects_limit(tmp_path): - jsonl = tmp_path / "test.jsonl" - jsonl.write_text( - "\n".join( - json.dumps({"id": i, "scene_name": "a", "question": "q"}) for i in range(5) - ) - ) - rows = harness_run.load_questions(jsonl, limit=2) - assert [r["id"] for r in rows] == [0, 1] - - -def test_scalar_score_returns_metric_name_and_value(): - doc = {"question_type": "object_counting", "ground_truth": "4"} - score_doc = harness_run.vsi_official_eval.vsibench_process_results(doc, ["4"])[ - "vsibench_score" - ] - metric_name, value = harness_run._scalar_score("object_counting", score_doc) - assert metric_name == "MRA:.5:.95:.05" - assert value == 1.0 - - -def test_scalar_score_rejects_unknown_question_type(): - with pytest.raises(ValueError): - harness_run._scalar_score("not_a_real_type", {}) - - -def test_results_dir_for_matches_established_dimension_nesting(): - root = harness_run.results_dir_for("qwen3.5-4b", "base", "selective", 32) - assert root == A.RESULTS_DIR / "qwen3.5-4b" / "selective" / "32" - - -def test_results_dir_for_keeps_protocols_together(): - base = harness_run.results_dir_for("qwen3.5-4b", "base", "selective", 32) - extended = harness_run.results_dir_for("qwen3.5-4b", "thinking", "selective", 32) - assert base == extended - - -def test_results_dir_for_honors_explicit_override(tmp_path): - assert ( - harness_run.results_dir_for("qwen3.5-4b", "base", "uniform", 16, tmp_path) - == tmp_path - ) - - -def test_build_record_preserves_every_field_untruncated(): - record = harness_run._build_record( - _FAKE_ROW, - "full prompt text", - _FAKE_ANSWER, - "MRA:.5:.95:.05", - 1.0, - "qwen3.5-4b", - "/root/models/qwen3.5-4b", - _FAKE_FRAME_INFO, - ) - assert record["question"] == "How many chairs?" - assert record["full_prompt"] == "full prompt text" - assert record["rendered_prompt"] == _FAKE_ANSWER["prompt_text"] - assert record["answer_given"] == "4" - assert record["answer_raw"] == _FAKE_ANSWER["answer_raw"] - assert record["output_token_ids"] == [19, 151645] - assert record["output_token_count"] == 2 - assert record["hit_token_limit"] is False - assert record["generation_config"] == _FAKE_ANSWER["generation_config"] - assert record["frame_timestamps_seconds"] == [0.0, 1.0, 2.0] - assert record["frame_indices"] == [0, 30, 60] - assert record["video_path"] == _FAKE_FRAME_INFO["video_path"] - assert record["device"] == "cuda" - assert record["dtype"] == "bfloat16" - assert record["library_versions"] == _FAKE_ANSWER["library_versions"] - assert record["vision_input_shapes"] == {"pixel_values": [512, 1536]} - assert record["generation_seconds"] == 1.234 - assert record["metric"] == "MRA:.5:.95:.05" - assert record["score"] == 1.0 - assert record["scene"] == "scene0001_00" - assert record["question_id"] == 7 - - -def test_write_question_result_writes_one_json_file_per_question(tmp_path): - path, record = harness_run.write_question_result( - _FAKE_ROW, - "full prompt text", - _FAKE_ANSWER, - "MRA:.5:.95:.05", - 1.0, - "qwen3.5-4b", - "/root/models/qwen3.5-4b", - _FAKE_FRAME_INFO, - results_dir=tmp_path, - ) - assert path == tmp_path / "scene0001_00" / "7.json" - on_disk = json.loads(path.read_text()) - assert on_disk == record - - -def test_build_record_defaults_reasoning_fields_when_not_extended(): - record = harness_run._build_record( - _FAKE_ROW, - "full prompt text", - _FAKE_ANSWER, - "MRA:.5:.95:.05", - 1.0, - "qwen3.5-4b", - "/root/models/qwen3.5-4b", - _FAKE_FRAME_INFO, - ) - assert record["reasoning_text"] is None - assert record["forced"] is False - assert record["forced_input_token_count"] is None - - -def test_build_record_carries_reasoning_fields_when_extended(): - extended_answer = { - **_FAKE_ANSWER, - "reasoning_text": "long reasoning about the scene", - "reasoning_raw": "long reasoning about the scene<|im_end|>", - "reasoning_token_ids": list(range(50)), - "reasoning_token_count": 50, - "reasoning_hit_limit": True, - "forced": True, - "forced_input_token_count": 2510, - } - record = harness_run._build_record( - _FAKE_ROW, - "full prompt text", - extended_answer, - "MRA:.5:.95:.05", - 1.0, - "qwen3.5-4b", - "/root/models/qwen3.5-4b", - _FAKE_FRAME_INFO, - ) - assert record["reasoning_text"] == "long reasoning about the scene" - assert record["reasoning_token_count"] == 50 - assert record["reasoning_hit_limit"] is True - assert record["forced"] is True - assert record["forced_input_token_count"] == 2510 - - -def test_video_results_use_video_branch(): - assert ( - harness_run.results_dir_for("qwen3.5-4b", "thinking", "video", None) - == A.RESULTS_DIR / "qwen3.5-4b" / "video" - ) - - -def test_video_record_has_no_frame_count_in_condition(): - info = dict(_FAKE_FRAME_INFO, frame_selection="video", frame_count=None) - record = harness_run._build_record( - _FAKE_ROW, "prompt", _FAKE_ANSWER, "metric", 1.0, "qwen3.5-4b", "/model", info - ) - assert record["condition"] == "base:video" - assert record["frame_count"] is None diff --git a/tests/test_A/test_sweep.py b/tests/test_A/test_sweep.py deleted file mode 100644 index ad3c0b8308854149f8478ab92ef6bae28b2b092d..0000000000000000000000000000000000000000 --- a/tests/test_A/test_sweep.py +++ /dev/null @@ -1,69 +0,0 @@ -"""Tests for harness/A/sweep.py -- multi-config sweep planning.""" - -import pytest - -from harness.A import models as vlm_models -from harness.A import sweep - - -def test_parse_csv_choice_splits_and_dedups(): - result = sweep._parse_csv_choice( - "uniform,selective,uniform", ("uniform", "selective"), "--x" - ) - assert result == ["uniform", "selective"] - - -def test_parse_csv_choice_expands_all(): - result = sweep._parse_csv_choice("all", ("uniform", "selective"), "--x") - assert result == ["uniform", "selective"] - - -def test_parse_csv_choice_rejects_unknown_value(): - with pytest.raises(ValueError): - sweep._parse_csv_choice("uniform,bogus", ("uniform", "selective"), "--x") - - -def test_parse_csv_choice_rejects_empty(): - with pytest.raises(ValueError): - sweep._parse_csv_choice("", ("uniform", "selective"), "--x") - - -def test_parse_frame_counts_splits_and_dedups(): - assert sweep._parse_frame_counts("16,32,64,32") == [16, 32, 64] - - -def test_parse_frame_counts_rejects_nonpositive(): - with pytest.raises(ValueError): - sweep._parse_frame_counts("16,0,64") - - -def test_parse_frame_counts_rejects_non_integer(): - with pytest.raises(ValueError): - sweep._parse_frame_counts("16,abc") - - -def test_build_plan_covers_every_combination(): - plan = sweep.build_plan( - ["qwen3.5-2b", "qwen3.5-4b"], ["uniform", "selective"], [16, 32] - ) - assert len(plan) == 2 * 2 * 2 - assert set(plan) == { - ("qwen3.5-2b", "uniform", 16), - ("qwen3.5-2b", "uniform", 32), - ("qwen3.5-2b", "selective", 16), - ("qwen3.5-2b", "selective", 32), - ("qwen3.5-4b", "uniform", 16), - ("qwen3.5-4b", "uniform", 32), - ("qwen3.5-4b", "selective", 16), - ("qwen3.5-4b", "selective", 32), - } - - -def test_build_plan_orders_by_frame_count_first(): - plan = sweep.build_plan(["qwen3.5-2b"], ["uniform"], [64, 16, 32]) - assert [frame_count for _model, _selection, frame_count in plan] == [16, 32, 64] - - -def test_build_plan_with_all_registered_models(): - plan = sweep.build_plan(list(vlm_models.available_models()), ["uniform"], [16]) - assert len(plan) == len(vlm_models.available_models()) diff --git a/tests/test_B/__init__.py b/tests/test_B/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/tests/test_B/conftest.py b/tests/test_B/conftest.py deleted file mode 100644 index cff300cdd89d64dac0aa52d10f2982c6fcbbe74d..0000000000000000000000000000000000000000 --- a/tests/test_B/conftest.py +++ /dev/null @@ -1,12 +0,0 @@ -"""Shared import setup for harness.B tests.""" - -from pathlib import Path -import sys - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - - -def pytest_configure(config): - config.option.importmode = "importlib" diff --git a/tests/test_B/test_B.py b/tests/test_B/test_B.py deleted file mode 100644 index ad4bc9206f95e5af7a9f103c1e4cdb2763864b28..0000000000000000000000000000000000000000 --- a/tests/test_B/test_B.py +++ /dev/null @@ -1,35 +0,0 @@ -"""Tests for harness/B/__init__.py -- shared config constants.""" - -from pathlib import Path - -from harness import A, B - - -def test_spatial_code_formats_is_explicit_only(): - assert B.SPATIAL_CODE_FORMATS == ("explicit",) - assert B.DEFAULT_SPATIAL_CODE_FORMAT in B.SPATIAL_CODE_FORMATS - - -def test_input_selections_match_harness_a_vocabulary(): - assert B.INPUT_SELECTIONS == A.FRAME_SELECTIONS - assert B.DEFAULT_INPUT_SELECTION in B.INPUT_SELECTIONS - - -def test_reuses_harness_a_model_paths_and_generation_protocol(): - assert B.MODEL_PATHS is A.MODEL_PATHS - assert B.MAX_NEW_TOKENS == A.MAX_NEW_TOKENS - assert B.DO_SAMPLE == A.DO_SAMPLE - assert B.TEMPERATURE == A.TEMPERATURE - - -def test_results_dir_defaults_under_root_results(): - assert B.RESULTS_DIR == Path("/root/results/B") - - -def test_depth_and_tracking_reuse_encoder_config_vocabulary(): - from encoder.config import DEPTH_VARIANTS, TRACKING_MODES - - assert B.DEPTH_VARIANTS == DEPTH_VARIANTS - assert B.TRACKING_MODES == TRACKING_MODES - assert B.DEFAULT_DEPTH in B.DEPTH_VARIANTS - assert B.DEFAULT_TRACKING in B.TRACKING_MODES diff --git a/tests/test_B/test_init.py b/tests/test_B/test_init.py deleted file mode 100644 index 2f860021759bd0c9b136c19b188a5c0f4dbddee6..0000000000000000000000000000000000000000 --- a/tests/test_B/test_init.py +++ /dev/null @@ -1,33 +0,0 @@ -"""Tests for harness/B/__init__.py -- shared config constants.""" - -from harness import A, B - - -def test_spatial_code_formats_is_explicit_only(): - assert B.SPATIAL_CODE_FORMATS == ("explicit",) - assert B.DEFAULT_SPATIAL_CODE_FORMAT in B.SPATIAL_CODE_FORMATS - - -def test_input_selections_match_harness_a_vocabulary(): - assert B.INPUT_SELECTIONS == A.FRAME_SELECTIONS - assert B.DEFAULT_INPUT_SELECTION in B.INPUT_SELECTIONS - - -def test_reuses_harness_a_model_paths_and_generation_protocol(): - assert B.MODEL_PATHS is A.MODEL_PATHS - assert B.MAX_NEW_TOKENS == A.MAX_NEW_TOKENS - assert B.DO_SAMPLE == A.DO_SAMPLE - assert B.TEMPERATURE == A.TEMPERATURE - - -def test_results_dir_defaults_under_workspace_results(): - assert B.RESULTS_DIR == B.WORKSPACE_ROOT / "results" / "B" - - -def test_depth_and_tracking_reuse_encoder_config_vocabulary(): - from encoder.config import DEPTH_VARIANTS, TRACKING_MODES - - assert B.DEPTH_VARIANTS == DEPTH_VARIANTS - assert B.TRACKING_MODES == TRACKING_MODES - assert B.DEFAULT_DEPTH in B.DEPTH_VARIANTS - assert B.DEFAULT_TRACKING in B.TRACKING_MODES diff --git a/tests/test_B/test_launch.py b/tests/test_B/test_launch.py deleted file mode 100644 index 598fa4e72abf4cc301473153f1c818df3d694b2f..0000000000000000000000000000000000000000 --- a/tests/test_B/test_launch.py +++ /dev/null @@ -1,85 +0,0 @@ -"""Tests for harness/B/launch.py -- multi-GPU scene sharding across workers.""" - -import pytest - -from harness.B import launch - - -def test_launcher_imports(): - assert callable(launch.main) - - -class _FakeRun: - rows = [{"id": 1}, {"id": 3}] - - @staticmethod - def results_dir_for(*args, **kwargs): - return args[-1] - - @classmethod - def load_questions(cls, scene=None): - return list(cls.rows) - - -def test_launch_skips_scene_already_fully_answered(tmp_path, capsys, monkeypatch): - scene = "scene-b" - monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) - - scene_dir = tmp_path / scene - scene_dir.mkdir() - for row in _FakeRun.rows: - (scene_dir / f"{row['id']}.json").write_text("{}") - - launch.launch( - "qwen3.5-2b", "explicit", "selective", 64, [scene], results_dir=tmp_path - ) - - output = capsys.readouterr().out - assert "skipped" in output - assert "DONE: 1 ok, 0 failed" in output - - -def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch): - scene = "scene-b" - monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) - scene_dir = tmp_path / scene - scene_dir.mkdir() - for row in _FakeRun.rows: - (scene_dir / f"{row['id']}.json").write_text("{}") - - monkeypatch.setattr(launch, "visible_gpus", lambda: []) - monkeypatch.setattr( - launch.mp, - "get_context", - lambda *_: (_ for _ in ()).throw( - RuntimeError("rebuild correctly reached worker dispatch") - ), - ) - try: - launch.launch( - "qwen3.5-2b", - "explicit", - "selective", - 64, - [scene], - results_dir=tmp_path, - rebuild=True, - ) - except RuntimeError as exc: - assert "rebuild correctly reached worker dispatch" in str(exc) - else: - raise AssertionError("expected rebuild to force scene into the pending path") - - -def test_launch_rejects_question_id_filter_that_matches_nothing(monkeypatch, tmp_path): - monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) - with pytest.raises(ValueError, match="no questions found"): - launch.launch( - "qwen3.5-2b", - "explicit", - "selective", - 64, - ["scene-b"], - results_dir=tmp_path, - question_ids={999}, - ) diff --git a/tests/test_B/test_prompts.py b/tests/test_B/test_prompts.py deleted file mode 100644 index ad7945c4d970f71f92ae5db81907af6effecbc75..0000000000000000000000000000000000000000 --- a/tests/test_B/test_prompts.py +++ /dev/null @@ -1,103 +0,0 @@ -"""Tests for harness/B/prompts.py -- spatial-code-as-text prompt construction.""" - -import json - -import pytest - -from harness.A.prompts import MCA_QUESTION_TYPES, NA_QUESTION_TYPES -from harness.B import prompts as code_prompts - -_CODE = { - "objects": {"chair": {"count": 1}}, - "room": {"floor area": "10.0 square meters"}, -} - - -def test_na_question_prompt_embeds_the_spatial_code_as_text_and_a_post_prompt(): - prompt = code_prompts.build_prompt(_CODE, "object_counting", "How many chairs?") - assert prompt.startswith(code_prompts.PRE_PROMPT) - assert json.dumps(_CODE, indent=1) in prompt - assert prompt.endswith(code_prompts.NA_POST_PROMPT) - - -def test_mca_question_prompt_includes_options_and_matches_harness_a_post_prompt(): - prompt = code_prompts.build_prompt( - _CODE, "object_rel_distance", "Which is closest?", ["A. sofa", "B. table"] - ) - assert "Options:\nA. sofa\nB. table" in prompt - assert prompt.endswith(code_prompts.MCA_POST_PROMPT) - - -def test_mca_question_requires_options(): - with pytest.raises(ValueError): - code_prompts.build_prompt(_CODE, "route_planning", "Which way?", None) - - -def test_unknown_question_type_rejected(): - with pytest.raises(ValueError): - code_prompts.build_prompt(_CODE, "not_a_real_type", "?", None) - - -def test_no_frames_language_in_pre_prompt(): - # B has no video frames -- the context line must not claim otherwise. - assert "frame" not in code_prompts.PRE_PROMPT.lower() - - -@pytest.mark.parametrize("question_type", NA_QUESTION_TYPES) -def test_every_na_question_type_builds(question_type): - prompt = code_prompts.build_prompt(_CODE, question_type, "q?") - assert prompt.startswith(code_prompts.PRE_PROMPT) - - -@pytest.mark.parametrize("question_type", MCA_QUESTION_TYPES) -def test_every_mca_question_type_builds(question_type): - prompt = code_prompts.build_prompt(_CODE, question_type, "q?", ["A. x", "B. y"]) - assert prompt.startswith(code_prompts.PRE_PROMPT) - - -def test_default_arguments_reproduce_the_standard_prompt_byte_for_byte(): - standard = code_prompts.build_prompt(_CODE, "object_counting", "How many chairs?") - explicit_defaults = code_prompts.build_prompt( - _CODE, - "object_counting", - "How many chairs?", - serialization="json", - context_line=None, - ) - assert standard == explicit_defaults - - -def test_yaml_serialization_renders_the_identical_dict(): - import yaml - - prompt = code_prompts.build_prompt( - _CODE, "object_counting", "How many chairs?", serialization="yaml" - ) - rendered = prompt.split("\n", 1)[1].rsplit("How many chairs?", 1)[0] - assert yaml.safe_load(rendered) == _CODE - - -def test_yaml_arm_context_line_does_not_claim_json(): - prompt = code_prompts.build_prompt( - _CODE, "object_counting", "How many chairs?", serialization="yaml" - ) - context = prompt.split("\n", 1)[0] - assert "JSON" not in context - assert "YAML" in context - - -def test_paraphrase_context_line_swaps_only_the_first_line(): - standard = code_prompts.build_prompt(_CODE, "object_counting", "How many chairs?") - paraphrased = code_prompts.build_prompt( - _CODE, - "object_counting", - "How many chairs?", - context_line=code_prompts.PARAPHRASE_PRE_PROMPT, - ) - assert standard.split("\n", 1)[1] == paraphrased.split("\n", 1)[1] - assert standard.split("\n", 1)[0] != paraphrased.split("\n", 1)[0] - - -def test_unknown_serialization_rejected(): - with pytest.raises(ValueError): - code_prompts.render_code(_CODE, "xml") diff --git a/tests/test_B/test_run.py b/tests/test_B/test_run.py deleted file mode 100644 index 5f1fb73addd01ef139bc59fae05fc421836357a7..0000000000000000000000000000000000000000 --- a/tests/test_B/test_run.py +++ /dev/null @@ -1,231 +0,0 @@ -"""Tests for harness/B/run.py -- result-record shape and result-file writing.""" - -import json - -from harness import B -from harness.B import run as harness_run - -_FAKE_ANSWER = { - "prompt_text": "", - "answer_text": "4", - "answer_raw": "<|im_start|>assistant\n4<|im_end|>", - "input_token_count": 2558, - "vision_input_shapes": {"mm_token_type_ids": [1, 2558]}, - "output_token_ids": [19, 151645], - "output_token_count": 2, - "hit_token_limit": False, - "eos_token_ids": [151645], - "generation_seconds": 0.65, - "device": "cuda", - "dtype": "bfloat16", - "library_versions": {"transformers": "5.14.1", "torch": "2.13.0+cu130"}, - "generation_config": { - "max_new_tokens": 16, - "do_sample": False, - "temperature": 0.0, - "top_p": None, - "top_k": None, - "enable_thinking": False, - }, -} - -_FAKE_ROW = { - "id": 7, - "scene_name": "scene0001_00", - "dataset": "scannet", - "question_type": "object_counting", - "question": "How many chairs?", - "options": None, - "ground_truth": "4", -} - -_FAKE_CODE_INFO = { - "protocol": "thinking", - "spatial_code_format": "explicit", - "input_selection": "selective", - "frame_count": 64, - "depth": "metric", - "tracking": "tracking", - "spatial_code_path": "/workspace/data/spatial codes/.../scene0001_00.json", -} - - -def test_results_dir_for_matches_established_dimension_nesting(): - root = harness_run.results_dir_for( - "qwen3.5-4b", "thinking", "explicit", "metric", "tracking", "uniform", 32 - ) - assert root == ( - B.RESULTS_DIR - / "qwen3.5-4b" - / "explicit" - / "metric" - / "tracking" - / "uniform" - / "32" - ) - - -def test_results_dir_for_keeps_protocols_together(): - base = harness_run.results_dir_for( - "qwen3.5-4b", "base", "explicit", "metric", "tracking", "uniform", 32 - ) - extended = harness_run.results_dir_for( - "qwen3.5-4b", "thinking", "explicit", "metric", "tracking", "uniform", 32 - ) - assert base == extended - - -def test_results_dir_for_honors_explicit_override(tmp_path): - root = harness_run.results_dir_for( - "qwen3.5-4b", - "base", - "explicit", - "relative", - "no tracking", - "selective", - 16, - tmp_path, - ) - assert root == tmp_path - - -def test_build_record_preserves_every_field_untruncated(): - record = harness_run._build_record( - _FAKE_ROW, - "full prompt text", - _FAKE_ANSWER, - "MRA:.5:.95:.05", - 1.0, - "qwen3.5-4b", - "/root/models/qwen3.5-4b", - _FAKE_CODE_INFO, - ) - assert record["question"] == "How many chairs?" - assert record["full_prompt"] == "full prompt text" - assert record["rendered_prompt"] == _FAKE_ANSWER["prompt_text"] - assert record["answer_given"] == "4" - assert record["answer_raw"] == _FAKE_ANSWER["answer_raw"] - assert record["spatial_code_format"] == "explicit" - assert record["input_selection"] == "selective" - assert record["frame_count"] == 64 - assert record["depth"] == "metric" - assert record["tracking"] == "tracking" - assert record["spatial_code_path"] == _FAKE_CODE_INFO["spatial_code_path"] - assert record["condition"] == "extended:explicit:metric:tracking:selective:64" - assert record["protocol"] == "thinking" - assert record["vision_input_shapes"] == {"mm_token_type_ids": [1, 2558]} - assert record["generation_config"] == _FAKE_ANSWER["generation_config"] - assert record["metric"] == "MRA:.5:.95:.05" - assert record["score"] == 1.0 - assert record["scene"] == "scene0001_00" - assert record["question_id"] == 7 - # No frame-provenance fields -- B has no video frames. - assert "frame_selection" not in record - assert "video_path" not in record - assert "frame_indices" not in record - - -def test_write_question_result_writes_one_json_file_per_question(tmp_path): - path, record = harness_run.write_question_result( - _FAKE_ROW, - "full prompt text", - _FAKE_ANSWER, - "MRA:.5:.95:.05", - 1.0, - "qwen3.5-4b", - "/root/models/qwen3.5-4b", - _FAKE_CODE_INFO, - results_dir=tmp_path, - ) - assert path == tmp_path / "scene0001_00" / "7.json" - on_disk = json.loads(path.read_text()) - assert on_disk == record - - -def test_build_record_carries_reasoning_fields_when_forced(): - extended_answer = { - **_FAKE_ANSWER, - "reasoning_text": "long reasoning about the spatial code", - "reasoning_raw": "long reasoning about the spatial code<|im_end|>", - "reasoning_token_ids": list(range(50)), - "reasoning_token_count": 50, - "reasoning_hit_limit": True, - "forced": True, - "forced_input_token_count": 2510, - } - record = harness_run._build_record( - _FAKE_ROW, - "full prompt text", - extended_answer, - "MRA:.5:.95:.05", - 1.0, - "qwen3.5-4b", - "/root/models/qwen3.5-4b", - _FAKE_CODE_INFO, - ) - assert record["reasoning_text"] == "long reasoning about the spatial code" - assert record["forced"] is True - assert record["forced_input_token_count"] == 2510 - - -def test_run_strip_schema_legend_removes_only_the_legend(monkeypatch): - seen = {} - - def fake_load(scene_id, depth, input_selection, tracking, frame_count, fmt): - return { - "spatial code schema": {"doc": 1}, - "objects": {"chair": {"count": 1}}, - }, "/fake.json" - - class FakeAdapter: - model_path = "/fake/model" - - def answer_extended(self, frames, prompt, **kwargs): - seen["prompt"] = prompt - return { - "prompt_text": prompt, - "answer_text": "1", - "answer_raw": "1", - "input_token_count": 1, - "vision_input_shapes": {}, - "output_token_ids": [1], - "output_token_count": 1, - "hit_token_limit": False, - "eos_token_ids": [1], - "generation_seconds": 0.0, - "device": "cpu", - "dtype": "float32", - "library_versions": {}, - "generation_config": {}, - } - - monkeypatch.setattr(harness_run.spatial_codes, "load_spatial_code", fake_load) - results = harness_run.run( - "qwen3.5-2b", - scene="13c3e046d7", - adapter=FakeAdapter(), - write_results=False, - limit=1, - strip_schema_legend=True, - ) - assert results - assert "spatial code schema" not in seen["prompt"] - assert '"chair"' in seen["prompt"] - - -def test_video_results_use_video_branch(): - assert ( - harness_run.results_dir_for( - "qwen3.5-4b", "thinking", "explicit", "metric", "tracking", "video", None - ) - == B.RESULTS_DIR / "qwen3.5-4b" / "explicit" / "metric" / "tracking" / "video" - ) - - -def test_video_record_has_no_frame_count_in_condition(): - info = dict(_FAKE_CODE_INFO, input_selection="video", frame_count=None) - record = harness_run._build_record( - _FAKE_ROW, "prompt", _FAKE_ANSWER, "metric", 1.0, "qwen3.5-4b", "/model", info - ) - assert record["condition"] == "thinking:explicit:metric:tracking:video" - assert record["frame_count"] is None diff --git a/tests/test_B/test_spatial_codes.py b/tests/test_B/test_spatial_codes.py deleted file mode 100644 index ae26c07a952b13eb2c61f9efe7623b0a226a9223..0000000000000000000000000000000000000000 --- a/tests/test_B/test_spatial_codes.py +++ /dev/null @@ -1,48 +0,0 @@ -"""Tests for harness/B/spatial_codes.py -- loading on-disk spatial codes as plain JSON.""" - -import json - -import pytest - -from harness.B import spatial_codes - - -def test_load_spatial_code_rejects_unknown_format(): - with pytest.raises(ValueError): - spatial_codes.load_spatial_code( - "scene", "metric", "selective", "tracking", 64, "bogus" - ) - - -def test_load_spatial_code_raises_clearly_when_missing(tmp_path, monkeypatch): - monkeypatch.setattr( - spatial_codes, - "spatial_code_path", - lambda *a, **k: str(tmp_path / "missing.json"), - ) - with pytest.raises(FileNotFoundError): - spatial_codes.load_spatial_code( - "scene", "metric", "selective", "tracking", 64, "explicit" - ) - - -def test_load_spatial_code_returns_dict_and_path(tmp_path, monkeypatch): - fixture = tmp_path / "13c3e046d7.json" - fixture.write_text(json.dumps({"objects": {}, "room": {}})) - monkeypatch.setattr( - spatial_codes, "spatial_code_path", lambda *a, **k: str(fixture) - ) - code, path = spatial_codes.load_spatial_code( - "13c3e046d7", "metric", "selective", "tracking", 64, "explicit" - ) - assert code == {"objects": {}, "room": {}} - assert path == str(fixture) - - -def test_spatial_code_path_uses_tracking_frames_hierarchy(): - path = spatial_codes.spatial_code_path( - "scene-a", "metric", "selective", "tracking", 64, "explicit" - ) - assert path.endswith( - "data/spatial codes/sam3+depth-anything-3/tracking/frames/selective/64/explicit/scene-a.json" - ) diff --git a/tests/test_B/test_sweep.py b/tests/test_B/test_sweep.py deleted file mode 100644 index bcafb68aa6df20989f7667a32859e439bd017aa0..0000000000000000000000000000000000000000 --- a/tests/test_B/test_sweep.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Tests for harness/B/sweep.py -- multi-config sweep planning.""" - -import pytest - -from harness.A import models as vlm_models -from harness.B import sweep - - -def test_build_plan_covers_every_combination(): - plan = sweep.build_plan( - ["qwen3.5-2b", "qwen3.5-4b"], - ["explicit"], - ["uniform", "selective"], - [16, 32], - ["metric"], - ["tracking"], - ) - assert len(plan) == 2 * 1 * 2 * 2 - assert ("qwen3.5-2b", "explicit", "metric", "tracking", "uniform", 16) in plan - assert ("qwen3.5-4b", "explicit", "metric", "tracking", "selective", 32) in plan - - -def test_build_plan_sweeps_depth_and_tracking_too(): - plan = sweep.build_plan( - ["qwen3.5-2b"], - ["explicit"], - ["uniform"], - [16], - ["metric", "relative"], - ["tracking", "no tracking"], - ) - assert len(plan) == 4 - assert ("qwen3.5-2b", "explicit", "relative", "no tracking", "uniform", 16) in plan - - -def test_build_plan_orders_by_frame_count_first(): - plan = sweep.build_plan( - ["qwen3.5-2b"], - ["explicit"], - ["uniform"], - [64, 16, 32], - ["metric"], - ["tracking"], - ) - assert [frame_count for *_rest, frame_count in plan] == [16, 32, 64] - - -def test_build_plan_with_all_registered_models(): - plan = sweep.build_plan( - list(vlm_models.available_models()), - ["explicit"], - ["uniform"], - [16], - ["metric"], - ["tracking"], - ) - assert len(plan) == len(vlm_models.available_models()) - - -def test_sweep_parser_rejects_unknown_depth(): - with pytest.raises(ValueError): - sweep._parse_csv_choice("bogus", sweep.DEPTH_VARIANTS, "--depths") - - -def test_sweep_parser_rejects_unknown_tracking(): - with pytest.raises(ValueError): - sweep._parse_csv_choice("bogus", sweep.TRACKING_MODES, "--trackings") diff --git a/tests/test_C/__init__.py b/tests/test_C/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/tests/test_C/conftest.py b/tests/test_C/conftest.py deleted file mode 100644 index 3abc76e01c01cd0bfbddf3345cf7422f6c71fe53..0000000000000000000000000000000000000000 --- a/tests/test_C/conftest.py +++ /dev/null @@ -1,12 +0,0 @@ -"""Shared import setup for harness.C tests.""" - -from pathlib import Path -import sys - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - - -def pytest_configure(config): - config.option.importmode = "importlib" diff --git a/tests/test_C/test_C.py b/tests/test_C/test_C.py deleted file mode 100644 index 14f3b72ba8d26def86d9b63337d7e4d3e544689a..0000000000000000000000000000000000000000 --- a/tests/test_C/test_C.py +++ /dev/null @@ -1,27 +0,0 @@ -"""Tests for harness/C/__init__.py -- shared config constants.""" - -from pathlib import Path - -from harness import A, B, C - - -def test_input_selections_are_one_shared_vocabulary_with_a_and_b(): - assert B.INPUT_SELECTIONS == A.FRAME_SELECTIONS - - -def test_reuses_harness_a_model_paths_and_generation_protocol(): - assert C.MODEL_PATHS is A.MODEL_PATHS - assert C.MAX_NEW_TOKENS == A.MAX_NEW_TOKENS - assert C.DO_SAMPLE == A.DO_SAMPLE - assert C.TEMPERATURE == A.TEMPERATURE - - -def test_results_dir_defaults_under_root_results(): - assert C.RESULTS_DIR == Path("/root/results/C") - - -def test_depth_and_tracking_reuse_encoder_config_vocabulary(): - from encoder.config import DEPTH_VARIANTS, TRACKING_MODES - - assert C.DEPTH_VARIANTS == DEPTH_VARIANTS - assert C.TRACKING_MODES == TRACKING_MODES diff --git a/tests/test_C/test_init.py b/tests/test_C/test_init.py deleted file mode 100644 index 62629afcda57cbea7408725d50f1f536ffe7bae7..0000000000000000000000000000000000000000 --- a/tests/test_C/test_init.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Tests for harness/C/__init__.py -- shared config constants.""" - -from harness import A, B, C - - -def test_input_selections_are_one_shared_vocabulary_with_a_and_b(): - assert B.INPUT_SELECTIONS == A.FRAME_SELECTIONS - - -def test_reuses_harness_a_model_paths_and_generation_protocol(): - assert C.MODEL_PATHS is A.MODEL_PATHS - assert C.MAX_NEW_TOKENS == A.MAX_NEW_TOKENS - assert C.DO_SAMPLE == A.DO_SAMPLE - assert C.TEMPERATURE == A.TEMPERATURE - - -def test_results_dir_defaults_under_workspace_results(): - assert C.RESULTS_DIR == C.WORKSPACE_ROOT / "results" / "C" - - -def test_depth_and_tracking_reuse_encoder_config_vocabulary(): - from encoder.config import DEPTH_VARIANTS, TRACKING_MODES - - assert C.DEPTH_VARIANTS == DEPTH_VARIANTS - assert C.TRACKING_MODES == TRACKING_MODES diff --git a/tests/test_C/test_launch.py b/tests/test_C/test_launch.py deleted file mode 100644 index 8ef65e3d7664c5e316651f42a09bde2d9f18c5ac..0000000000000000000000000000000000000000 --- a/tests/test_C/test_launch.py +++ /dev/null @@ -1,69 +0,0 @@ -"""Tests for harness/C/launch.py -- multi-GPU scene sharding across workers.""" - -from harness.C import launch - - -def test_launcher_imports(): - assert callable(launch.main) - - -class _FakeRun: - rows = [{"id": 1}, {"id": 2}] - - @staticmethod - def results_dir_for(*args, **kwargs): - return args[-1] - - @classmethod - def load_questions(cls, scene=None): - return list(cls.rows) - - -def test_launch_skips_scene_already_fully_answered(tmp_path, capsys, monkeypatch): - scene = "scene-c" - monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) - - scene_dir = tmp_path / scene - scene_dir.mkdir() - for row in _FakeRun.rows: - (scene_dir / f"{row['id']}.json").write_text("{}") - - launch.launch( - "qwen3.5-2b", "explicit", "selective", 64, [scene], results_dir=tmp_path - ) - - output = capsys.readouterr().out - assert "skipped" in output - assert "DONE: 1 ok, 0 failed" in output - - -def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch): - scene = "scene-c" - monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) - scene_dir = tmp_path / scene - scene_dir.mkdir() - for row in _FakeRun.rows: - (scene_dir / f"{row['id']}.json").write_text("{}") - - monkeypatch.setattr(launch, "visible_gpus", lambda: []) - monkeypatch.setattr( - launch.mp, - "get_context", - lambda *_: (_ for _ in ()).throw( - RuntimeError("rebuild correctly reached worker dispatch") - ), - ) - try: - launch.launch( - "qwen3.5-2b", - "explicit", - "selective", - 64, - [scene], - results_dir=tmp_path, - rebuild=True, - ) - except RuntimeError as exc: - assert "rebuild correctly reached worker dispatch" in str(exc) - else: - raise AssertionError("expected rebuild to force scene into the pending path") diff --git a/tests/test_C/test_overlay.py b/tests/test_C/test_overlay.py deleted file mode 100644 index f087058a643d116cd69ea1b72d2cc6cfb457af28..0000000000000000000000000000000000000000 --- a/tests/test_C/test_overlay.py +++ /dev/null @@ -1,209 +0,0 @@ -"""Tests for harness/C/overlay.py -- overlay labels, cache, and stamping.""" - -import json -from pathlib import Path - -import pytest -from PIL import Image - -from harness.C import overlay - -_EXPLICIT_CODE = { - "objects": { - "chair": { - "instances": [ - { - "position": { - "x coordinate": "1.5 m", - "y coordinate": "-2 m", - "height above floor": "0.25 m", - }, - "longest dimension": "0.80 m", - } - ] - }, - "table": { - "instances": [ - { - "position": { - "x coordinate": "3 m", - "y coordinate": "4 m", - "height above floor": "0 m", - }, - "longest dimension": "1.20 m", - } - ] - }, - } -} - - -def test_instance_ids_adds_stable_one_based_labels_without_mutating_input(): - original = {"objects": {"chair": {"instances": [{"position": {}}]}}} - - labeled = overlay.instance_ids(original) - - assert labeled["objects"]["chair"]["instances"][0]["instance id"] == "chair 1" - assert "instance id" not in original["objects"]["chair"]["instances"][0] - - -def test_overlay_spatial_code_path_lives_under_overlay_root(monkeypatch, tmp_path): - monkeypatch.setattr( - overlay.encoder_config, "CODES_ROOT", tmp_path / "data" / "spatial codes" - ) - monkeypatch.setattr(overlay.encoder_config, "MODEL", "sam3+depth-anything-3") - - path = overlay.overlay_spatial_code_path( - "scene", "metric", "uniform", "tracking", 32 - ) - - assert path == ( - tmp_path - / "data" - / "spatial codes" - / "overlay" - / "sam3+depth-anything-3" - / "metric" - / "tracking" - / "uniform" - / "32" - / "explicit" - / "scene.json" - ) - - -def test_load_or_create_overlay_code_saves_missing_file(monkeypatch, tmp_path): - monkeypatch.setattr(overlay.encoder_config, "CODES_ROOT", tmp_path / "codes") - monkeypatch.setattr(overlay.encoder_config, "MODEL", "model") - - code, path = overlay.load_or_create_overlay_code( - _EXPLICIT_CODE, "scene", "metric", "uniform", "tracking", 32 - ) - - path = Path(path) - assert path.is_file() - assert json.loads(path.read_text()) == code - assert code["objects"]["chair"]["instances"][0]["instance id"] == "chair 1" - - -def test_load_or_create_overlay_code_reuses_existing_file(monkeypatch, tmp_path): - monkeypatch.setattr(overlay.encoder_config, "CODES_ROOT", tmp_path / "codes") - monkeypatch.setattr(overlay.encoder_config, "MODEL", "model") - path = overlay.overlay_spatial_code_path( - "scene", "metric", "uniform", "tracking", 32 - ) - path.parent.mkdir(parents=True) - existing = {"objects": {"saved": {"instances": []}}, "sentinel": True} - path.write_text(json.dumps(existing)) - - code, returned = overlay.load_or_create_overlay_code( - _EXPLICIT_CODE, "scene", "metric", "uniform", "tracking", 32 - ) - - assert returned == str(path) - assert code == existing - assert json.loads(path.read_text()) == existing - - -def test_label_positions_parse_meter_strings_in_code_order(): - assert overlay.label_positions(_EXPLICIT_CODE) == [ - ("chair 1", 1.5, -2.0, 0.25, 0.8), - ("table 1", 3.0, 4.0, 0.0, 1.2), - ] - - -def test_load_cached_frames_requires_complete_png_set_and_labels(tmp_path): - assert overlay._load_cached_frames(tmp_path, 2) is None - (tmp_path / "labels.json").write_text(json.dumps([["chair 1"], []])) - Image.new("RGB", (4, 4), "white").save(tmp_path / "0.png") - assert overlay._load_cached_frames(tmp_path, 2) is None - - Image.new("RGB", (4, 4), "black").save(tmp_path / "1.png") - images, visible = overlay._load_cached_frames(tmp_path, 2) - - assert [image.mode for image in images] == ["RGB", "RGB"] - assert visible == [["chair 1"], []] - - -def test_save_cached_frames_writes_pngs_and_labels(tmp_path): - frames = [Image.new("RGB", (2, 2), color) for color in ("white", "black")] - - overlay._save_cached_frames(tmp_path, frames, [["a"], ["b"]]) - - assert (tmp_path / "0.png").is_file() - assert (tmp_path / "1.png").is_file() - assert json.loads((tmp_path / "labels.json").read_text()) == [["a"], ["b"]] - - -def test_stamp_frames_uses_raw_sam3_boxes_and_does_not_mutate_inputs( - monkeypatch, tmp_path -): - monkeypatch.setattr( - overlay, "overlay_frame_cache_dir", lambda *args: tmp_path / "cache" - ) - monkeypatch.setattr( - overlay.perceive, - "cache_or_load", - lambda *args: ({"geometry": "fake"}, "cache"), - ) - monkeypatch.setattr( - overlay.gm, - "instance_source_track_ids", - lambda geometry: {"chair": [[10]], "table": [[20]]}, - ) - monkeypatch.setattr( - overlay, - "_load_raw_sam3_boxes", - lambda *args: { - "chair": {0: {10: (0.10, 0.10, 0.30, 0.30)}}, - "table": {1: {20: (0.50, 0.50, 0.25, 0.25)}}, - }, - ) - frames = [Image.new("RGB", (40, 40), "white"), Image.new("RGB", (40, 40), "white")] - before = frames[0].copy() - - stamped, visible = overlay.stamp_frames( - frames, - _EXPLICIT_CODE, - "scene", - "metric", - "uniform", - "tracking", - 2, - use_cache=True, - ) - - assert visible == [["chair 1"], ["table 1"]] - assert stamped[0].getpixel((8, 8)) != before.getpixel((8, 8)) - assert frames[0].tobytes() == before.tobytes() - cached = overlay._load_cached_frames(tmp_path / "cache", 2) - assert cached is not None - assert cached[1] == visible - - -def test_stamp_frames_serves_complete_cache_without_loading_dependencies( - monkeypatch, tmp_path -): - cache_dir = tmp_path / "cache" - overlay._save_cached_frames( - cache_dir, [Image.new("RGB", (2, 2), "red")], [["cached"]] - ) - monkeypatch.setattr(overlay, "overlay_frame_cache_dir", lambda *args: cache_dir) - monkeypatch.setattr( - overlay.perceive, - "cache_or_load", - lambda *args: pytest.fail("cache hit should not touch perception"), - ) - - stamped, visible = overlay.stamp_frames( - [Image.new("RGB", (2, 2), "white")], - {}, - "scene", - "metric", - "uniform", - "tracking", - 1, - ) - - assert visible == [["cached"]] - assert stamped[0].getpixel((0, 0)) == (255, 0, 0) diff --git a/tests/test_C/test_overlay_launch.py b/tests/test_C/test_overlay_launch.py deleted file mode 100644 index 3b8ab35c47b74a51b9650679fd5368be8b2e3933..0000000000000000000000000000000000000000 --- a/tests/test_C/test_overlay_launch.py +++ /dev/null @@ -1,144 +0,0 @@ -"""Tests for harness/C/overlay_launch.py -- cache pregeneration orchestration.""" - -import pytest - -from harness.C import overlay_launch - - -def test_available_cpu_count_honors_positive_environment(monkeypatch): - monkeypatch.setenv("VSI_CPU_WORKERS", "3") - assert overlay_launch._available_cpu_count() == 3 - monkeypatch.setenv("VSI_CPU_WORKERS", "0") - with pytest.raises(ValueError, match="positive"): - overlay_launch._available_cpu_count() - - -def test_has_dependencies_requires_spatial_code_and_sam3_cache(monkeypatch, tmp_path): - cache = tmp_path / "sam3.pt" - monkeypatch.setattr( - overlay_launch.spatial_codes, - "load_spatial_code", - lambda *args: ({"objects": {}}, "code.json"), - ) - monkeypatch.setattr( - "encoder.config.sam3_cache_file", - lambda *args: cache, - ) - - assert ( - overlay_launch._has_dependencies("scene", "metric", "uniform", "tracking", 32) - is False - ) - cache.write_text("cache") - assert ( - overlay_launch._has_dependencies("scene", "metric", "uniform", "tracking", 32) - is True - ) - - -def test_has_dependencies_treats_missing_code_as_ineligible(monkeypatch): - def missing(*args): - raise FileNotFoundError("missing code") - - monkeypatch.setattr(overlay_launch.spatial_codes, "load_spatial_code", missing) - assert ( - overlay_launch._has_dependencies("scene", "metric", "uniform", "tracking", 32) - is False - ) - - -def test_launch_skips_missing_and_already_cached_without_pool( - monkeypatch, tmp_path, capsys -): - monkeypatch.setattr( - overlay_launch, - "_has_dependencies", - lambda scene, *args: scene != "missing", - ) - monkeypatch.setattr( - overlay_launch.overlay, - "overlay_frame_cache_dir", - lambda scene, *args: tmp_path / scene, - ) - monkeypatch.setattr( - overlay_launch.overlay, - "_load_cached_frames", - lambda cache_dir, frame_count: ( - ([object()], [[]]) if cache_dir.name == "cached" else None - ), - ) - monkeypatch.setattr( - overlay_launch.overlay, - "overlay_spatial_code_path", - lambda scene, *args: tmp_path / scene / "overlay-code.json", - ) - (tmp_path / "cached").mkdir() - (tmp_path / "cached" / "overlay-code.json").write_text("{}") - monkeypatch.setattr( - overlay_launch.mp, - "get_context", - lambda *_: pytest.fail("no pending scenes should avoid multiprocessing"), - ) - - succeeded, failed, missing = overlay_launch.launch( - "metric", "uniform", "tracking", 32, ["missing", "cached"] - ) - - assert succeeded == [] - assert failed == [] - assert missing == ["missing"] - output = capsys.readouterr().out - assert "missing a code or SAM3 cache" in output - assert "already cached" in output - - -def test_launch_does_not_skip_frames_cache_when_overlay_code_is_missing( - monkeypatch, tmp_path -): - monkeypatch.setattr(overlay_launch, "_has_dependencies", lambda scene, *args: True) - monkeypatch.setattr( - overlay_launch.overlay, - "overlay_frame_cache_dir", - lambda scene, *args: tmp_path / scene, - ) - monkeypatch.setattr( - overlay_launch.overlay, - "_load_cached_frames", - lambda cache_dir, frame_count: ([object()], [[]]), - ) - monkeypatch.setattr( - overlay_launch.overlay, - "overlay_spatial_code_path", - lambda scene, *args: tmp_path / scene / "missing-overlay-code.json", - ) - - calls = [] - - class FakePool: - def __init__(self, workers): - self.workers = workers - - def __enter__(self): - return self - - def __exit__(self, *exc): - return False - - def map(self, fn, tasks): - calls.extend(tasks) - return [(task[0], True, None) for task in tasks] - - class FakeContext: - def Pool(self, workers): - return FakePool(workers) - - monkeypatch.setattr(overlay_launch.mp, "get_context", lambda *_: FakeContext()) - - succeeded, failed, missing = overlay_launch.launch( - "metric", "uniform", "tracking", 32, ["frames_only"], workers=1 - ) - - assert calls == [("frames_only", "metric", "uniform", "tracking", 32)] - assert succeeded == ["frames_only"] - assert failed == [] - assert missing == [] diff --git a/tests/test_C/test_prompts.py b/tests/test_C/test_prompts.py deleted file mode 100644 index bbfb6e066facf20eb079b567791a8212697d5f30..0000000000000000000000000000000000000000 --- a/tests/test_C/test_prompts.py +++ /dev/null @@ -1,66 +0,0 @@ -"""Tests for harness/C/prompts.py -- combined frames+spatial-code prompt construction.""" - -import json - -import pytest - -from harness.A.prompts import MCA_QUESTION_TYPES, NA_QUESTION_TYPES -from harness.C import prompts as combined_prompts - -_CODE = { - "objects": {"chair": {"count": 1}}, - "room": {"floor area": "10.0 square meters"}, -} - - -def test_pre_prompt_mentions_both_frames_and_spatial_code(): - lowered = combined_prompts.PRE_PROMPT.lower() - assert "frame" in lowered - assert "spatial code" in lowered - - -def test_na_question_prompt_layout_is_context_then_code_then_question_then_post_prompt(): - prompt = combined_prompts.build_prompt(_CODE, "object_counting", "How many chairs?") - context_pos = prompt.find(combined_prompts.PRE_PROMPT) - code_pos = prompt.find(json.dumps(_CODE, indent=1)) - question_pos = prompt.find("How many chairs?") - post_pos = prompt.find(combined_prompts.NA_POST_PROMPT) - assert context_pos == 0 - assert context_pos < code_pos < question_pos < post_pos - - -def test_mca_question_prompt_includes_options_and_post_prompt(): - prompt = combined_prompts.build_prompt( - _CODE, "object_rel_distance", "Which is closest?", ["A. sofa", "B. table"] - ) - assert "Options:\nA. sofa\nB. table" in prompt - assert prompt.endswith(combined_prompts.MCA_POST_PROMPT) - - -def test_mca_question_requires_options(): - with pytest.raises(ValueError): - combined_prompts.build_prompt(_CODE, "route_planning", "Which way?", None) - - -def test_unknown_question_type_rejected(): - with pytest.raises(ValueError): - combined_prompts.build_prompt(_CODE, "not_a_real_type", "?", None) - - -@pytest.mark.parametrize("question_type", NA_QUESTION_TYPES) -def test_every_na_question_type_builds(question_type): - prompt = combined_prompts.build_prompt(_CODE, question_type, "q?") - assert prompt.startswith(combined_prompts.PRE_PROMPT) - - -@pytest.mark.parametrize("question_type", MCA_QUESTION_TYPES) -def test_every_mca_question_type_builds(question_type): - prompt = combined_prompts.build_prompt(_CODE, question_type, "q?", ["A. x", "B. y"]) - assert prompt.startswith(combined_prompts.PRE_PROMPT) - - -def test_video_prompt_names_native_video(): - prompt = combined_prompts.build_prompt( - _CODE, "object_counting", "How many chairs?", video=True - ) - assert prompt.startswith("This is a video.\n") diff --git a/tests/test_C/test_run.py b/tests/test_C/test_run.py deleted file mode 100644 index bc32ab67b3b8a65d2e962e96d82f984ca01f114a..0000000000000000000000000000000000000000 --- a/tests/test_C/test_run.py +++ /dev/null @@ -1,176 +0,0 @@ -"""Tests for harness/C/run.py -- result-record shape and result-file writing.""" - -import json - -from harness import C -from harness.C import run as harness_run - -_FAKE_ANSWER = { - "prompt_text": "", - "answer_text": "4", - "answer_raw": "<|im_start|>assistant\n4<|im_end|>", - "input_token_count": 22205, - "vision_input_shapes": {"pixel_values": [76800, 1536], "image_grid_thw": [64, 3]}, - "output_token_ids": [19, 151645], - "output_token_count": 2, - "hit_token_limit": False, - "eos_token_ids": [151645], - "generation_seconds": 5.6, - "device": "cuda", - "dtype": "bfloat16", - "library_versions": {"transformers": "5.14.1", "torch": "2.13.0+cu130"}, - "generation_config": { - "max_new_tokens": 16, - "do_sample": False, - "temperature": 0.0, - "top_p": None, - "top_k": None, - "enable_thinking": False, - }, -} - -_FAKE_ROW = { - "id": 7, - "scene_name": "scene0001_00", - "dataset": "scannet", - "question_type": "object_counting", - "question": "How many chairs?", - "options": None, - "ground_truth": "4", -} - -_FAKE_SOURCE_INFO = { - "protocol": "thinking", - "spatial_code_format": "explicit", - "input_selection": "selective", - "frame_count": 64, - "depth": "metric", - "tracking": "tracking", - "spatial_code_path": "/workspace/data/spatial codes/.../scene0001_00.json", - "video_path": "/root/data/VSI-Bench/scannet/scene0001_00.mp4", - "frame_indices": [0, 30, 60], - "frame_timestamps": [0.0, 1.0, 2.0], -} - - -def test_results_dir_for_matches_established_dimension_nesting(): - root = harness_run.results_dir_for( - "qwen3.5-4b", "thinking", "explicit", "metric", "tracking", "uniform", 32 - ) - assert root == ( - C.RESULTS_DIR - / "qwen3.5-4b" - / "explicit" - / "metric" - / "tracking" - / "uniform" - / "32" - ) - - -def test_results_dir_for_honors_explicit_override(tmp_path): - root = harness_run.results_dir_for( - "qwen3.5-4b", - "base", - "explicit", - "relative", - "no tracking", - "selective", - 16, - tmp_path, - ) - assert root == tmp_path - - -def test_build_record_carries_both_frame_and_spatial_code_provenance(): - record = harness_run._build_record( - _FAKE_ROW, - "full prompt text", - _FAKE_ANSWER, - "MRA:.5:.95:.05", - 1.0, - "qwen3.5-4b", - "/root/models/qwen3.5-4b", - _FAKE_SOURCE_INFO, - ) - # Spatial-code provenance (shared with harness.B). - assert record["spatial_code_format"] == "explicit" - assert record["input_selection"] == "selective" - assert record["frame_count"] == 64 - assert record["depth"] == "metric" - assert record["tracking"] == "tracking" - assert record["spatial_code_path"] == _FAKE_SOURCE_INFO["spatial_code_path"] - # Frame provenance (shared with harness.A). - assert record["video_path"] == _FAKE_SOURCE_INFO["video_path"] - assert record["frame_indices"] == [0, 30, 60] - assert record["frame_timestamps_seconds"] == [0.0, 1.0, 2.0] - # Question/answer fields, same shape as A and B. - assert record["question"] == "How many chairs?" - assert record["answer_given"] == "4" - assert record["vision_input_shapes"] == _FAKE_ANSWER["vision_input_shapes"] - assert record["condition"] == "extended:explicit:metric:tracking:selective:64" - assert record["protocol"] == "thinking" - assert record["score"] == 1.0 - - -def test_write_question_result_writes_one_json_file_per_question(tmp_path): - path, record = harness_run.write_question_result( - _FAKE_ROW, - "full prompt text", - _FAKE_ANSWER, - "MRA:.5:.95:.05", - 1.0, - "qwen3.5-4b", - "/root/models/qwen3.5-4b", - _FAKE_SOURCE_INFO, - results_dir=tmp_path, - ) - assert path == tmp_path / "scene0001_00" / "7.json" - on_disk = json.loads(path.read_text()) - assert on_disk == record - - -def test_build_record_carries_reasoning_fields_when_forced(): - extended_answer = { - **_FAKE_ANSWER, - "reasoning_text": "long reasoning about the frames and spatial code", - "reasoning_raw": "long reasoning about the frames and spatial code<|im_end|>", - "reasoning_token_ids": list(range(50)), - "reasoning_token_count": 50, - "reasoning_hit_limit": True, - "forced": True, - "forced_input_token_count": 22300, - } - record = harness_run._build_record( - _FAKE_ROW, - "full prompt text", - extended_answer, - "MRA:.5:.95:.05", - 1.0, - "qwen3.5-4b", - "/root/models/qwen3.5-4b", - _FAKE_SOURCE_INFO, - ) - assert ( - record["reasoning_text"] == "long reasoning about the frames and spatial code" - ) - assert record["forced"] is True - assert record["forced_input_token_count"] == 22300 - - -def test_video_results_use_video_branch(): - assert ( - harness_run.results_dir_for( - "qwen3.5-4b", "thinking", "explicit", "metric", "tracking", "video", None - ) - == C.RESULTS_DIR / "qwen3.5-4b" / "explicit" / "metric" / "tracking" / "video" - ) - - -def test_video_record_has_no_frame_count_in_condition(): - info = dict(_FAKE_SOURCE_INFO, input_selection="video", frame_count=None) - record = harness_run._build_record( - _FAKE_ROW, "prompt", _FAKE_ANSWER, "metric", 1.0, "qwen3.5-4b", "/model", info - ) - assert record["condition"] == "thinking:explicit:metric:tracking:video" - assert record["frame_count"] is None diff --git a/tests/test_C/test_sweep.py b/tests/test_C/test_sweep.py deleted file mode 100644 index c497f4f29f912024ad425bc513c0438c2e8752c2..0000000000000000000000000000000000000000 --- a/tests/test_C/test_sweep.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Tests for harness/C/sweep.py -- multi-config sweep planning.""" - -import pytest - -from harness.A import models as vlm_models -from harness.C import sweep - - -def test_build_plan_covers_every_combination(): - plan = sweep.build_plan( - ["qwen3.5-2b", "qwen3.5-4b"], - ["explicit"], - ["uniform", "selective"], - [16, 32], - ["metric"], - ["tracking"], - ) - assert len(plan) == 2 * 1 * 2 * 2 - assert ("qwen3.5-2b", "explicit", "metric", "tracking", "uniform", 16) in plan - assert ("qwen3.5-4b", "explicit", "metric", "tracking", "selective", 32) in plan - - -def test_build_plan_sweeps_depth_and_tracking_too(): - plan = sweep.build_plan( - ["qwen3.5-2b"], - ["explicit"], - ["uniform"], - [16], - ["metric", "relative"], - ["tracking", "no tracking"], - ) - assert len(plan) == 4 - assert ("qwen3.5-2b", "explicit", "relative", "no tracking", "uniform", 16) in plan - - -def test_build_plan_orders_by_frame_count_first(): - plan = sweep.build_plan( - ["qwen3.5-2b"], - ["explicit"], - ["uniform"], - [64, 16, 32], - ["metric"], - ["tracking"], - ) - assert [frame_count for *_rest, frame_count in plan] == [16, 32, 64] - - -def test_build_plan_with_all_registered_models(): - plan = sweep.build_plan( - list(vlm_models.available_models()), - ["explicit"], - ["uniform"], - [16], - ["metric"], - ["tracking"], - ) - assert len(plan) == len(vlm_models.available_models()) - - -def test_sweep_parser_rejects_unknown_depth(): - with pytest.raises(ValueError): - sweep._parse_csv_choice("bogus", sweep.DEPTH_VARIANTS, "--depths") - - -def test_sweep_parser_rejects_unknown_tracking(): - with pytest.raises(ValueError): - sweep._parse_csv_choice("bogus", sweep.TRACKING_MODES, "--trackings") diff --git a/tests/test_D/__init__.py b/tests/test_D/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/tests/test_D/conftest.py b/tests/test_D/conftest.py deleted file mode 100644 index 14a3272bdddc53337bcd1ed07dc1a360035d3bdc..0000000000000000000000000000000000000000 --- a/tests/test_D/conftest.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Shared, self-contained import setup for harness.D tests.""" - -import os -from pathlib import Path -import sys -import tempfile -import types - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -# D imports the official VSI scorer eagerly. Provide a tiny interface-compatible scorer -# and manifest so unit tests do not depend on /root/data being mounted. -_FIXTURES = Path(tempfile.mkdtemp(prefix="test_D_")) -_SCORER = _FIXTURES / "utils.py" -_SCORER.write_text( - 'MCA_QUESTION_TYPES = ("object_rel_direction_easy", "object_rel_direction_medium", "object_rel_direction_hard", "object_rel_distance", "route_planning", "obj_appearance_order")\n' - 'NA_QUESTION_TYPES = ("object_abs_distance", "object_counting", "object_size_estimation", "room_size_estimation")\n' - 'METRICS_FOR_MCA = {"exact_match": None}\n' - 'METRICS_FOR_NA = {"MRA:.5:.95:.05": None}\n' - "def vsibench_process_results(doc, results):\n" - ' metric = "exact_match" if doc["question_type"] in MCA_QUESTION_TYPES else "MRA:.5:.95:.05"\n' - ' score = float(str(results[0]).strip() == str(doc["ground_truth"]).strip())\n' - ' return {"vsibench_score": {metric: score}}\n' -) -_MANIFEST = _FIXTURES / "test.jsonl" -_MANIFEST.write_text( - '{"id": 7, "scene_name": "13c3e046d7", "dataset": "scannet", "question_type": "object_counting", "question": "How many chairs?", "options": null, "ground_truth": "1"}\n' -) -os.environ["HARNESS_OFFICIAL_EVAL"] = str(_SCORER) -os.environ["SYMBOLIC_OFFICIAL_EVAL"] = str(_SCORER) -sys.path.insert(0, str(_FIXTURES)) -os.environ["VSI_JSONL"] = str(_MANIFEST) - -# OpenCV is only needed when the optional frame arm actually decodes a video. Frame -# unit tests monkeypatch that boundary and never call this placeholder. -if "cv2" not in sys.modules: - cv2 = types.ModuleType("cv2") - cv2.CAP_PROP_FPS = 5 - sys.modules["cv2"] = cv2 - - -def pytest_configure(config): - config.option.importmode = "importlib" diff --git a/tests/test_D/test_D.py b/tests/test_D/test_D.py deleted file mode 100644 index 9989e0c2371219f148e0b57e9c1e0c7c5542d5c4..0000000000000000000000000000000000000000 --- a/tests/test_D/test_D.py +++ /dev/null @@ -1,21 +0,0 @@ -"""Tests for harness/D/__init__.py -- shared config constants.""" - -from pathlib import Path - -from harness import A, B, D - - -def test_spatial_code_formats_reuse_harness_b_vocabulary(): - assert D.SPATIAL_CODE_FORMATS == B.SPATIAL_CODE_FORMATS - assert D.DEFAULT_SPATIAL_CODE_FORMAT in D.SPATIAL_CODE_FORMATS - - -def test_reuses_harness_a_model_paths_and_generation_protocol(): - assert D.MODEL_PATHS is A.MODEL_PATHS - assert D.MAX_NEW_TOKENS == A.MAX_NEW_TOKENS - assert D.DO_SAMPLE == A.DO_SAMPLE - assert D.TEMPERATURE == A.TEMPERATURE - - -def test_results_dir_defaults_under_root_results(): - assert D.RESULTS_DIR == Path("/root/results/D") diff --git a/tests/test_D/test_init.py b/tests/test_D/test_init.py deleted file mode 100644 index 5164a571f95d4a5ad250132d0ed90430297ac338..0000000000000000000000000000000000000000 --- a/tests/test_D/test_init.py +++ /dev/null @@ -1,19 +0,0 @@ -"""Tests for harness/D/__init__.py -- shared config constants.""" - -from harness import A, B, D - - -def test_spatial_code_formats_reuse_harness_b_vocabulary(): - assert D.SPATIAL_CODE_FORMATS == B.SPATIAL_CODE_FORMATS - assert D.DEFAULT_SPATIAL_CODE_FORMAT in D.SPATIAL_CODE_FORMATS - - -def test_reuses_harness_a_model_paths_and_generation_protocol(): - assert D.MODEL_PATHS is A.MODEL_PATHS - assert D.MAX_NEW_TOKENS == A.MAX_NEW_TOKENS - assert D.DO_SAMPLE == A.DO_SAMPLE - assert D.TEMPERATURE == A.TEMPERATURE - - -def test_results_dir_defaults_under_workspace_results(): - assert D.RESULTS_DIR == D.WORKSPACE_ROOT / "results" / "D" diff --git a/tests/test_D/test_launch.py b/tests/test_D/test_launch.py deleted file mode 100644 index 08f7a5419a82b2e2be3378a1cc2dbf910f863ff8..0000000000000000000000000000000000000000 --- a/tests/test_D/test_launch.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Tests for harness/D/launch.py -- multi-GPU scene sharding across workers.""" - -from harness.D import launch - - -def test_launcher_imports(): - assert callable(launch.main) - - -class _FakeRun: - rows = [{"id": 2}, {"id": 5}] - - @staticmethod - def results_dir_for(*args, **kwargs): - return args[3] - - @classmethod - def load_questions(cls, scene=None): - return list(cls.rows) - - -def test_launch_skips_scene_already_fully_answered(tmp_path, capsys, monkeypatch): - scene = "scene-d" - monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) - - scene_dir = tmp_path / scene - scene_dir.mkdir() - for row in _FakeRun.rows: - (scene_dir / f"{row['id']}.json").write_text("{}") - - launch.launch("qwen3.5-2b", "explicit", [scene], results_dir=tmp_path) - - output = capsys.readouterr().out - assert "skipped" in output - assert "DONE: 1 ok, 0 failed" in output - - -def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch): - scene = "scene-d" - monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) - scene_dir = tmp_path / scene - scene_dir.mkdir() - for row in _FakeRun.rows: - (scene_dir / f"{row['id']}.json").write_text("{}") - - monkeypatch.setattr(launch, "visible_gpus", lambda: []) - monkeypatch.setattr( - launch.mp, - "get_context", - lambda *_: (_ for _ in ()).throw( - RuntimeError("rebuild correctly reached worker dispatch") - ), - ) - try: - launch.launch( - "qwen3.5-2b", "explicit", [scene], results_dir=tmp_path, rebuild=True - ) - except RuntimeError as exc: - assert "rebuild correctly reached worker dispatch" in str(exc) - else: - raise AssertionError("expected rebuild to force scene into the pending path") - - -def test_scenes_is_subset_of_vsi_bench_scenes_with_ground_truth_coverage(monkeypatch): - monkeypatch.setattr("harness.A.launch.scenes", lambda: ["a", "b", "c"]) - monkeypatch.setattr(launch, "ground_truth_scenes", lambda: ["b", "c", "z"]) - assert launch.scenes() == ["b", "c"] diff --git a/tests/test_D/test_prompts.py b/tests/test_D/test_prompts.py deleted file mode 100644 index 53ac352315b71bd29d86dc1bf39345149d0cc08b..0000000000000000000000000000000000000000 --- a/tests/test_D/test_prompts.py +++ /dev/null @@ -1,55 +0,0 @@ -"""Tests for harness/D/prompts.py -- ground-truth spatial-code-as-text prompt construction.""" - -import json - -import pytest - -from harness.A.prompts import MCA_QUESTION_TYPES, NA_QUESTION_TYPES -from harness.D import prompts as code_prompts - -_CODE = { - "objects": {"chair": {"count": 1}}, - "room": {"floor area": "10.0 square meters"}, -} - - -def test_na_question_prompt_embeds_the_spatial_code_as_text_and_a_post_prompt(): - prompt = code_prompts.build_prompt(_CODE, "object_counting", "How many chairs?") - assert prompt.startswith(code_prompts.PRE_PROMPT) - assert json.dumps(_CODE, indent=1) in prompt - assert prompt.endswith(code_prompts.NA_POST_PROMPT) - - -def test_mca_question_prompt_includes_options_and_matches_harness_a_post_prompt(): - prompt = code_prompts.build_prompt( - _CODE, "object_rel_distance", "Which is closest?", ["A. sofa", "B. table"] - ) - assert "Options:\nA. sofa\nB. table" in prompt - assert prompt.endswith(code_prompts.MCA_POST_PROMPT) - - -def test_mca_question_requires_options(): - with pytest.raises(ValueError): - code_prompts.build_prompt(_CODE, "route_planning", "Which way?", None) - - -def test_unknown_question_type_rejected(): - with pytest.raises(ValueError): - code_prompts.build_prompt(_CODE, "not_a_real_type", "?", None) - - -def test_no_frames_or_video_language_in_pre_prompt(): - assert "frame" not in code_prompts.PRE_PROMPT.lower() - assert "video" not in code_prompts.PRE_PROMPT.lower() - - -@pytest.mark.parametrize("question_type", NA_QUESTION_TYPES) -def test_every_na_question_type_builds(question_type): - prompt = code_prompts.build_prompt(_CODE, question_type, "q?") - assert prompt.startswith(code_prompts.PRE_PROMPT) - - -@pytest.mark.parametrize("question_type", MCA_QUESTION_TYPES) -def test_every_mca_question_type_builds(question_type): - prompt = code_prompts.build_prompt(_CODE, question_type, "q?", ["A. x", "B. y"]) - assert prompt.startswith(code_prompts.PRE_PROMPT) diff --git a/tests/test_D/test_run.py b/tests/test_D/test_run.py deleted file mode 100644 index 5b958de017e2594e13a06954fd9703a340ce3f77..0000000000000000000000000000000000000000 --- a/tests/test_D/test_run.py +++ /dev/null @@ -1,246 +0,0 @@ -"""Tests for harness/D/run.py -- result-record shape and result-file writing.""" - -import json - -from harness import D -from harness.D import run as harness_run - -_FAKE_ANSWER = { - "prompt_text": "", - "answer_text": "4", - "answer_raw": "<|im_start|>assistant\n4<|im_end|>", - "input_token_count": 2558, - "vision_input_shapes": {"mm_token_type_ids": [1, 2558]}, - "output_token_ids": [19, 151645], - "output_token_count": 2, - "hit_token_limit": False, - "eos_token_ids": [151645], - "generation_seconds": 0.65, - "device": "cuda", - "dtype": "bfloat16", - "library_versions": {"transformers": "5.14.1", "torch": "2.13.0+cu130"}, - "generation_config": { - "max_new_tokens": 16, - "do_sample": False, - "temperature": 0.0, - "top_p": None, - "top_k": None, - "enable_thinking": False, - }, -} - -_FAKE_ROW = { - "id": 7, - "scene_name": "scene0001_00", - "dataset": "scannet", - "question_type": "object_counting", - "question": "How many chairs?", - "options": None, - "ground_truth": "4", -} - -_FAKE_CODE_INFO = { - "protocol": "extended", - "spatial_code_format": "explicit", - "spatial_code_path": "/workspace/data/spatial codes/ground truth/explicit/scene0001_00.json", -} - - -def test_results_dir_for_matches_model_protocol_and_format_only(): - root = harness_run.results_dir_for("qwen3.5-4b", "extended", "compact") - assert root == D.RESULTS_DIR / "qwen3.5-4b" / "code" / "extended" / "compact" - - -def test_results_dir_for_isolates_frames_and_truncated_budget_arms(): - root = harness_run.results_dir_for( - "qwen3.5-4b", - "truncated/64", - "explicit", - frames=True, - frame_selection="uniform", - frame_count=32, - ) - assert root == ( - D.RESULTS_DIR - / "qwen3.5-4b" - / "code + frames" - / "truncated" - / "64" - / "explicit" - / "uniform" - / "32" - ) - - -def test_build_record_describes_frames_plus_ground_truth_condition(): - code_info = { - **_FAKE_CODE_INFO, - "protocol": "512", - "frames": True, - "frame_selection": "uniform", - "frame_count": 32, - "video_path": "/fake/scene.mp4", - "frame_indices": [0, 30], - "frame_timestamps": [0.0, 1.0], - } - record = harness_run._build_record( - _FAKE_ROW, - "full prompt text", - _FAKE_ANSWER, - "MRA:.5:.95:.05", - 1.0, - "qwen3.5-4b", - "/root/models/qwen3.5-4b", - code_info, - ) - assert record["condition"] == "512:explicit:frames:uniform:32" - assert record["frames"] is True - assert record["video_path"] == "/fake/scene.mp4" - assert record["frame_indices"] == [0, 30] - assert record["frame_timestamps_seconds"] == [0.0, 1.0] - - -def test_results_dir_for_honors_explicit_override(tmp_path): - root = harness_run.results_dir_for("qwen3.5-4b", "base", "explicit", tmp_path) - assert root == tmp_path - - -def test_build_record_preserves_every_field_untruncated(): - record = harness_run._build_record( - _FAKE_ROW, - "full prompt text", - _FAKE_ANSWER, - "MRA:.5:.95:.05", - 1.0, - "qwen3.5-4b", - "/root/models/qwen3.5-4b", - _FAKE_CODE_INFO, - ) - assert record["question"] == "How many chairs?" - assert record["full_prompt"] == "full prompt text" - assert record["rendered_prompt"] == _FAKE_ANSWER["prompt_text"] - assert record["answer_given"] == "4" - assert record["spatial_code_format"] == "explicit" - assert record["spatial_code_path"] == _FAKE_CODE_INFO["spatial_code_path"] - # No depth/tracking/input_selection -- ground truth has no such axis. frames/ - # frame_selection/frame_count/video_path/frame_indices/frame_timestamps_seconds DO - # exist on every record (the frames+ground-truth-code arm's fields), null here since - # _FAKE_CODE_INFO has no "frames" key -- same present-but-null pattern as - # reasoning_text on a base-protocol record. - assert record["condition"] == "extended:explicit" - assert record["protocol"] == "extended" - assert record["frames"] is False - assert record["frame_selection"] is None - assert record["frame_count"] is None - assert record["video_path"] is None - assert "input_selection" not in record - assert "depth" not in record - assert "tracking" not in record - assert record["metric"] == "MRA:.5:.95:.05" - assert record["score"] == 1.0 - assert record["scene"] == "scene0001_00" - assert record["question_id"] == 7 - - -def test_write_question_result_writes_one_json_file_per_question(tmp_path): - path, record = harness_run.write_question_result( - _FAKE_ROW, - "full prompt text", - _FAKE_ANSWER, - "MRA:.5:.95:.05", - 1.0, - "qwen3.5-4b", - "/root/models/qwen3.5-4b", - _FAKE_CODE_INFO, - results_dir=tmp_path, - ) - assert path == tmp_path / "scene0001_00" / "7.json" - on_disk = json.loads(path.read_text()) - assert on_disk == record - - -def test_build_record_carries_reasoning_fields_when_forced(): - extended_answer = { - **_FAKE_ANSWER, - "reasoning_text": "long reasoning about the spatial code", - "reasoning_raw": "long reasoning about the spatial code<|im_end|>", - "reasoning_token_ids": list(range(50)), - "reasoning_token_count": 50, - "reasoning_hit_limit": True, - "forced": True, - "forced_input_token_count": 2510, - } - record = harness_run._build_record( - _FAKE_ROW, - "full prompt text", - extended_answer, - "MRA:.5:.95:.05", - 1.0, - "qwen3.5-4b", - "/root/models/qwen3.5-4b", - _FAKE_CODE_INFO, - ) - assert record["reasoning_text"] == "long reasoning about the spatial code" - assert record["forced"] is True - assert record["forced_input_token_count"] == 2510 - - -def test_build_record_defaults_reasoning_fields_when_absent(): - record = harness_run._build_record( - _FAKE_ROW, - "full prompt text", - _FAKE_ANSWER, - "MRA:.5:.95:.05", - 1.0, - "qwen3.5-4b", - "/root/models/qwen3.5-4b", - _FAKE_CODE_INFO, - ) - assert record["reasoning_token_count"] is None - assert record["forced"] is False - - -def test_run_code_transform_hook_replaces_the_loaded_code(monkeypatch, tmp_path): - """The corruption module's entry point: the hook's return value is what the - prompt is built from, and passing no hook keeps behavior identical.""" - scene = "13c3e046d7" - seen = {} - - def fake_load(scene_id, spatial_code_format): - return {"objects": {"chair": {"count": 1}}}, f"/fake/{scene_id}.json" - - class FakeAdapter: - model_path = "/fake/model" - - def answer_extended(self, frames, prompt, **kwargs): - seen["prompt"] = prompt - return { - "prompt_text": prompt, - "answer_text": "1", - "answer_raw": "1", - "input_token_count": 1, - "vision_input_shapes": {}, - "output_token_ids": [1], - "output_token_count": 1, - "hit_token_limit": False, - "eos_token_ids": [1], - "generation_seconds": 0.0, - "device": "cpu", - "dtype": "float32", - "library_versions": {}, - "generation_config": {}, - } - - monkeypatch.setattr(harness_run.spatial_codes, "load_spatial_code", fake_load) - replacement = {"objects": {"table": {"count": 9}}} - results = harness_run.run( - "qwen3.5-2b", - scene=scene, - adapter=FakeAdapter(), - write_results=False, - limit=1, - code_transform=lambda code, scene_id, fmt: replacement, - ) - assert results - assert '"table"' in seen["prompt"] - assert '"chair"' not in seen["prompt"] diff --git a/tests/test_D/test_spatial_codes.py b/tests/test_D/test_spatial_codes.py deleted file mode 100644 index 7bfe4b9759c034727417933f4d25e97c96c4e15a..0000000000000000000000000000000000000000 --- a/tests/test_D/test_spatial_codes.py +++ /dev/null @@ -1,33 +0,0 @@ -"""Tests for harness/D/spatial_codes.py -- loading on-disk ground-truth spatial codes.""" - -import json - -import pytest - -from harness.D import spatial_codes - - -def test_load_spatial_code_rejects_unknown_format(): - with pytest.raises(ValueError): - spatial_codes.load_spatial_code("scene", "bogus") - - -def test_load_spatial_code_raises_clearly_when_missing(tmp_path, monkeypatch): - monkeypatch.setattr( - spatial_codes, - "ground_truth_spatial_code_path", - lambda *a, **k: str(tmp_path / "missing.json"), - ) - with pytest.raises(FileNotFoundError): - spatial_codes.load_spatial_code("scene", "explicit") - - -def test_load_spatial_code_returns_dict_and_path(tmp_path, monkeypatch): - fixture = tmp_path / "scene1.json" - fixture.write_text(json.dumps({"objects": {}, "room": {}})) - monkeypatch.setattr( - spatial_codes, "ground_truth_spatial_code_path", lambda *a, **k: str(fixture) - ) - code, path = spatial_codes.load_spatial_code("scene1", "compact") - assert code == {"objects": {}, "room": {}} - assert path == str(fixture) diff --git a/tests/test_D/test_sweep.py b/tests/test_D/test_sweep.py deleted file mode 100644 index 6c8e5b1bbb97ad37db8e5cc33104d136a7d7438d..0000000000000000000000000000000000000000 --- a/tests/test_D/test_sweep.py +++ /dev/null @@ -1,28 +0,0 @@ -"""Tests for harness/D/sweep.py -- multi-config sweep planning.""" - -from harness.A import models as vlm_models -from harness.D import sweep - - -def test_build_plan_covers_every_combination(): - plan = sweep.build_plan(["qwen3.5-2b", "qwen3.5-4b"], ["explicit", "compact"]) - assert len(plan) == 4 - assert ("qwen3.5-2b", "explicit") in plan - assert ("qwen3.5-4b", "compact") in plan - - -def test_build_plan_with_all_registered_models(): - plan = sweep.build_plan(list(vlm_models.available_models()), ["explicit"]) - assert len(plan) == len(vlm_models.available_models()) - - -def test_default_spatial_code_formats_cover_both_when_not_restricted(): - # This session's execution-design decision: D sweeps both formats by default - # (unlike a hypothetical "winning cell only" design) since ground truth costs - # nothing extra to build across formats. - import argparse - - parser = argparse.ArgumentParser() - parser.add_argument("--spatial-code-formats", default="all") - args = parser.parse_args([]) - assert args.spatial_code_formats == "all" diff --git a/tests/test_D/test_symbolic_eval.py b/tests/test_D/test_symbolic_eval.py deleted file mode 100644 index 39e8c19b0c05bfe224c2d413a67a20c70b210358..0000000000000000000000000000000000000000 --- a/tests/test_D/test_symbolic_eval.py +++ /dev/null @@ -1,116 +0,0 @@ -"""Tests for harness/D/symbolic_eval.py -- symbolic solver run directly on ground-truth -spatial codes, no VLM, written through symbolic.run's own writer into -results/symbolic/ground truth//... (not a separate results/D/... location).""" - -import json - -from harness.D import symbolic_eval - -_FAKE_CODE = { - "spatial code schema": {}, - "objects": { - "chair": [ - { - "3D oriented bounding box": { - "3D oriented bounding box center coordinates": [0, 0, 0.5], - "3D oriented bounding box dimensions": [1, 1, 1], - "3D oriented bounding box orientation unit vectors": [ - [1, 0, 0], - [0, 1, 0], - [0, 0, 1], - ], - }, - "first visible time": 0.0, - } - ] - }, - "room": {"floor boundary polygons": []}, -} - - -def _fake_load(scene_id, spatial_code_format): - return _FAKE_CODE, f"/fake/{scene_id}.json" - - -def test_run_answers_real_questions_for_a_real_ground_truth_scene( - tmp_path, monkeypatch -): - scene = "13c3e046d7" - monkeypatch.setattr(symbolic_eval.spatial_codes, "load_spatial_code", _fake_load) - - results = symbolic_eval.run( - spatial_code_format="compact", - scene=scene, - results_dir=tmp_path, - ) - - assert results - for record in results: - assert record["scene"] == scene - assert record["result_path"] is not None - - written = list(tmp_path.rglob("*.json")) - assert len(written) == len(results) - native_record = json.loads(written[0].read_text()) - assert native_record["model"] == "symbolic" - assert native_record["condition"] == "ground truth:compact" - assert native_record["scene"] == scene - - -def test_run_selects_ground_truth_spatial_codes_when_writing(tmp_path, monkeypatch): - scene = "13c3e046d7" - monkeypatch.setattr(symbolic_eval.spatial_codes, "load_spatial_code", _fake_load) - called = {"select": False, "format": None} - - def fake_select(spatial_code_format): - called["select"] = True - called["format"] = spatial_code_format - - monkeypatch.setattr( - symbolic_eval.symbolic_run, "select_ground_truth_spatial_codes", fake_select - ) - - symbolic_eval.run(spatial_code_format="explicit", scene=scene, results_dir=tmp_path) - - assert called["select"] is True - assert called["format"] == "explicit" - - -def test_run_does_not_write_when_write_results_is_false(tmp_path, monkeypatch): - scene = "13c3e046d7" - monkeypatch.setattr(symbolic_eval.spatial_codes, "load_spatial_code", _fake_load) - called = {"select": False} - monkeypatch.setattr( - symbolic_eval.symbolic_run, - "select_ground_truth_spatial_codes", - lambda *a, **k: called.__setitem__("select", True), - ) - - results = symbolic_eval.run( - spatial_code_format="compact", - scene=scene, - results_dir=tmp_path, - write_results=False, - ) - - assert called["select"] is False - assert results - for record in results: - assert record["result_path"] is None - assert list(tmp_path.rglob("*.json")) == [] - - -def test_run_forwards_results_dir_to_symbolic_writer(tmp_path, monkeypatch): - scene = "13c3e046d7" - monkeypatch.setattr(symbolic_eval.spatial_codes, "load_spatial_code", _fake_load) - seen = {} - - def fake_write(scene_id, pq, code, results_dir=None): - seen["results_dir"] = results_dir - return tmp_path / "fake.json" - - monkeypatch.setattr(symbolic_eval.symbolic_run, "write_question_result", fake_write) - - symbolic_eval.run(spatial_code_format="compact", scene=scene, results_dir=tmp_path) - - assert seen["results_dir"] == tmp_path diff --git a/tests/test_E/__init__.py b/tests/test_E/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/tests/test_E/conftest.py b/tests/test_E/conftest.py deleted file mode 100644 index 8a801f94b60da603c80287f186e31c5d32012e99..0000000000000000000000000000000000000000 --- a/tests/test_E/conftest.py +++ /dev/null @@ -1,12 +0,0 @@ -"""Shared import setup for this test package.""" - -from pathlib import Path -import sys - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - - -def pytest_configure(config): - config.option.importmode = "importlib" diff --git a/tests/test_E/test_E.py b/tests/test_E/test_E.py deleted file mode 100644 index 3656a84bdfd3a36926b95730ad130fa769650a9b..0000000000000000000000000000000000000000 --- a/tests/test_E/test_E.py +++ /dev/null @@ -1,20 +0,0 @@ -"""Tests for harness/E package configuration.""" - -import importlib -from pathlib import Path - -from harness import E - - -def test_blind_floor_reuses_harness_a_public_config(): - assert E.PROTOCOLS == ("base", "extended") - assert "qwen3.5-2b" in E.MODEL_PATHS - assert E.RESULTS_DIR == Path("/root/results/E") - - -def test_results_dir_can_be_overridden_by_environment(monkeypatch, tmp_path): - monkeypatch.setenv("VSI_HARNESS_E_RESULTS_DIR", str(tmp_path / "E")) - reloaded = importlib.reload(E) - assert reloaded.RESULTS_DIR == tmp_path / "E" - monkeypatch.delenv("VSI_HARNESS_E_RESULTS_DIR") - importlib.reload(E) diff --git a/tests/test_E/test_launch.py b/tests/test_E/test_launch.py deleted file mode 100644 index 8879c92358f669bf9bd6d3e81bd77cc5299dd2da..0000000000000000000000000000000000000000 --- a/tests/test_E/test_launch.py +++ /dev/null @@ -1,66 +0,0 @@ -"""Tests for harness/E/launch.py -- multi-GPU scene sharding for the blind floor.""" - -from harness.E import launch - - -def test_launcher_imports(): - assert callable(launch.main) - - -class _FakeRun: - rows = [{"id": 4}, {"id": 9}] - - @staticmethod - def results_dir_for(model, protocol, results_dir=None): - return results_dir - - @classmethod - def load_questions(cls, scene=None): - return list(cls.rows) - - -def test_launch_skips_scene_already_fully_answered(tmp_path, capsys, monkeypatch): - scene = "scene-e" - monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) - - scene_dir = tmp_path / scene - scene_dir.mkdir() - for row in _FakeRun.rows: - (scene_dir / f"{row['id']}.json").write_text("{}") - - launch.launch("qwen3.5-2b", [scene], results_dir=tmp_path) - - output = capsys.readouterr().out - assert "skipped" in output - assert "DONE: 1 ok, 0 failed" in output - - -def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch): - scene = "scene-e" - monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) - scene_dir = tmp_path / scene - scene_dir.mkdir() - for row in _FakeRun.rows: - (scene_dir / f"{row['id']}.json").write_text("{}") - - monkeypatch.setattr(launch, "visible_gpus", lambda: []) - monkeypatch.setattr( - launch.mp, - "get_context", - lambda *_: (_ for _ in ()).throw( - RuntimeError("rebuild correctly reached worker dispatch") - ), - ) - try: - launch.launch("qwen3.5-2b", [scene], results_dir=tmp_path, rebuild=True) - except RuntimeError as exc: - assert "rebuild correctly reached worker dispatch" in str(exc) - else: - raise AssertionError("expected rebuild to force scene into the pending path") - - -def test_launch_protocols_use_separate_result_roots(): - run = launch._load_run_module() - base = run.results_dir_for("qwen3.5-2b", "base") - extended = run.results_dir_for("qwen3.5-2b", "extended") - assert base != extended diff --git a/tests/test_E/test_prompts.py b/tests/test_E/test_prompts.py deleted file mode 100644 index 41570afc460258064e85f423d6ec42294562c43d..0000000000000000000000000000000000000000 --- a/tests/test_E/test_prompts.py +++ /dev/null @@ -1,48 +0,0 @@ -"""Tests for harness/E/prompts.py -- blind question-only prompt construction.""" - -import pytest - -from harness.A.prompts import MCA_QUESTION_TYPES, NA_QUESTION_TYPES -from harness.E import prompts as blind_prompts - - -def test_na_question_prompt_is_question_plus_post_prompt_only(): - prompt = blind_prompts.build_prompt("object_counting", "How many chairs?") - assert prompt == "How many chairs?\n" + blind_prompts.NA_POST_PROMPT - - -def test_mca_question_prompt_includes_options_and_post_prompt(): - prompt = blind_prompts.build_prompt( - "object_rel_distance", "Which is closest?", ["A. sofa", "B. table"] - ) - assert "Options:\nA. sofa\nB. table" in prompt - assert prompt.endswith(blind_prompts.MCA_POST_PROMPT) - - -def test_no_scene_language_anywhere(): - # Blind means blind: no context line claiming frames, video, or a spatial code. - prompt = blind_prompts.build_prompt("object_counting", "How many chairs?") - lowered = prompt.lower() - assert "frame" not in lowered - assert "video" not in lowered - assert "spatial code" not in lowered - - -def test_mca_question_requires_options(): - with pytest.raises(ValueError): - blind_prompts.build_prompt("route_planning", "Which way?", None) - - -def test_unknown_question_type_rejected(): - with pytest.raises(ValueError): - blind_prompts.build_prompt("not_a_real_type", "?", None) - - -@pytest.mark.parametrize("question_type", NA_QUESTION_TYPES) -def test_every_na_question_type_builds(question_type): - assert blind_prompts.build_prompt(question_type, "q?") - - -@pytest.mark.parametrize("question_type", MCA_QUESTION_TYPES) -def test_every_mca_question_type_builds(question_type): - assert blind_prompts.build_prompt(question_type, "q?", ["A. x", "B. y"]) diff --git a/tests/test_E/test_run.py b/tests/test_E/test_run.py deleted file mode 100644 index 8452b467d423715a3c6ad703eb39aea760bb87b3..0000000000000000000000000000000000000000 --- a/tests/test_E/test_run.py +++ /dev/null @@ -1,97 +0,0 @@ -"""Tests for harness/E/run.py -- result-record shape and result-file writing.""" - -import json - -from harness import E -from harness.E import run as harness_run - -_FAKE_ANSWER = { - "prompt_text": "", - "answer_text": "4", - "answer_raw": "<|im_start|>assistant\n4<|im_end|>", - "input_token_count": 42, - "vision_input_shapes": {}, - "output_token_ids": [19, 151645], - "output_token_count": 2, - "hit_token_limit": False, - "eos_token_ids": [151645], - "generation_seconds": 0.2, - "device": "cuda", - "dtype": "bfloat16", - "library_versions": {"transformers": "5.14.1", "torch": "2.13.0+cu130"}, - "generation_config": { - "max_new_tokens": 16, - "do_sample": False, - "temperature": 0.0, - "top_p": None, - "top_k": None, - "enable_thinking": False, - }, -} - -_FAKE_ROW = { - "id": 7, - "scene_name": "scene0001_00", - "dataset": "scannet", - "question_type": "object_counting", - "question": "How many chairs?", - "options": None, - "ground_truth": "4", -} - - -def test_results_dir_for_matches_model_and_protocol_only(): - root = harness_run.results_dir_for("qwen3.5-4b", "base") - assert root == E.RESULTS_DIR / "qwen3.5-4b" / "base" - - -def test_results_dir_for_isolates_the_two_protocols(): - assert harness_run.results_dir_for( - "qwen3.5-4b", "base" - ) != harness_run.results_dir_for("qwen3.5-4b", "extended") - - -def test_results_dir_for_honors_explicit_override(tmp_path): - assert harness_run.results_dir_for("qwen3.5-4b", "base", tmp_path) == tmp_path - - -def test_build_record_has_no_scene_input_provenance(): - record = harness_run._build_record( - _FAKE_ROW, - "full prompt text", - _FAKE_ANSWER, - "MRA:.5:.95:.05", - 1.0, - "qwen3.5-4b", - "/root/models/qwen3.5-4b", - "base", - ) - assert record["condition"] == "base" - assert record["protocol"] == "base" - assert record["question"] == "How many chairs?" - assert record["answer_given"] == "4" - assert record["metric"] == "MRA:.5:.95:.05" - assert record["score"] == 1.0 - # Blind: no frame or spatial-code provenance of any kind. - assert "frame_selection" not in record - assert "video_path" not in record - assert "frame_indices" not in record - assert "spatial_code_format" not in record - assert "spatial_code_path" not in record - - -def test_write_question_result_writes_one_json_file_per_question(tmp_path): - path, record = harness_run.write_question_result( - _FAKE_ROW, - "full prompt text", - _FAKE_ANSWER, - "MRA:.5:.95:.05", - 1.0, - "qwen3.5-4b", - "/root/models/qwen3.5-4b", - "base", - results_dir=tmp_path, - ) - assert path == tmp_path / "scene0001_00" / "7.json" - on_disk = json.loads(path.read_text()) - assert on_disk == record diff --git a/tests/test_E/test_sweep.py b/tests/test_E/test_sweep.py deleted file mode 100644 index 14ea803121f66e56d137c3378e939a1f9514139b..0000000000000000000000000000000000000000 --- a/tests/test_E/test_sweep.py +++ /dev/null @@ -1,40 +0,0 @@ -"""Tests for harness/E/sweep.py -- per-model blind-floor sweeping.""" - -import pytest - -from harness.E import sweep - - -def test_sweep_imports(): - assert callable(sweep.main) - - -def test_sweep_runs_every_model_through_launch(monkeypatch): - launched = [] - monkeypatch.setattr( - sweep.harness_launch, - "launch", - lambda model, scenes, **kwargs: launched.append( - (model, kwargs.get("extended")) - ), - ) - sweep.sweep(["qwen3.5-2b", "qwen3.5-4b"], ["scene_a"], extended=True) - assert launched == [("qwen3.5-2b", True), ("qwen3.5-4b", True)] - - -def test_sweep_defaults_to_base_protocol(monkeypatch): - launched = [] - monkeypatch.setattr( - sweep.harness_launch, - "launch", - lambda model, scenes, **kwargs: launched.append(kwargs.get("extended")), - ) - sweep.sweep(["qwen3.5-2b"], ["scene_a"]) - assert launched == [False] - - -def test_sweep_parser_rejects_unknown_model(monkeypatch, capsys): - monkeypatch.setattr("sys.argv", ["sweep", "--models", "not-a-model"]) - with pytest.raises(SystemExit): - sweep.main() - assert "unknown" in capsys.readouterr().err diff --git a/tests/test_F/__init__.py b/tests/test_F/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/tests/test_F/conftest.py b/tests/test_F/conftest.py deleted file mode 100644 index 8a801f94b60da603c80287f186e31c5d32012e99..0000000000000000000000000000000000000000 --- a/tests/test_F/conftest.py +++ /dev/null @@ -1,12 +0,0 @@ -"""Shared import setup for this test package.""" - -from pathlib import Path -import sys - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - - -def pytest_configure(config): - config.option.importmode = "importlib" diff --git a/tests/test_F/test_F.py b/tests/test_F/test_F.py deleted file mode 100644 index bab18510998a1a4f6610b195409163f0d297285c..0000000000000000000000000000000000000000 --- a/tests/test_F/test_F.py +++ /dev/null @@ -1,20 +0,0 @@ -"""Tests for harness/F package configuration.""" - -import importlib -from pathlib import Path - -from harness import F - - -def test_sources_and_default_are_declared(): - assert F.SOURCES == ("perceived",) - assert F.DEFAULT_SOURCE == "perceived" - assert F.RESULTS_DIR == Path("/root/results/F") - - -def test_results_dir_can_be_overridden_by_environment(monkeypatch, tmp_path): - monkeypatch.setenv("VSI_HARNESS_F_RESULTS_DIR", str(tmp_path / "F")) - reloaded = importlib.reload(F) - assert reloaded.RESULTS_DIR == tmp_path / "F" - monkeypatch.delenv("VSI_HARNESS_F_RESULTS_DIR") - importlib.reload(F) diff --git a/tests/test_F/test_launch.py b/tests/test_F/test_launch.py deleted file mode 100644 index 7b52d804e37f83c137001510c9f91533f86fb69b..0000000000000000000000000000000000000000 --- a/tests/test_F/test_launch.py +++ /dev/null @@ -1,7 +0,0 @@ -"""Tests for harness/F/launch.py.""" - -from harness.F import launch - - -def test_launch_entrypoint_exposes_run_main(): - assert callable(launch.main) diff --git a/tests/test_F/test_run.py b/tests/test_F/test_run.py deleted file mode 100644 index 5006cd1d37632566a05d4c9a39f5241af33670aa..0000000000000000000000000000000000000000 --- a/tests/test_F/test_run.py +++ /dev/null @@ -1,19 +0,0 @@ -from pathlib import Path -from harness import F -from harness.F import run - - -def test_results_default_under_root(): - assert F.RESULTS_DIR == Path("/root/results/F") - - -def test_perceived_layout_contains_every_input_axis(): - assert run.results_dir_for( - "perceived", "explicit", "metric", "tracking", "uniform", 32 - ) == Path("/root/results/F/perceived/metric/tracking/uniform/32/explicit") - - -def test_video_results_use_video_branch(): - assert run.results_dir_for( - "perceived", "explicit", "metric", "tracking", "video", None - ) == Path("/root/results/F/perceived/metric/tracking/video/explicit") diff --git a/tests/test_F/test_sweep.py b/tests/test_F/test_sweep.py deleted file mode 100644 index 95fa360e1106fe50593b284f19cb7a49ea42453e..0000000000000000000000000000000000000000 --- a/tests/test_F/test_sweep.py +++ /dev/null @@ -1,14 +0,0 @@ -"""Tests for harness/F/sweep.py -- CLI cartesian product wiring.""" - -import pytest - -from harness.F import sweep - - -def test_csv_expands_all_dedups_and_rejects_unknowns(): - assert sweep._csv("all", ("a", "b")) == ["a", "b"] - assert sweep._csv("b,a,b", ("a", "b")) == ["b", "a"] - with pytest.raises(ValueError, match="unknown values"): - sweep._csv("c", ("a", "b")) - - diff --git a/tests/test_analysis/__init__.py b/tests/test_analysis/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/tests/test_analysis/conftest.py b/tests/test_analysis/conftest.py deleted file mode 100644 index 126f811cb075cab9a44b8d2b97db54fafef16859..0000000000000000000000000000000000000000 --- a/tests/test_analysis/conftest.py +++ /dev/null @@ -1,118 +0,0 @@ -"""Shared fixtures and helpers for report-export tests.""" - -import json -import tempfile -import unittest -from pathlib import Path -from analysis.letters_reports import ( - analyze_modular, - export_reports, - load_profile as load, -) - - -def vlm(letter, qid=1, score=1.0, protocol="base", model="m", frames=32): - r = { - "model": model, - "protocol": protocol, - "condition": protocol, - "question_id": qid, - "scene": "s", - "dataset": "d", - "question_type": "count", - "score": score, - "frame_count": frames, - "input_token_count": 10, - "output_token_count": 2, - "generation_seconds": 1.0, - "answer_given": "x", - "full_prompt": "p", - } - if letter == "A": - r["frame_selection"] = "uniform" - elif letter in "BC": - r.update( - input_selection="uniform", - spatial_code_format="explicit", - depth="metric", - tracking="tracking", - ) - return r - - -def put(root, relative, record): - p = root / relative - p.parent.mkdir(parents=True, exist_ok=True) - p.write_text(json.dumps(record)) - return p - - -class ReportTestCase(unittest.TestCase): - def setUp(self): - self.temp = tempfile.TemporaryDirectory() - self.root = Path(self.temp.name) - - def tearDown(self): - self.temp.cleanup() - - def directory(self, letter, records): - d = self.root / letter - d.mkdir() - for i, r in enumerate(records): - put(d, f"{i}.json", r) - return d - - def symbolic(self, future=False): - d = self.root / ("F_future" if future else "F") - d.mkdir(exist_ok=True) - prefix = ( - "perceived/metric/tracking/uniform/32/explicit" - if future - else "metric/tracking/uniform/32/explicit" - ) - put( - d, - f"{prefix}/s/1.json", - { - "model": "symbolic", - "condition": "metric:tracking:uniform:32:explicit", - "question_id": 1, - "scene": "s", - "dataset": "d", - "question_type": "count", - "score": 1.0, - "spatial_code_format": "explicit", - "depth": "metric", - "tracking": "tracking", - "input": "uniform", - "number_of_frames": 32, - }, - ) - return d - - def ground_truth_symbolic(self): - d = self.root / "F" - d.mkdir() - put( - d, - "ground truth/explicit/s/1.json", - { - "model": "symbolic", - "condition": "ground truth:explicit", - "question_id": 1, - "scene": "s", - "dataset": "d", - "question_type": "count", - "score": 1.0, - "spatial_code_format": "explicit", - }, - ) - return d - - def analyze(self, letters, dirs, pairs=(), protocols=("base",)): - profiles = {l: load(l) for l in letters} - per, combined = analyze_modular( - {l: dirs[l] for l in letters}, profiles, protocols, pairs - ) - paths = export_reports(per, combined, self.root / "reports") - return per, combined, {p.name for p in paths} diff --git a/tests/test_analysis/test_A_reports.py b/tests/test_analysis/test_A_reports.py deleted file mode 100644 index 273c4f9218f4f0fffcdf8def6e636de9d36f881a..0000000000000000000000000000000000000000 --- a/tests/test_analysis/test_A_reports.py +++ /dev/null @@ -1,11 +0,0 @@ -from tests.test_analysis.conftest import ReportTestCase, vlm -from analysis import A_reports - - -class TestAReports(ReportTestCase): - def test_A_report_and_controlled_frame_comparison(self): - d = self.directory("A", [vlm("A", frames=32), vlm("A", frames=64)]) - result = A_reports.generate(d, ["base"], self.root / "reports") - self.assertEqual(result["path"].name, "A_report.json") - self.assertEqual(len(result["report"]["cells"]), 2) - self.assertEqual(len(result["report"]["within_harness_comparisons"]), 1) diff --git a/tests/test_analysis/test_B_reports.py b/tests/test_analysis/test_B_reports.py deleted file mode 100644 index 19a06743b73f83c7256b8a8c4c52da8057fe4f3b..0000000000000000000000000000000000000000 --- a/tests/test_analysis/test_B_reports.py +++ /dev/null @@ -1,11 +0,0 @@ -from tests.test_analysis.conftest import ReportTestCase, vlm -from analysis import B_reports - - -class TestBReports(ReportTestCase): - def test_B_report_contains_spatial_cell(self): - result = B_reports.generate( - self.directory("B", [vlm("B")]), ["base"], self.root / "reports" - ) - self.assertEqual(result["path"].name, "B_report.json") - self.assertEqual(len(result["report"]["cells"]), 1) diff --git a/tests/test_analysis/test_C_reports.py b/tests/test_analysis/test_C_reports.py deleted file mode 100644 index 35cf3f5c014ddd304f787e1bc09f4f4a1ea56977..0000000000000000000000000000000000000000 --- a/tests/test_analysis/test_C_reports.py +++ /dev/null @@ -1,11 +0,0 @@ -from tests.test_analysis.conftest import ReportTestCase, vlm -from analysis import C_reports - - -class TestCReports(ReportTestCase): - def test_C_report_is_exported(self): - result = C_reports.generate( - self.directory("C", [vlm("C")]), ["base"], self.root / "reports" - ) - self.assertEqual(result["path"].name, "C_report.json") - self.assertEqual(len(result["report"]["cells"]), 1) diff --git a/tests/test_analysis/test_D_reports.py b/tests/test_analysis/test_D_reports.py deleted file mode 100644 index 6fd57e3dadf66c863bee1cabf963e4c02b925dc1..0000000000000000000000000000000000000000 --- a/tests/test_analysis/test_D_reports.py +++ /dev/null @@ -1,13 +0,0 @@ -from tests.test_analysis.conftest import ReportTestCase, vlm -from analysis import D_reports - - -class TestDReports(ReportTestCase): - def test_D_report_is_ground_truth_code_report(self): - result = D_reports.generate( - self.directory("D", [vlm("D")]), ["base"], self.root / "reports" - ) - self.assertEqual(result["path"].name, "D_report.json") - self.assertEqual( - result["report"]["manifest"]["profile"]["input_source"], "ground_truth" - ) diff --git a/tests/test_analysis/test_F_reports.py b/tests/test_analysis/test_F_reports.py deleted file mode 100644 index 5862c066b0999e55501084a0d6b9710027a1a9b1..0000000000000000000000000000000000000000 --- a/tests/test_analysis/test_F_reports.py +++ /dev/null @@ -1,15 +0,0 @@ -from tests.test_analysis.conftest import ReportTestCase -from analysis import F_reports - - -class TestFReports(ReportTestCase): - def test_F_legacy_and_future_perceived_layouts(self): - for future in (False, True): - result = F_reports.generate( - self.symbolic(future), - (), - self.root / ("future" if future else "legacy"), - ) - self.assertEqual(result["path"].name, "F_report.json") - cell = next(iter(result["report"]["cells"].values())) - self.assertEqual(cell["identity"]["source"], "perceived") diff --git a/tests/test_analysis/test_analysis.py b/tests/test_analysis/test_analysis.py deleted file mode 100644 index 69c91bab64cb4e8d7e729b83ba33ba1b879c2d34..0000000000000000000000000000000000000000 --- a/tests/test_analysis/test_analysis.py +++ /dev/null @@ -1,12 +0,0 @@ -import json -from tests.test_analysis.conftest import ReportTestCase, vlm -from analysis.letters_reports import load_profile as load - - -class TestAnalysisDirectory(ReportTestCase): - def test_arbitrary_subset_exports_letter_and_combined_files(self): - dirs = {l: self.directory(l, [vlm(l)]) for l in "AC"} - _, _, names = self.analyze("AC", dirs) - self.assertEqual(names, {"A_report.json", "C_report.json", "AC_report.json"}) - for name in names: - json.loads((self.root / "reports" / name).read_text()) diff --git a/tests/test_analysis/test_letters_reports.py b/tests/test_analysis/test_letters_reports.py deleted file mode 100644 index 78f4bab503b285f3f5ae2a35815084e64f5eca81..0000000000000000000000000000000000000000 --- a/tests/test_analysis/test_letters_reports.py +++ /dev/null @@ -1,55 +0,0 @@ -from tests.test_analysis.conftest import ReportTestCase, vlm -from analysis import letters_reports - - -class TestLettersReports(ReportTestCase): - def test_arbitrary_subset_and_combined_name(self): - cells = {l: self.directory(l, [vlm(l)]) for l in "AC"} - result = letters_reports.generate( - cells, ["base"], output_dir=self.root / "reports" - ) - self.assertEqual( - {p.name for p in result["paths"]}, - {"A_report.json", "C_report.json", "AC_report.json"}, - ) - - def test_folded_statistical_and_solver_helpers(self): - self.assertEqual( - letters_reports.holm_bonferroni({"a": 0.01, "b": 0.04, "c": 0.03}), - {"a": 0.03, "c": 0.06, "b": 0.06}, - ) - a = [{"question_id": 1, "score": 1.0}, {"question_id": 2, "score": 0.0}] - b = [{"question_id": 1, "score": 1.0}, {"question_id": 2, "score": 1.0}] - overlap = letters_reports.solved_set_overlap({"A": a, "B": b}) - self.assertEqual(overlap["pairs"]["A|B"]["only_B"], 1) - vlm = [ - {"question_id": 1, "question_type": "count", "score": 0.0}, - {"question_id": 2, "question_type": "count", "score": 1.0}, - ] - solver = [{"question_id": 1, "score": 1.0}, {"question_id": 2, "score": 0.0}] - split = letters_reports.sufficiency_decomposition(vlm, solver) - self.assertEqual(split["certified"]["vlm_wrong"], 1) - - def test_pair_restriction(self): - cells = {l: self.directory(l, [vlm(l)]) for l in "ABC"} - result = letters_reports.generate( - cells, ["base"], ["A:B"], self.root / "reports" - ) - self.assertTrue( - all( - v["letters"] == ("A", "B") - for v in result["combined_report"]["cross_harness_comparisons"].values() - ) - ) - - def test_manifest_generated_at_is_deterministic_by_default(self): - cells = {"A": self.directory("A", [vlm("A")])} - first = letters_reports.generate(cells, ["base"], output_dir=self.root / "r1") - second = letters_reports.generate(cells, ["base"], output_dir=self.root / "r2") - self.assertEqual( - first["letter_reports"]["A"]["manifest"]["generated_at"], "reproducible" - ) - self.assertEqual( - first["letter_reports"]["A"]["manifest"], - second["letter_reports"]["A"]["manifest"], - ) diff --git a/tests/test_backup.py b/tests/test_backup.py deleted file mode 100644 index 36152265db767b88d0ecb87aefddab8a67007c6c..0000000000000000000000000000000000000000 --- a/tests/test_backup.py +++ /dev/null @@ -1,47 +0,0 @@ -"""Tests for backup.py -- target resolution and dry-run behavior without network.""" - -import pytest - -import backup - - -def test_resolve_targets_expands_all_without_uploading_unknowns(): - assert backup._resolve_targets("A") == ["A"] - assert backup._resolve_targets("all") == list(backup.TARGETS) - with pytest.raises(ValueError, match="unknown target"): - backup._resolve_targets("missing") - - -def test_local_paths_keep_results_under_results_host(monkeypatch, tmp_path): - workspace = tmp_path / "workspace" - host = tmp_path / "host" - monkeypatch.setattr(backup, "WORKSPACE_ROOT", workspace) - monkeypatch.setattr(backup, "RESULTS_HOST_ROOT", host) - - assert backup._local_path("results/A") == host / "results/A" - assert backup._local_path("harness") == workspace / "harness" - - -def test_backup_dry_run_skips_empty_targets_and_never_imports_hub( - monkeypatch, tmp_path, capsys -): - workspace = tmp_path / "workspace" - host = tmp_path / "host" - (workspace / "harness").mkdir(parents=True) - (workspace / "harness" / "run.py").write_text("# source\n") - monkeypatch.setattr(backup, "WORKSPACE_ROOT", workspace) - monkeypatch.setattr(backup, "RESULTS_HOST_ROOT", host) - monkeypatch.setattr(backup, "TARGETS", {"code": ["harness"], "A": ["results/A"]}) - - uploaded = backup.backup("owner/dataset", "all", dry_run=True) - - assert uploaded == ["code"] - output = capsys.readouterr().out - assert "[A] skipped" in output - assert "would upload" in output - assert str(workspace / "harness") in output - - -def test_target_root_rejects_mixed_workspace_and_results_roots(): - with pytest.raises(ValueError, match="mixes incompatible"): - backup._target_root(["results/A", "tests"]) diff --git a/tests/test_calibration/__init__.py b/tests/test_calibration/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/tests/test_calibration/conftest.py b/tests/test_calibration/conftest.py deleted file mode 100644 index 8a801f94b60da603c80287f186e31c5d32012e99..0000000000000000000000000000000000000000 --- a/tests/test_calibration/conftest.py +++ /dev/null @@ -1,12 +0,0 @@ -"""Shared import setup for this test package.""" - -from pathlib import Path -import sys - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - - -def pytest_configure(config): - config.option.importmode = "importlib" diff --git a/tests/test_calibration/test_calibration.py b/tests/test_calibration/test_calibration.py deleted file mode 100644 index 0f8fa86b6a7f93f7661ae8fb9965fda2e4ec4b44..0000000000000000000000000000000000000000 --- a/tests/test_calibration/test_calibration.py +++ /dev/null @@ -1,18 +0,0 @@ -"""Tests for calibration package configuration.""" - -import importlib -from pathlib import Path - -import calibration - - -def test_results_dir_defaults_to_root_results(): - assert calibration.RESULTS_DIR == Path("/root/results/calibration") - - -def test_results_dir_can_be_overridden_by_environment(monkeypatch, tmp_path): - monkeypatch.setenv("VSI_CALIBRATION_RESULTS_DIR", str(tmp_path / "calibration")) - reloaded = importlib.reload(calibration) - assert reloaded.RESULTS_DIR == tmp_path / "calibration" - monkeypatch.delenv("VSI_CALIBRATION_RESULTS_DIR") - importlib.reload(calibration) diff --git a/tests/test_calibration/test_report.py b/tests/test_calibration/test_report.py deleted file mode 100644 index 63f7a89adeb3de1a5691b4eca3a4f787486eb1ce..0000000000000000000000000000000000000000 --- a/tests/test_calibration/test_report.py +++ /dev/null @@ -1,140 +0,0 @@ -"""Tests for calibration/report.py -- budget stats and the recommendation rule.""" - -import json - -from calibration import report as calibration_report - - -def _record(question_id, score, forced=False, reasoning_tokens=100, seconds=1.0): - return { - "question_id": question_id, - "question_type": "object_counting", - "answer_expected": "4", - "metric": "MRA:.5:.95:.05", - "score": score, - "forced": forced, - "reasoning_token_count": reasoning_tokens, - "generation_seconds": seconds, - } - - -def test_cell_stats_counts_forced_and_natural_lengths(): - stats = calibration_report.cell_stats( - [ - _record(1, 1.0, forced=False, reasoning_tokens=50), - _record(2, 0.0, forced=True, reasoning_tokens=512), - ] - ) - assert stats["count"] == 2 - assert stats["forced_rate"] == 0.5 - # Forced records are excluded from the natural-stop length mean. - assert stats["natural_reasoning_tokens_mean"] == 50 - - -def test_report_scores_only_the_shared_question_intersection(): - grid = { - "m": { - 256: {1: _record(1, 0.0), 2: _record(2, 1.0)}, - 512: {1: _record(1, 1.0)}, # never answered q2 - } - } - result = calibration_report.report(grid) - assert result["m"]["questions"] == 1 - assert result["m"]["budgets"][256]["count"] == 1 - - -def test_recommendation_picks_smallest_saturated_low_forced_budget(): - grid = { - "m": { - 256: {1: _record(1, 0.0, forced=True)}, - 512: {1: _record(1, 1.0, forced=False)}, - 2048: {1: _record(1, 1.0, forced=False)}, - } - } - result = calibration_report.report(grid, tolerance=1.0, max_forced_rate=0.15) - assert result["m"]["recommended"] == 512 - - -def test_recommendation_rejects_high_forced_rate_even_at_best_accuracy(): - grid = { - "m": { - 256: {1: _record(1, 1.0, forced=True)}, # accurate but 100% forced - 1024: {1: _record(1, 1.0, forced=False)}, - } - } - result = calibration_report.report(grid, max_forced_rate=0.15) - assert result["m"]["recommended"] == 1024 - - -def test_load_grid_reads_the_full_config_layout(tmp_path): - cell = ( - tmp_path - / "qwen3.5-2b" - / "explicit" - / "metric" - / "tracking" - / "selective" - / "64" - / "512" - / "scene_a" - ) - cell.mkdir(parents=True) - (cell / "7.json").write_text(json.dumps(_record(7, 1.0))) - grid = calibration_report.load_grid(tmp_path) - assert grid == { - "qwen3.5-2b/explicit/metric/tracking/selective/64": { - "512": {7: json.loads((cell / "7.json").read_text())} - } - } - - -def test_load_grid_does_not_mistake_frame_count_dirs_for_budgets(tmp_path): - # The "64" frame-count level is numeric too -- only the budget leaf (whose - # children are scene folders with JSONs) may be treated as a budget. - cell = ( - tmp_path - / "qwen3.5-2b" - / "explicit" - / "metric" - / "tracking" - / "selective" - / "64" - / "512" - / "scene_a" - ) - cell.mkdir(parents=True) - (cell / "7.json").write_text(json.dumps(_record(7, 1.0))) - grid = calibration_report.load_grid(tmp_path) - assert list(grid) == ["qwen3.5-2b/explicit/metric/tracking/selective/64"] - assert list(grid["qwen3.5-2b/explicit/metric/tracking/selective/64"]) == ["512"] - - -def test_load_grid_includes_variant_budget_directories(tmp_path): - cell = ( - tmp_path - / "qwen3.5-2b" - / "explicit" - / "metric" - / "tracking" - / "selective" - / "64" - / "512-prose-legend" - / "scene_a" - ) - cell.mkdir(parents=True) - (cell / "7.json").write_text(json.dumps(_record(7, 1.0))) - grid = calibration_report.load_grid(tmp_path) - assert list(grid["qwen3.5-2b/explicit/metric/tracking/selective/64"]) == [ - "512-prose-legend" - ] - - -def test_variant_rows_are_never_recommended(): - grid = { - "m": { - "512": {1: _record(1, 0.5)}, - "512-prose-legend": {1: _record(1, 1.0)}, - } - } - result = calibration_report.report(grid) - assert result["m"]["recommended"] == "512" diff --git a/tests/test_calibration/test_run.py b/tests/test_calibration/test_run.py deleted file mode 100644 index 66087deeeb524fc8d8e1a2d80577eaae36ab2d73..0000000000000000000000000000000000000000 --- a/tests/test_calibration/test_run.py +++ /dev/null @@ -1,130 +0,0 @@ -"""Tests for calibration/run.py -- operator-specified budget-grid orchestration.""" - -import pytest - -from calibration import run as calibration_run - - -def test_results_dir_isolates_every_pilot_axis(): - base = ("qwen3.5-4b", "explicit", "metric", "tracking", "selective", 32, 512) - variants = {calibration_run.results_dir_for(*base)} - for index, value in [ - (0, "qwen3.5-2b"), - (1, "compact"), - (2, "relative"), - (3, "no tracking"), - (4, "uniform"), - (5, 64), - (6, 1024), - ]: - changed = list(base) - changed[index] = value - variants.add(calibration_run.results_dir_for(*changed)) - assert len(variants) == 8 - - -def test_build_plan_orders_cheapest_budget_first(): - plan = calibration_run.build_plan(["m1", "m2"], [2048, 256]) - assert plan == [("m1", 256), ("m2", 256), ("m1", 2048), ("m2", 2048)] - - -def test_scenes_for_derives_scenes_and_rejects_unknown_ids(monkeypatch): - rows = [ - {"id": 1, "scene_name": "scene_a"}, - {"id": 2, "scene_name": "scene_b"}, - {"id": 3, "scene_name": "scene_a"}, - ] - monkeypatch.setattr(calibration_run, "load_questions", lambda: list(rows)) - assert calibration_run.scenes_for({1, 2, 3}) == ["scene_a", "scene_b"] - with pytest.raises(ValueError): - calibration_run.scenes_for({1, 999}) - - -def test_run_grid_passes_budget_questions_and_isolated_dir(monkeypatch): - launched = [] - monkeypatch.setattr(calibration_run, "scenes_for", lambda ids: ["scene_a"]) - monkeypatch.setattr( - calibration_run.harness_b_launch, - "launch", - lambda model, fmt, sel, frames, scenes, **kwargs: launched.append( - ( - model, - fmt, - kwargs["reasoning_budget"], - str(kwargs["results_dir"]), - kwargs["question_ids"], - scenes, - ) - ), - ) - calibration_run.run_grid( - ["qwen3.5-2b"], - [256, 512], - [1, 2], - "compact", - "metric", - "tracking", - "selective", - 64, - ) - assert [(m, f, b) for m, f, b, _, _, _ in launched] == [ - ("qwen3.5-2b", "compact", 256), - ("qwen3.5-2b", "compact", 512), - ] - assert launched[0][3] != launched[1][3] - assert launched[0][4] == {1, 2} - assert launched[0][5] == ["scene_a"] - - -def test_cli_requires_exactly_one_question_source(monkeypatch, capsys): - monkeypatch.setattr( - "sys.argv", - [ - "run", - "--models", - "qwen3.5-2b", - "--budgets", - "256", - "--spatial-code-format", - "explicit", - "--depth", - "metric", - "--tracking", - "tracking", - "--input-selection", - "selective", - "--frames", - "32", - ], - ) - with pytest.raises(SystemExit): - calibration_run.main() - assert "exactly one of" in capsys.readouterr().err - - -def test_cli_rejects_nonpositive_budget(monkeypatch, capsys): - monkeypatch.setattr( - "sys.argv", - [ - "run", - "--models", - "qwen3.5-2b", - "--budgets", - "0", - "--questions", - "1", - "--spatial-code-format", - "explicit", - "--depth", - "metric", - "--tracking", - "tracking", - "--input-selection", - "selective", - "--frames", - "32", - ], - ) - with pytest.raises(SystemExit): - calibration_run.main() - assert "must be positive" in capsys.readouterr().err diff --git a/tests/test_corruption/__init__.py b/tests/test_corruption/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/tests/test_corruption/conftest.py b/tests/test_corruption/conftest.py deleted file mode 100644 index 8a801f94b60da603c80287f186e31c5d32012e99..0000000000000000000000000000000000000000 --- a/tests/test_corruption/conftest.py +++ /dev/null @@ -1,12 +0,0 @@ -"""Shared import setup for this test package.""" - -from pathlib import Path -import sys - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - - -def pytest_configure(config): - config.option.importmode = "importlib" diff --git a/tests/test_corruption/test_chimera.py b/tests/test_corruption/test_chimera.py deleted file mode 100644 index 6cab03969a07548dd79096173bc70a44cc6128f0..0000000000000000000000000000000000000000 --- a/tests/test_corruption/test_chimera.py +++ /dev/null @@ -1,96 +0,0 @@ -"""Tests for corruption/chimera.py -- hybrid codes and the single-object probe.""" - -import random - -from corruption import chimera - - -def _instance(x, y, dims=(1.0, 1.0, 1.0), time=0.0): - return { - "3D oriented bounding box": { - "3D oriented bounding box center coordinates": [x, y, 0.5], - "3D oriented bounding box dimensions": list(dims), - "3D oriented bounding box orientation unit vectors": [ - [1.0, 0.0, 0.0], - [0.0, 0.0, 1.0], - [0.0, -1.0, 0.0], - ], - }, - "first visible time": time, - } - - -def _code(objects): - return { - "spatial code schema": {}, - "objects": objects, - "room": {"floor boundary polygons": []}, - } - - -def test_gt_inventory_keeps_gt_counts_but_takes_perceived_boxes(): - gt = _code({"chair": [_instance(0.0, 0.0), _instance(5.0, 5.0)]}) - perceived = _code({"chair": [_instance(0.3, 0.1, dims=(9.0, 9.0, 9.0))]}) - hybrid, coverage = chimera.gt_inventory_perceived_geometry(gt, perceived) - # GT count preserved (2 chairs), nearest GT instance got the perceived box. - assert len(hybrid["objects"]["chair"]) == 2 - assert coverage == {"instances": 2, "swapped": 1} - boxes = [ - item["3D oriented bounding box"]["3D oriented bounding box dimensions"] - for item in hybrid["objects"]["chair"] - ] - assert [9.0, 9.0, 9.0] in boxes - - -def test_perceived_inventory_keeps_perceived_counts_but_takes_gt_boxes(): - gt = _code({"chair": [_instance(0.0, 0.0, dims=(2.0, 2.0, 2.0))]}) - perceived = _code( - { - "chair": [_instance(0.4, 0.0), _instance(8.0, 8.0)], - "ghost": [_instance(1.0, 1.0)], - } - ) - hybrid, coverage = chimera.perceived_inventory_gt_geometry(gt, perceived) - # Perceived inventory preserved: 2 chairs + the hallucinated "ghost" class. - assert len(hybrid["objects"]["chair"]) == 2 - assert "ghost" in hybrid["objects"] - assert coverage["swapped"] == 1 # only one GT chair box available to give out - boxes = [ - item["3D oriented bounding box"]["3D oriented bounding box dimensions"] - for item in hybrid["objects"]["chair"] - ] - assert [2.0, 2.0, 2.0] in boxes - - -def test_chimeras_do_not_mutate_inputs(): - gt = _code({"chair": [_instance(0.0, 0.0)]}) - perceived = _code({"chair": [_instance(1.0, 1.0)]}) - frozen_gt, frozen_perceived = str(gt), str(perceived) - chimera.gt_inventory_perceived_geometry(gt, perceived) - chimera.perceived_inventory_gt_geometry(gt, perceived) - assert str(gt) == frozen_gt - assert str(perceived) == frozen_perceived - - -def test_perturb_single_object_changes_exactly_one_instance(): - code = _code( - { - "chair": [_instance(0.0, 0.0), _instance(5.0, 5.0)], - "table": [_instance(2.0, 2.0)], - } - ) - out, info = chimera.perturb_single_object(code, random.Random(0)) - changed = 0 - for name in code["objects"]: - for before, after in zip(code["objects"][name], out["objects"][name]): - if before != after: - changed += 1 - assert changed == 1 - assert info["class"] in code["objects"] - - -def test_perturb_single_object_empty_code_is_a_noop(): - code = _code({}) - out, info = chimera.perturb_single_object(code, random.Random(0)) - assert out == code - assert info is None diff --git a/tests/test_corruption/test_corruption.py b/tests/test_corruption/test_corruption.py deleted file mode 100644 index 55573a76f5e670440ec7182c5b89deb5af998d94..0000000000000000000000000000000000000000 --- a/tests/test_corruption/test_corruption.py +++ /dev/null @@ -1,19 +0,0 @@ -"""Tests for corruption package configuration.""" - -import importlib -from pathlib import Path - -import corruption - - -def test_corruption_defaults_are_explicit(): - assert corruption.RESULTS_DIR == Path("/root/results/corruption") - assert corruption.SAMPLE_SEED == 20260725 - - -def test_results_dir_can_be_overridden_by_environment(monkeypatch, tmp_path): - monkeypatch.setenv("VSI_CORRUPTION_RESULTS_DIR", str(tmp_path / "corruption")) - reloaded = importlib.reload(corruption) - assert reloaded.RESULTS_DIR == tmp_path / "corruption" - monkeypatch.delenv("VSI_CORRUPTION_RESULTS_DIR") - importlib.reload(corruption) diff --git a/tests/test_corruption/test_empirical.py b/tests/test_corruption/test_empirical.py deleted file mode 100644 index b8526352da1210c304cd6ba81a358790f115441f..0000000000000000000000000000000000000000 --- a/tests/test_corruption/test_empirical.py +++ /dev/null @@ -1,96 +0,0 @@ -"""Tests for corruption/empirical.py -- measured residuals and empirical noise.""" - -import random - -from corruption import empirical - - -def _instance(x, y, dims=(1.0, 1.0, 1.0)): - return { - "3D oriented bounding box": { - "3D oriented bounding box center coordinates": [x, y, 0.5], - "3D oriented bounding box dimensions": list(dims), - "3D oriented bounding box orientation unit vectors": [ - [1.0, 0.0, 0.0], - [0.0, 0.0, 1.0], - [0.0, -1.0, 0.0], - ], - }, - "first visible time": 0.0, - } - - -def _code(objects): - return { - "spatial code schema": {}, - "objects": objects, - "room": {"floor boundary polygons": []}, - } - - -def test_measure_residuals_matches_missed_and_hallucinated(): - gt = _code({"chair": [_instance(0.0, 0.0), _instance(5.0, 5.0)]}) - perceived = _code( - {"chair": [_instance(0.5, 0.0)], "phantom": [_instance(9.0, 9.0)]} - ) - residuals = empirical.measure_residuals([(perceived, gt)]) - assert residuals["matched"] == 1 - assert residuals["missed"] == 1 # second GT chair unmatched - assert residuals["hallucinated"] == 1 # the phantom class - assert residuals["miss_rate"] == 0.5 - assert residuals["position_residuals"] == [[0.5, 0.0, 0.0]] - - -def test_measure_residuals_dimension_ratios(): - gt = _code({"chair": [_instance(0.0, 0.0, dims=(2.0, 2.0, 2.0))]}) - perceived = _code({"chair": [_instance(0.0, 0.0, dims=(1.0, 3.0, 2.0))]}) - residuals = empirical.measure_residuals([(perceived, gt)]) - assert residuals["dimension_ratios"] == [[0.5, 1.5, 1.0]] - - -def test_empirical_noise_at_zero_scale_is_identity(): - code = _code({"chair": [_instance(1.0, 1.0)]}) - residuals = { - "position_residuals": [[0.5, 0.5, 0.0]], - "dimension_ratios": [[2.0, 2.0, 2.0]], - "matched": 1, - "missed": 1, - "hallucinated": 1, - "miss_rate": 0.5, - "hallucination_rate": 0.5, - } - out = empirical.empirical_noise(code, residuals, random.Random(0), scale=0.0) - assert out == code - - -def test_empirical_noise_applies_sampled_residuals(): - code = _code({"chair": [_instance(1.0, 1.0)]}) - residuals = { - "position_residuals": [[0.5, -0.5, 0.0]], - "dimension_ratios": [[2.0, 1.0, 1.0]], - "matched": 1, - "missed": 0, - "hallucinated": 0, - "miss_rate": 0.0, - "hallucination_rate": 0.0, - } - out = empirical.empirical_noise(code, residuals, random.Random(0), scale=1.0) - box = out["objects"]["chair"][0]["3D oriented bounding box"] - assert box["3D oriented bounding box center coordinates"] == [1.5, 0.5, 0.5] - assert box["3D oriented bounding box dimensions"] == [2.0, 1.0, 1.0] - - -def test_empirical_noise_is_reproducible(): - code = _code({"chair": [_instance(1.0, 1.0), _instance(3.0, 3.0)]}) - residuals = { - "position_residuals": [[0.5, 0.0, 0.0], [-0.2, 0.1, 0.0]], - "dimension_ratios": [[1.1, 0.9, 1.0]], - "matched": 2, - "missed": 1, - "hallucinated": 1, - "miss_rate": 0.3, - "hallucination_rate": 0.3, - } - first = empirical.empirical_noise(code, residuals, random.Random(7)) - second = empirical.empirical_noise(code, residuals, random.Random(7)) - assert first == second diff --git a/tests/test_corruption/test_launch.py b/tests/test_corruption/test_launch.py deleted file mode 100644 index 4bba8040e41bf38050f554ac2db568b814715e9d..0000000000000000000000000000000000000000 --- a/tests/test_corruption/test_launch.py +++ /dev/null @@ -1,68 +0,0 @@ -"""Tests for corruption/launch.py -- grid looping over conditions.""" - -import pytest - -from corruption import launch - - -def test_launch_imports(): - assert callable(launch.main) - - -def test_launch_rejects_unknown_transform(monkeypatch, capsys): - monkeypatch.setattr( - "sys.argv", - [ - "launch", - "--transforms", - "not-a-transform", - "--magnitudes", - "0.5", - "--arm", - "solver", - ], - ) - with pytest.raises(SystemExit): - launch.main() - assert "unknown transform" in capsys.readouterr().err - - -def test_launch_vlm_arm_requires_models(monkeypatch, capsys): - monkeypatch.setattr( - "sys.argv", - ["launch", "--transforms", "translate", "--magnitudes", "10", "--arm", "vlm"], - ) - with pytest.raises(SystemExit): - launch.main() - assert "requires --models" in capsys.readouterr().err - - -def test_launch_runs_the_full_grid_through_run_solver(monkeypatch): - conditions = [] - monkeypatch.setattr( - launch, - "run_solver", - lambda transform, magnitude, fmt, **kwargs: conditions.append( - (transform, magnitude) - ) - or [], - ) - monkeypatch.setattr( - "sys.argv", - [ - "launch", - "--arm", - "solver", - "--transforms", - "translate,rotate-z", - "--magnitudes", - "10,90", - ], - ) - launch.main() - assert conditions == [ - ("translate", 10.0), - ("translate", 90.0), - ("rotate-z", 10.0), - ("rotate-z", 90.0), - ] diff --git a/tests/test_corruption/test_run.py b/tests/test_corruption/test_run.py deleted file mode 100644 index cefe176074934ca4f277145341195a5536504835..0000000000000000000000000000000000000000 --- a/tests/test_corruption/test_run.py +++ /dev/null @@ -1,220 +0,0 @@ -"""Tests for corruption/run.py -- condition orchestration, determinism, and certification.""" - -import copy - -import pytest - -from corruption import run as corruption_run -from encoder.geometric import _explicit_from_compact - -_SCENE = "13c3e046d7" -_OTHER_SCENE = "09c1414f1b" - - -def _box(x, y, z=0.5, dims=(1.0, 1.0, 1.0)): - return { - "3D oriented bounding box center coordinates": [x, y, z], - "3D oriented bounding box dimensions": list(dims), - "3D oriented bounding box orientation unit vectors": [ - [1.0, 0.0, 0.0], - [0.0, 1.0, 0.0], - [0.0, 0.0, 1.0], - ], - } - - -def _compact(offset=0.0): - return { - "spatial code schema": {}, - "objects": { - "chair": [ - { - "3D oriented bounding box": _box(offset, 0.0), - "first visible time": 0.0, - } - ], - "table": [ - { - "3D oriented bounding box": _box(offset + 3.0, 0.0), - "first visible time": 1.0, - } - ], - }, - "room": { - "floor boundary polygons": [ - { - "outer boundary coordinates": [ - [-2.0, -2.0], - [5.0, -2.0], - [5.0, 2.0], - [-2.0, 2.0], - ], - "interior hole boundary coordinates": [], - } - ] - }, - } - - -@pytest.fixture(autouse=True) -def self_contained_ground_truth(monkeypatch): - codes = {_SCENE: _compact(), _OTHER_SCENE: _compact(offset=10.0)} - - def load_compact(scene): - return copy.deepcopy(codes[scene]) - - def load_spatial_code(scene, spatial_code_format): - compact = load_compact(scene) - if spatial_code_format == "compact": - return compact, f"/fixture/{scene}.json" - if spatial_code_format == "explicit": - explicit, _floor_area = _explicit_from_compact(compact) - return explicit, f"/fixture/{scene}.json" - raise ValueError(spatial_code_format) - - monkeypatch.setattr(corruption_run, "load_ground_truth_compact", load_compact) - monkeypatch.setattr( - corruption_run.gt_spatial_codes, "load_spatial_code", load_spatial_code - ) - - -def test_seed_is_deterministic_and_condition_specific(): - first = corruption_run._seed_for(_SCENE, "position-jitter", 0.25) - second = corruption_run._seed_for(_SCENE, "position-jitter", 0.25) - different = corruption_run._seed_for(_SCENE, "position-jitter", 0.5) - assert first == second - assert first != different - - -def test_corrupted_code_is_reproducible(): - first = corruption_run.corrupted_code(_SCENE, "position-jitter", 0.25, "compact") - second = corruption_run.corrupted_code(_SCENE, "position-jitter", 0.25, "compact") - assert first == second - - -def test_corrupted_explicit_is_derived_from_the_corrupted_compact(): - compact = corruption_run.corrupted_code(_SCENE, "position-jitter", 0.25, "compact") - explicit = corruption_run.corrupted_code( - _SCENE, "position-jitter", 0.25, "explicit" - ) - # Same corruption seed -> the explicit code's per-class counts must match the - # corrupted compact's own instance counts (consistency-by-construction). - for class_name, items in compact["objects"].items(): - assert explicit["objects"][class_name]["count"] == len(items) - - -def test_wrong_scene_returns_the_substitute_scenes_code(): - substituted = corruption_run.corrupted_code( - _SCENE, "wrong-scene", 0, "compact", wrong_scene=_OTHER_SCENE - ) - own = corruption_run.load_ground_truth_compact(_SCENE) - other = corruption_run.load_ground_truth_compact(_OTHER_SCENE) - assert substituted == other - assert substituted != own - - -def test_wrong_scene_requires_a_substitute(): - with pytest.raises(ValueError): - corruption_run.corrupted_code(_SCENE, "wrong-scene", 0, "compact") - - -def test_chimera_requires_perceived_config(): - with pytest.raises(ValueError): - corruption_run.corrupted_code(_SCENE, "chimera-gt-inventory", 0, "compact") - - -def test_empirical_requires_residuals(): - with pytest.raises(ValueError): - corruption_run.corrupted_code(_SCENE, "empirical", 1.0, "compact") - - -def test_unknown_transform_rejected(): - with pytest.raises(ValueError): - corruption_run.corrupted_code(_SCENE, "not-a-transform", 1.0, "compact") - - -def test_results_dir_for_isolates_every_axis(): - a = corruption_run.results_dir_for("vlm", "position-jitter", 0.25, "qwen3.5-4b") - b = corruption_run.results_dir_for("vlm", "position-jitter", 0.5, "qwen3.5-4b") - c = corruption_run.results_dir_for("solver", "position-jitter", 0.25, "symbolic") - assert len({a, b, c}) == 3 - - -def test_certify_rejects_non_invariance_transforms(): - with pytest.raises(ValueError): - corruption_run.certify_invariant(_SCENE, "position-jitter", 0.25) - - -def test_certify_translate_passes_on_a_real_scene(): - assert corruption_run.certify_invariant(_SCENE, "translate", 10.0) is True - - -def test_run_solver_answers_and_writes_records(tmp_path): - results = corruption_run.run_solver( - "position-jitter", 0.0, scenes=[_SCENE], results_dir=tmp_path - ) - assert results - for record in results: - assert record["model"] == "symbolic" - assert record["transform"] == "position-jitter" - assert record["scene"] == _SCENE - assert (tmp_path / _SCENE / f"{record['question_id']}.json").is_file() - - -def test_run_solver_zero_magnitude_jitter_matches_clean_ground_truth(): - # position-jitter at 0.0 is geometrically the identity, so the solver must score - # exactly what it scores on the clean ground-truth code. - from harness.D import symbolic_eval - - corrupted = corruption_run.run_solver( - "position-jitter", 0.0, scenes=[_SCENE], write_results=False - ) - clean = symbolic_eval.run( - spatial_code_format="explicit", scene=_SCENE, write_results=False - ) - corrupted_scores = {r["question_id"]: r["score"] for r in corrupted} - clean_scores = {r["question_id"]: r["score"] for r in clean} - assert corrupted_scores == clean_scores - - -def test_run_solver_respects_the_question_sample(tmp_path): - all_results = corruption_run.run_solver( - "position-jitter", 0.0, scenes=[_SCENE], write_results=False - ) - keep = {all_results[0]["question_id"]} - sampled = corruption_run.run_solver( - "position-jitter", 0.0, scenes=[_SCENE], question_ids=keep, write_results=False - ) - assert [r["question_id"] for r in sampled] == list(keep) - - -def test_make_code_transform_ignores_the_loaded_code(): - hook = corruption_run.make_code_transform("position-jitter", 0.25) - out = hook({"not": "used"}, _SCENE, "compact") - assert out == corruption_run.corrupted_code( - _SCENE, "position-jitter", 0.25, "compact" - ) - - -def test_single_object_info_is_deterministic_and_recomputable(): - first = corruption_run.single_object_info(_SCENE, 0) - second = corruption_run.single_object_info(_SCENE, 0) - assert first == second - assert "class" in first and "instance" in first - - -def test_single_object_solver_run_writes_perturbation_sidecar(tmp_path): - corruption_run.run_solver("single-object", 0, scenes=[_SCENE], results_dir=tmp_path) - sidecar = tmp_path / _SCENE / "_perturbation.json" - assert sidecar.is_file() - import json - - info = json.loads(sidecar.read_text()) - assert info == corruption_run.single_object_info(_SCENE, 0) - - -def test_non_probe_runs_write_no_sidecar(tmp_path): - corruption_run.run_solver( - "position-jitter", 0.0, scenes=[_SCENE], results_dir=tmp_path - ) - assert not (tmp_path / _SCENE / "_perturbation.json").exists() diff --git a/tests/test_corruption/test_sample.py b/tests/test_corruption/test_sample.py deleted file mode 100644 index 848798e3df29196319e8c19c86cf3a856165ca0a..0000000000000000000000000000000000000000 --- a/tests/test_corruption/test_sample.py +++ /dev/null @@ -1,72 +0,0 @@ -"""Tests for corruption/sample.py -- the pre-registered question sampler.""" - -from corruption import sample as corruption_sample - - -def _rows(monkeypatch, rows): - monkeypatch.setattr(corruption_sample, "load_questions", lambda: list(rows)) - - -def test_budget_key_pools_direction_subtypes(): - assert ( - corruption_sample._budget_key("object_rel_direction_easy") - == "object_rel_direction" - ) - assert ( - corruption_sample._budget_key("object_rel_direction_hard") - == "object_rel_direction" - ) - assert corruption_sample._budget_key("object_counting") == "object_counting" - - -def test_draw_sample_is_deterministic_for_the_frozen_seed(monkeypatch): - rows = [ - {"id": i, "scene_name": f"scene{i % 5}", "question_type": "object_counting"} - for i in range(50) - ] - _rows(monkeypatch, rows) - scenes = {f"scene{i}" for i in range(5)} - first = corruption_sample.draw_sample(scenes, budgets={"object_counting": 10}) - second = corruption_sample.draw_sample(scenes, budgets={"object_counting": 10}) - assert first == second - assert len(first) == 10 - - -def test_draw_sample_spreads_across_scenes_round_robin(monkeypatch): - # 5 scenes x 10 questions each; a 5-question budget must touch 5 DISTINCT scenes. - rows = [ - { - "id": scene * 100 + i, - "scene_name": f"scene{scene}", - "question_type": "object_counting", - } - for scene in range(5) - for i in range(10) - ] - _rows(monkeypatch, rows) - scenes = {f"scene{i}" for i in range(5)} - sampled = corruption_sample.draw_sample(scenes, budgets={"object_counting": 5}) - assert len({qid // 100 for qid in sampled}) == 5 - - -def test_draw_sample_excludes_unlisted_categories_and_scenes(monkeypatch): - rows = [ - {"id": 1, "scene_name": "scene_in", "question_type": "object_counting"}, - {"id": 2, "scene_name": "scene_in", "question_type": "obj_appearance_order"}, - {"id": 3, "scene_name": "scene_out", "question_type": "object_counting"}, - ] - _rows(monkeypatch, rows) - sampled = corruption_sample.draw_sample( - {"scene_in"}, budgets={"object_counting": 10} - ) - assert sampled == [1] - - -def test_draw_sample_budget_caps_the_draw(monkeypatch): - rows = [ - {"id": i, "scene_name": "scene0", "question_type": "object_counting"} - for i in range(100) - ] - _rows(monkeypatch, rows) - sampled = corruption_sample.draw_sample({"scene0"}, budgets={"object_counting": 7}) - assert len(sampled) == 7 diff --git a/tests/test_corruption/test_transforms.py b/tests/test_corruption/test_transforms.py deleted file mode 100644 index 6c9a0280d77967bf4b6f72d835160b1fc9c07650..0000000000000000000000000000000000000000 --- a/tests/test_corruption/test_transforms.py +++ /dev/null @@ -1,178 +0,0 @@ -"""Tests for corruption/transforms.py -- noise and invariance transform families.""" - -import math -import random - -from corruption import transforms - - -def _compact(classes=("chair", "table"), instances_per_class=2): - objects = {} - for class_index, name in enumerate(classes): - items = [] - for index in range(instances_per_class): - items.append( - { - "3D oriented bounding box": { - "3D oriented bounding box center coordinates": [ - float(class_index), - float(index), - 0.5, - ], - "3D oriented bounding box dimensions": [1.0, 2.0, 0.5], - "3D oriented bounding box orientation unit vectors": [ - [1.0, 0.0, 0.0], - [0.0, 0.0, 1.0], - [0.0, -1.0, 0.0], - ], - }, - "first visible time": float(index), - } - ) - objects[name] = items - return { - "spatial code schema": {}, - "objects": objects, - "room": { - "floor boundary polygons": [ - { - "outer boundary coordinates": [ - [0.0, 0.0], - [4.0, 0.0], - [4.0, 4.0], - [0.0, 4.0], - ] - } - ] - }, - } - - -def test_transforms_never_mutate_the_input(): - code = _compact() - frozen = str(code) - for name, transform in transforms.TRANSFORMS.items(): - transform(code, 0.5, random.Random(0)) - assert str(code) == frozen, f"{name} mutated its input" - - -def test_position_jitter_moves_centers_and_nothing_else(): - code = _compact() - out = transforms.position_jitter(code, 0.5, random.Random(0)) - before = code["objects"]["chair"][0]["3D oriented bounding box"] - after = out["objects"]["chair"][0]["3D oriented bounding box"] - assert before["3D oriented bounding box center coordinates"] != ( - after["3D oriented bounding box center coordinates"] - ) - assert before["3D oriented bounding box dimensions"] == ( - after["3D oriented bounding box dimensions"] - ) - - -def test_position_jitter_zero_sigma_is_identity_geometry(): - code = _compact() - out = transforms.position_jitter(code, 0.0, random.Random(0)) - assert out == code - - -def test_dimension_noise_never_collapses_a_dimension(): - code = _compact() - out = transforms.dimension_noise(code, 5.0, random.Random(0)) - for _name, instance in transforms._instances(out): - for value in instance["3D oriented bounding box"][ - "3D oriented bounding box dimensions" - ]: - assert value > 0.0 - - -def test_drop_objects_removes_emptied_classes_entirely(): - code = _compact() - out = transforms.drop_objects(code, 1.0, random.Random(0)) - assert out["objects"] == {} - - -def test_drop_objects_zero_fraction_drops_nothing(): - code = _compact() - out = transforms.drop_objects(code, 0.0, random.Random(0)) - assert out == code - - -def test_hallucinate_objects_only_ever_adds(): - code = _compact() - out = transforms.hallucinate_objects(code, 1.0, random.Random(0)) - for name in code["objects"]: - assert len(out["objects"][name]) == 2 * len(code["objects"][name]) - - -def test_class_swap_keeps_geometry_but_relabels(): - code = _compact() - out = transforms.class_swap(code, 1.0, random.Random(0)) - # Same set of class names, same total geometry, but at least one class's items moved. - assert sorted(out["objects"]) == sorted(code["objects"]) - assert any( - out["objects"][name] != code["objects"][name] for name in code["objects"] - ) - - -def test_translate_shifts_centers_and_polygons_together(): - code = _compact() - out = transforms.translate(code, 10.0) - center = out["objects"]["chair"][0]["3D oriented bounding box"][ - "3D oriented bounding box center coordinates" - ] - assert center[:2] == [10.0, 10.0] - assert center[2] == 0.5 # height untouched - assert out["room"]["floor boundary polygons"][0]["outer boundary coordinates"][ - 0 - ] == [10.0, 10.0] - - -def test_rotate_z_preserves_pairwise_distances(): - code = _compact() - out = transforms.rotate_z(code, 90.0) - - def centers(c): - return [ - instance["3D oriented bounding box"][ - "3D oriented bounding box center coordinates" - ] - for _name, instance in transforms._instances(c) - ] - - before, after = centers(code), centers(out) - for i in range(len(before)): - for j in range(i + 1, len(before)): - assert ( - math.dist(before[i], before[j]) - == round(math.dist(after[i], after[j]), 10) - or abs(math.dist(before[i], before[j]) - math.dist(after[i], after[j])) - < 0.05 - ) - - -def test_reorder_changes_only_order(): - code = _compact(classes=("a", "b", "c", "d")) - out = transforms.reorder(code, None, random.Random(3)) - assert sorted(out["objects"]) == sorted(code["objects"]) - for name in code["objects"]: - assert sorted(map(str, out["objects"][name])) == sorted( - map(str, code["objects"][name]) - ) - - -def test_round_precision_rounds_every_geometry_value(): - code = _compact() - code["objects"]["chair"][0]["3D oriented bounding box"][ - "3D oriented bounding box center coordinates" - ] = [0.123456, 1.987654, 0.5] - out = transforms.round_precision(code, 1) - assert out["objects"]["chair"][0]["3D oriented bounding box"][ - "3D oriented bounding box center coordinates" - ] == [0.1, 2.0, 0.5] - - -def test_seeded_transforms_are_reproducible(): - code = _compact() - first = transforms.position_jitter(code, 0.3, random.Random(42)) - second = transforms.position_jitter(code, 0.3, random.Random(42)) - assert first == second diff --git a/tests/test_encoder/conftest.py b/tests/test_encoder/conftest.py deleted file mode 100644 index a77755f02a82953721899262a97085395ba8e213..0000000000000000000000000000000000000000 --- a/tests/test_encoder/conftest.py +++ /dev/null @@ -1,13 +0,0 @@ -"""Shared import setup for encoder tests.""" - -from pathlib import Path -import sys - -ROOT = Path(__file__).resolve().parents[2] -for path in (ROOT, ROOT / "encoder"): - if str(path) not in sys.path: - sys.path.insert(0, str(path)) - - -def pytest_configure(config): - config.option.importmode = "importlib" diff --git a/tests/test_encoder/test_adapters.py b/tests/test_encoder/test_adapters.py deleted file mode 100644 index b5bcdebbb32981b327f5ccbb4bbf7efb6115bd15..0000000000000000000000000000000000000000 --- a/tests/test_encoder/test_adapters.py +++ /dev/null @@ -1,311 +0,0 @@ -"""Tests for encoder/adapters.py -- model-output adapters and canonical geometry validation.""" - -import gzip -import pickle -import sys -import types - -import numpy as np -import pytest - -from encoder import adapters - - -def test_registry_decodes_native_segvggt_dictionary(tmp_path, monkeypatch): - torch = pytest.importorskip("torch") - evaluation = types.ModuleType("eval.instance_eval_common") - evaluation.predict_by_feat_instance = lambda *args, **kwargs: ( - torch.tensor([[1, 0, 0, 0], [0, 1, 0, 0]], dtype=torch.bool), - torch.tensor([0, 2]), - torch.ones(2), - ) - pose = types.ModuleType("segvggt.utils.pose_enc") - pose.pose_encoding_to_extri_intri = lambda value, size: ( - torch.cat( - [ - torch.eye(3).reshape(1, 1, 3, 3), - torch.zeros(1, 1, 3, 1), - ], - dim=-1, - ), - torch.eye(3).reshape(1, 1, 3, 3), - ) - monkeypatch.setitem(sys.modules, "eval.instance_eval_common", evaluation) - monkeypatch.setitem(sys.modules, "segvggt.utils.pose_enc", pose) - - path = tmp_path / "scene.pt" - torch.save( - { - "world_points": torch.zeros(1, 1, 2, 2, 3), - "instance_maps": torch.zeros(1, 2, 1, 2, 2), - "instance_labels": torch.zeros(1, 2, 4), - "pose_enc": torch.zeros(1, 1, 9), - }, - path, - ) - result = adapters.adapt("segvggt", path=path) - assert list(result["instances"]) == ["chair"] - assert result["instances"]["chair"][0]["n"] == 1 - - -def _scene(): - return { - "instances": {"chair": [{"pts": [[0, 0, 0]], "best_pts": [[0, 0, 0]]}]}, - "stats": {"chair": {"raw": 1, "merged": 1, "peak": 1}}, - "scene_pts": [[0, 0, 0]], - "cameras": None, - } - - -def test_validate_normalizes_canonical_geometry(): - result = adapters.validate(_scene()) - instance = result["instances"]["chair"][0] - assert instance["pts"].shape == (1, 3) - assert instance["frames"] == set() - assert instance["n"] == 1 - - -@pytest.mark.parametrize( - ("scene", "error"), - [ - ([], TypeError), - ({"instances": {}}, ValueError), - ( - {"instances": {"chair": [{"pts": [1, 2, 3]}]}, "scene_pts": [[0, 0, 0]]}, - ValueError, - ), - ], -) -def test_validate_rejects_invalid_geometry(scene, error): - with pytest.raises(error): - adapters.validate(scene) - - -def test_validate_identifies_empty_scene(): - with pytest.raises(adapters.EmptySceneError, match="no instances"): - adapters.validate({"instances": {}}) - - -def test_adapt_segvggt_reads_flat_npz(tmp_path): - path = tmp_path / "scene.npz" - world = np.array([[[[0, 0, 1], [1, 0, 1]]]], np.float32) - masks = np.array([[[[True, False]]]]) - np.savez( - path, - world_points=world, - instance_masks=masks, - labels=np.array(["chair"], dtype=object), - frame_times=np.array([0], np.float32), - ) - - result = adapters.adapt_segvggt(path=str(path)) - - instance = result["instances"]["chair"][0] - assert list(result["instances"]) == ["chair"] - assert instance["frames"] == {0} - assert result["stats"]["chair"] == {"raw": 1, "merged": 1, "peak": 1} - - -def test_adapt_segvggt_requires_existing_cache(tmp_path): - with pytest.raises(FileNotFoundError, match="raw cache does not exist"): - adapters.adapt_segvggt(path=str(tmp_path / "missing.npz")) - - -def test_adapter_owned_raw_cache_locations(tmp_path, monkeypatch): - seen = {} - raw_path = tmp_path / "segvggt" / "scene1.pt" - raw_path.parent.mkdir() - raw_path.touch() - - def fake_segvggt(path): - seen["segvggt"] = str(path) - return { - "world_points": np.zeros((1, 1, 1, 3), np.float32), - "instance_masks": np.ones((1, 1, 1, 1), bool), - "labels": np.array(["chair"], dtype=object), - "camera_positions": np.zeros((1, 3), np.float32), - } - - monkeypatch.setattr(adapters, "_decode_segvggt_raw", fake_segvggt) - adapters.adapt_segvggt(root=str(tmp_path), scene="scene1") - assert seen["segvggt"] == str(raw_path) - - -def test_fusion_adapter_resolves_two_native_model_directories(tmp_path, monkeypatch): - seen = {} - depth = np.ones((1, 1, 1), np.float32) - intr = np.eye(3, dtype=np.float32)[None] - c2w = np.eye(4, dtype=np.float32)[None] - - def fake_da3(path): - seen["da3"] = str(path) - return depth, intr, c2w, None - - def fake_sam3(path): - seen["sam3"] = str(path) - return {"object": {0: {0: np.ones((1, 1), bool)}}} - - monkeypatch.setattr(adapters, "_load_native_da3", fake_da3) - monkeypatch.setattr(adapters, "_load_native_sam3", fake_sam3) - adapters.adapt_sam3_depth_anything_3(root=str(tmp_path), scene="scene1") - assert seen == { - "da3": str(tmp_path / "depth-anything-3" / "scene1.pkl"), - "sam3": str(tmp_path / "sam3" / "scene1.pt"), - } - - -def test_adapters_default_to_root_data_caches(monkeypatch, tmp_path): - monkeypatch.delenv("VSI_CACHE_ROOT", raising=False) - seen = {} - - def fake_da3(path): - seen["da3"] = str(path) - return ( - np.ones((1, 1, 1), np.float32), - np.eye(3, dtype=np.float32)[None], - np.eye(4, dtype=np.float32)[None], - None, - ) - - def fake_sam3(path): - seen["sam3"] = str(path) - return {"object": {0: {0: np.ones((1, 1), bool)}}} - - monkeypatch.setattr(adapters, "_load_native_da3", fake_da3) - monkeypatch.setattr(adapters, "_load_native_sam3", fake_sam3) - adapters.adapt_sam3_depth_anything_3(scene="scene1") - assert seen == { - "da3": "/root/data/caches/depth-anything-3/scene1.pkl", - "sam3": "/root/data/caches/sam3/scene1.pt", - } - - -def test_adapt_segvggt_rejects_missing_npz_fields(tmp_path): - path = tmp_path / "broken.npz" - np.savez(path, labels=np.array(["chair"], dtype=object)) - with pytest.raises(KeyError): - adapters.adapt_segvggt(path=str(path)) - - -def test_adapt_sam3_depth_anything_3_decodes_masks_and_backprojects(tmp_path): - da3_path = tmp_path / "scene.da3.npz" - depth = np.full((1, 2, 2), 2.0, np.float32) - intrinsics = np.eye(3, dtype=np.float32)[None] - poses = np.eye(4, dtype=np.float32)[None] - np.savez( - da3_path, - depth=depth, - intr=intrinsics, - c2w=poses, - frame_times=np.array([1.5], np.float32), - ) - mask = np.array([[True, False], [False, True]]) - packed = {"chair": {0: {7: (np.packbits(mask), mask.shape)}}} - mask_path = tmp_path / "scene.sam3.pkl.gz" - with gzip.open(mask_path, "wb") as cache: - pickle.dump(packed, cache) - - result = adapters.adapt_sam3_depth_anything_3( - da3_path=str(da3_path), sam3_path=str(mask_path) - ) - - instance = result["instances"]["chair"][0] - assert instance["frames"] == {0} - assert instance["first_time"] == pytest.approx(1.5) - np.testing.assert_allclose(instance["pts"], [[0, 0, 2], [2, 2, 2]]) - assert result["stats"]["chair"] == {"raw": 1, "merged": 1, "peak": 1} - assert result["raw_inputs"]["per"]["chair"][0][7].dtype == bool - - -def test_backproject_resizes_sam3_mask_to_da3_depth_shape(): - depth = np.full((2, 2), 2.0, np.float32) - mask = np.zeros((4, 4), bool) - mask[0, 0] = True - mask[2, 2] = True - - points, confidence = adapters._backproject( - depth, - np.eye(3, dtype=np.float32), - np.eye(4, dtype=np.float32), - mask, - ) - - assert confidence is None - np.testing.assert_allclose(points, [[0, 0, 2], [2, 2, 2]]) - - -def test_native_sam3_decodes_prompt_keyed_independent_frames(monkeypatch): - responses = {"chair": [{"masks": np.array([[[1, 0], [0, 0]]], dtype=np.uint8)}, {}]} - monkeypatch.setitem( - sys.modules, - "torch", - types.SimpleNamespace(load=lambda *args, **kwargs: responses), - ) - result = adapters._load_native_sam3("scene.pt") - assert result["chair"][0][0].dtype == bool - assert result["chair"][1] == {} - - -def test_native_sam3_preserves_tracked_object_ids(monkeypatch): - responses = [{"out_obj_ids": np.array([7]), "out_binary_masks": np.ones((1, 2, 2))}] - monkeypatch.setitem( - sys.modules, - "torch", - types.SimpleNamespace(load=lambda *args, **kwargs: responses), - ) - monkeypatch.setenv("VSI_SAM3_PROMPT", "chair") - result = adapters._load_native_sam3("scene.pt") - assert list(result["chair"][0]) == [7] - - -def test_native_sam3_decodes_lossless_tracking_cache(monkeypatch): - responses = { - "chair": { - "start_session": {"session_id": "session"}, - "add_prompt": {"is_success": True}, - "stream": [ - { - "frame_index": 3, - "stream_metadata": "preserved", - "outputs": { - "out_obj_ids": np.array([7]), - "out_binary_masks": np.ones((1, 2, 2), bool), - }, - } - ], - "close_session": {"is_success": True}, - } - } - monkeypatch.setitem( - sys.modules, - "torch", - types.SimpleNamespace(load=lambda *args, **kwargs: responses), - ) - - result = adapters._load_native_sam3("scene.pt") - - assert list(result["chair"][3]) == [7] - - -def test_spatial_code_format_validation(): - assert adapters.validate_spatial_code_format("compact") == "compact" - assert adapters.validate_spatial_code_format("explicit") == "explicit" - with pytest.raises(ValueError, match="unknown spatial-code format"): - adapters.validate_spatial_code_format("unknown") - - -def test_native_fusion_times_are_measured_in_seconds(monkeypatch): - monkeypatch.setattr(adapters, "FPS", 4.0) - monkeypatch.setattr( - adapters, - "_load_native_da3", - lambda path: ( - np.ones((3, 1, 1), np.float32), - np.repeat(np.eye(3, dtype=np.float32)[None], 3, axis=0), - np.repeat(np.eye(4, dtype=np.float32)[None], 3, axis=0), - None, - ), - ) - monkeypatch.setattr(adapters, "_load_native_sam3", lambda path: {}) - *_, frame_times, _ = adapters._load_fusion_inputs("scene.pkl", "scene.pt") - np.testing.assert_allclose(frame_times, [0.0, 0.25, 0.5]) diff --git a/tests/test_encoder/test_config.py b/tests/test_encoder/test_config.py deleted file mode 100644 index cb2a852a69729a41d811bdd8ff32b6c3726e63c6..0000000000000000000000000000000000000000 --- a/tests/test_encoder/test_config.py +++ /dev/null @@ -1,44 +0,0 @@ -"""Tests for encoder/config.py -- cache and spatial-code path helpers.""" - -import pytest - -from encoder import config - - -def test_encoder_paths_mirror_all_dimensions(tmp_path, monkeypatch): - monkeypatch.setattr(config, "CACHE_ROOT", tmp_path / "caches") - monkeypatch.setattr(config, "CODES_ROOT", tmp_path / "codes") - assert config.cache_file("scene", "metric", "uniform", "no tracking", 64).endswith( - "no tracking/frames/uniform/64/scene.pkl.gz" - ) - assert config.da3_cache_file("scene", "relative", "uniform", 32).endswith( - "depth-anything-3/relative/frames/uniform/32/scene.pkl" - ) - assert config.video_da3_cache_file("scene").endswith( - "depth-anything-3/metric/video/scene.npz" - ) - assert config.video_da3_cache_file("scene", "relative").endswith( - "depth-anything-3/relative/video/scene.npz" - ) - assert config.video_sam3_cache_file("scene").endswith( - "sam3/no tracking/video/scene.pkl.gz" - ) - assert config.video_sam3_cache_file("scene", "tracking").endswith( - "sam3/tracking/video/scene.pkl.gz" - ) - assert config.spatial_code_path( - "scene", "metric", "selective", "tracking", 64 - ).endswith("tracking/frames/selective/64/explicit/scene.json") - assert config.spatial_code_path( - "scene", "relative", "uniform", "no tracking", 96, "compact" - ).endswith("no tracking/frames/uniform/96/compact/scene.json") - assert config.spatial_code_path( - "scene", "metric", config.VIDEO_INPUT_SELECTION, "no tracking", None, "explicit" - ).endswith("no tracking/video/explicit/scene.json") - - -def test_encoder_paths_reject_unknown_spatial_code_format(): - with pytest.raises(ValueError, match="unknown spatial-code format"): - config.spatial_code_path( - "scene", "metric", "uniform", "tracking", 32, "unknown" - ) diff --git a/tests/test_encoder/test_encoder.py b/tests/test_encoder/test_encoder.py deleted file mode 100644 index cf9a89521c777a8cf0989dbec38b639dd2b63d9d..0000000000000000000000000000000000000000 --- a/tests/test_encoder/test_encoder.py +++ /dev/null @@ -1,73 +0,0 @@ -"""Tests for encoder/geometric.py's low-level geometry primitives (backprojection, -direction/turn classification, distance, centroid/extent math).""" - -import numpy as np -import pytest - -import geometric - - -def test_backproject_frame_applies_intrinsics_pose_and_confidence(): - depth = np.array([[2.0, 2.0], [2.0, np.nan]], np.float32) - mask = np.ones((2, 2), bool) - intrinsics = np.eye(3, dtype=np.float32) - pose = np.eye(4, dtype=np.float32) - pose[0, 3] = 1.0 - confidence = np.array([[0.9, 0.8], [0.1, 1.0]], np.float32) - - points, kept_confidence = geometric.backproject_frame( - depth, intrinsics, pose, mask, confidence, conf_thr=0.5, return_conf=True - ) - - np.testing.assert_allclose(points, [[1.0, 0.0, 2.0], [3.0, 0.0, 2.0]]) - np.testing.assert_allclose(kept_confidence, [0.9, 0.8]) - - -def test_backproject_frame_returns_typed_empty_array(): - points = geometric.backproject_frame( - np.zeros((2, 2), np.float32), np.eye(3), np.eye(4), np.ones((2, 2), bool) - ) - assert points.shape == (0, 3) - assert points.dtype == np.float32 - - -def test_relative_direction_modes(): - origin = np.array([0.0, 0.0, 0.0]) - forward = np.array([0.0, 1.0, 0.0]) - front_left = np.array([-1.0, 1.0, 0.0]) - up = np.array([0.0, 0.0, 1.0]) - assert ( - geometric.answer_rel_direction(origin, forward, front_left, up, 2) - == "front-left" - ) - assert ( - geometric.answer_rel_direction(origin, forward, front_left, up, 2, "medium") - == "left" - ) - assert geometric.answer_rel_direction(origin, origin, front_left, up, 2) is None - - -def test_closest_distance_uses_point_cloud_distance(): - first = [{"pts": np.array([[0.0, 0.0, 0.0]], np.float32), "n": 1}] - second = [{"pts": np.array([[0.0, 3.0, 4.0]], np.float32), "n": 1}] - assert geometric.answer_closest_distance(first, second) == pytest.approx(5.0) - - -def test_robust_centroid_extent_returns_sorted_dimensions(): - points = np.array( - [[x, y, z] for x in (-2.0, 2.0) for y in (-1.0, 1.0) for z in (-0.5, 0.5)], - np.float32, - ) - centroid, longest, dimensions = geometric.robust_centroid_extent(points, up_axis=2) - np.testing.assert_allclose(centroid, [0.0, 0.0, 0.0]) - assert longest > 3.0 - assert np.all(dimensions[:-1] >= dimensions[1:]) - - -def test_depth_edges_handles_small_and_discontinuous_frames(): - small = np.ones((5, 5), np.float32) - assert not geometric.depth_edges(small, np.ones_like(small, bool)).any() - depth = np.ones((20, 20), np.float32) - depth[:, 10:] = 10.0 - edges = geometric.depth_edges(depth, np.ones_like(depth, bool)) - assert edges[:, 9:11].any() diff --git a/tests/test_encoder/test_geometric.py b/tests/test_encoder/test_geometric.py deleted file mode 100644 index b2e60ce74e62a492fcd023ef32d29c5352037623..0000000000000000000000000000000000000000 --- a/tests/test_encoder/test_geometric.py +++ /dev/null @@ -1,387 +0,0 @@ -"""Tests for encoder/geometric.py -- spatial-code schema construction and derivation.""" - -import json -import re - -import numpy as np - -import geometric - - -def test_dump_spatial_code(tmp_path): - path = tmp_path / "scene.json" - geometric.dump_spatial_code({"objects": {}, "appearance order": []}, path) - assert path.exists() - assert '"appearance order"' in path.read_text() - - -def test_raw_bundle_dispatches_to_explicit_derivation(monkeypatch): - expected = ( - { - "spatial code schema": geometric.EXPLICIT_SPATIAL_CODE_SCHEMA, - "objects": {}, - "room": {"floor area": "0.0 square meters"}, - "closest classes distance meters from": {}, - "appearance order": [], - }, - {}, - {}, - 1, - np.array([0, 1, 0], dtype=np.float32), - 0.0, - ) - seen = {} - - def fake(scene): - seen["scene"] = scene - return expected - - monkeypatch.setattr(geometric, "build_explicit_spatial_code", fake) - raw = { - "depth": np.ones((1, 2, 2), np.float32), - "intr": np.eye(3, dtype=np.float32)[None], - "c2w": np.eye(4, dtype=np.float32)[None], - "conf": None, - "ftimes": np.array([0.0], np.float32), - "per": {"chair": {}}, - } - scene = {"raw_inputs": raw} - assert geometric.build_spatial_code(scene) is expected - assert seen["scene"] is scene - - -def test_explicit_is_a_derivation_of_compact(monkeypatch): - """build_explicit_spatial_code() must always build compact FIRST and derive from it -- - not measure geometry independently.""" - compact_expected = ( - { - "spatial code schema": geometric.COMPACT_SPATIAL_CODE_SCHEMA, - "objects": {}, - "room": {}, - }, - {}, - {}, - 1, - np.array([0, 1, 0], dtype=np.float32), - None, - ) - seen = {} - - def fake_compact(scene): - seen["scene"] = scene - return compact_expected - - monkeypatch.setattr(geometric, "build_compact_spatial_code", fake_compact) - scene = {"raw_inputs": None} - code, *_ = geometric.build_explicit_spatial_code(scene) - assert seen["scene"] is scene - assert code["objects"] == {} - - -def test_exact_math_is_integrated_into_geometric_module(): - assert callable(geometric.build_explicit_spatial_code) - assert callable(geometric.dump_spatial_code) - assert not hasattr(geometric, "_reference") - - -def test_position_reader_accepts_current_and_legacy_formatting(): - assert geometric.pos3( - { - "position": { - "x coordinate": "1.25 meters", - "y coordinate": "-2.0 meters", - "height above floor": "0.5 meters", - } - } - ) == [1.25, -2.0, 0.5] - assert geometric.pos3( - { - "position": { - "floor_x_meters": 1.25, - "floor_y_meters": -2.0, - "height_above_floor_meters": 0.5, - } - } - ) == [1.25, -2.0, 0.5] - - -def test_floor_level_v1_v2_math_is_shared(monkeypatch): - points = np.array([[0, 0, z] for z in [0, 0, 0, 1, 10]], np.float32) - gravity = np.array([0, 0, 1], np.float32) - monkeypatch.delenv("VSI_CODE_V2", raising=False) - v1 = geometric._floor_level(points, gravity) - monkeypatch.setenv("VSI_CODE_V2", "1") - v2 = geometric._floor_level(points, gravity) - assert 0 <= v1 < 0.2 - assert v2 == 0.0 - - -METERS = re.compile(r"^-?\d+(?:\.\d+)? meters$") -SQUARE_METERS = re.compile(r"^\d+(?:\.\d+)? square meters$") - - -def _schema_instance(x, y, z, size, first_time=0.0): - pts = np.array( - [ - [x - size / 2, y, z], - [x + size / 2, y, z], - [x, y - size / 2, z], - [x, y + size / 2, z], - ], - dtype=np.float32, - ) - return { - "pts": pts, - "best_pts": pts, - "n": len(pts), - "nframes": 1, - "first_time": first_time, - "frames": {0}, - } - - -def _schema_scene(): - chair = _schema_instance(0.0, 0.0, 0.5, 0.8, first_time=0.0) - table = _schema_instance(1.0, 0.0, 0.7, 1.2, first_time=1.0) - floor = np.array( - [[x, y, 0.0] for x in np.linspace(-1, 2, 5) for y in np.linspace(-1, 1, 5)], - dtype=np.float32, - ) - return { - "instances": {"chair": [chair], "table": [table]}, - "stats": {"chair": {"peak": 1}, "table": {"peak": 3}}, - "scene_pts": np.concatenate([chair["pts"], table["pts"], floor], axis=0), - "cameras": None, - } - - -def test_spatial_code_matches_reference_schema(): - code, *_ = geometric.build_spatial_code(_schema_scene()) - assert list(code) == [ - "spatial code schema", - "objects", - "room", - "closest classes distance meters from", - "appearance order", - ] - assert code["spatial code schema"] == geometric.EXPLICIT_SPATIAL_CODE_SCHEMA - assert code["appearance order"] == ["chair", "table"] - assert SQUARE_METERS.match(code["room"]["floor area"]) - for class_data in code["objects"].values(): - assert set(class_data) == {"count", "instances"} - assert class_data["count"] == len(class_data["instances"]) - for instance in class_data["instances"]: - assert set(instance) == {"position", "longest dimension"} - assert set(instance["position"]) == { - "x coordinate", - "y coordinate", - "height above floor", - } - assert all(METERS.match(value) for value in instance["position"].values()) - assert METERS.match(instance["longest dimension"]) - assert code["objects"]["table"]["count"] == 1 - chair_to_table = code["closest classes distance meters from"]["chair"]["table"] - assert set(chair_to_table) == {"distance", "closeness rank"} - assert METERS.match(chair_to_table["distance"]) - assert chair_to_table["closeness rank"] == 1 - - -def test_dumped_json_preserves_schema(tmp_path): - code, *_ = geometric.build_spatial_code(_schema_scene()) - path = tmp_path / "scene.json" - geometric.dump_spatial_code(code, path) - assert json.loads(path.read_text()) == code - - -def test_compact_spatial_code_exposes_only_reusable_primitives(): - code, *_ = geometric.build_spatial_code(_schema_scene(), "compact") - assert list(code) == ["spatial code schema", "objects", "room"] - assert set(code["objects"]) == {"chair", "table"} - assert len(code["objects"]["chair"]) == 1 - instance = code["objects"]["chair"][0] - assert set(instance) == {"3D oriented bounding box", "first visible time"} - box = instance["3D oriented bounding box"] - assert set(box) == { - "3D oriented bounding box center coordinates", - "3D oriented bounding box dimensions", - "3D oriented bounding box orientation unit vectors", - } - assert len(box["3D oriented bounding box center coordinates"]) == 3 - assert len(box["3D oriented bounding box dimensions"]) == 3 - orientation = np.asarray( - box["3D oriented bounding box orientation unit vectors"], dtype=np.float64 - ) - np.testing.assert_allclose(orientation @ orientation.T, np.eye(3), atol=0.02) - assert instance["first visible time"] == 0.0 - polygons = code["room"]["floor boundary polygons"] - assert len(polygons) == 1 - assert len(polygons[0]["outer boundary coordinates"]) >= 3 - for hole in polygons[0]["interior hole boundary coordinates"]: - assert len(hole) >= 3 - assert all(len(coordinate) == 2 for coordinate in hole) - assert "closest classes distance meters from" not in code - assert "appearance order" not in code - - -def test_explicit_spatial_code_remains_the_default(): - default, *_ = geometric.build_spatial_code(_schema_scene()) - code, *_ = geometric.build_spatial_code(_schema_scene(), "explicit") - assert default == code - - -def test_compact_spatial_code_merges_revisit_instances_and_keeps_earliest_time(): - scene = _schema_scene() - revisit = dict(scene["instances"]["chair"][0]) - revisit.update({"frames": {1}, "first_time": -1.0}) - scene["instances"]["chair"].append(revisit) - scene["stats"]["chair"] = {"raw": 2, "merged": 2, "peak": 1} - - code, instances, *_ = geometric.build_spatial_code(scene, "compact") - - assert len(instances["chair"]) == 1 - assert len(code["objects"]["chair"]) == 1 - assert code["objects"]["chair"][0]["first visible time"] == -1.0 - - -def test_compact_oriented_box_uses_accumulated_instance_points(): - xs = np.linspace(-2.0, 2.0, 80) - points = np.stack([xs, np.zeros_like(xs), np.full_like(xs, 0.5)], axis=1) - instance = { - "pts": points.astype(np.float32), - "best_pts": points[38:42].astype(np.float32), - "conf": None, - } - - box = geometric._compact_oriented_box( - instance, - np.array([1.0, 0.0, 0.0]), - np.array([0.0, 1.0, 0.0]), - np.array([0.0, 0.0, 1.0]), - 0.0, - ) - - assert max(box["3D oriented bounding box dimensions"]) > 3.5 - - -def test_compact_floor_boundaries_preserve_disconnected_regions(): - first = np.array( - [[x, y, 0.0] for x in np.linspace(0, 1, 11) for y in np.linspace(0, 1, 11)] - ) - second = np.array( - [[x, y, 0.0] for x in np.linspace(5, 6, 11) for y in np.linspace(0, 1, 11)] - ) - - polygons = geometric._compact_floor_boundary_polygons( - np.concatenate([first, second]), - np.array([1.0, 0.0, 0.0]), - np.array([0.0, 1.0, 0.0]), - ) - - assert len(polygons) == 2 - assert all(len(polygon["outer boundary coordinates"]) >= 3 for polygon in polygons) - - -def test_compact_spatial_code_suppresses_co_visible_duplicate_tracks(): - points = np.array( - [[x, y, z] for x in (-0.5, 0.5) for y in (-0.5, 0.5) for z in (0.0, 1.0)], - dtype=np.float32, - ) - first = { - "pts": points, - "best_pts": points, - "observations": [points], - "frames": {0}, - "n": len(points), - "nframes": 1, - "first_time": 0.0, - } - second = dict(first) - second.update({"pts": points + 0.01, "best_pts": points + 0.01}) - scene = { - "instances": {"chair": [first, second]}, - "stats": {"chair": {"raw": 2, "merged": 2, "peak": 2}}, - "scene_pts": np.concatenate([points, points + 0.01]), - "cameras": None, - } - - code, instances, *_ = geometric.build_spatial_code(scene, "compact") - - assert len(instances["chair"]) == 1 - assert len(code["objects"]["chair"]) == 1 - - -def test_compact_oriented_box_combines_observation_extents_by_consensus(): - narrow_x = np.linspace(-1.0, 1.0, 80) - wide_x = np.linspace(-2.0, 2.0, 80) - narrow = np.stack( - [narrow_x, np.zeros_like(narrow_x), np.full_like(narrow_x, 0.5)], axis=1 - ).astype(np.float32) - wide = np.stack( - [wide_x, np.zeros_like(wide_x), np.full_like(wide_x, 0.5)], axis=1 - ).astype(np.float32) - instance = { - "pts": np.concatenate([narrow, wide]), - "best_pts": narrow, - "observations": [narrow, wide], - "conf": None, - } - - box = geometric._compact_oriented_box( - instance, - np.array([1.0, 0.0, 0.0]), - np.array([0.0, 1.0, 0.0]), - np.array([0.0, 0.0, 1.0]), - 0.0, - ) - - # The LONGEST axis recovers the fullest observed extent (the wide view's full 4.0 span), - # not the cross-observation consensus -- a partial view underestimates true length, so the - # object is at least as long as the fullest clean view saw (see _compact_oriented_box's - # length-axis decoupling). Width/depth stay on the robust consensus. - assert 3.9 < max(box["3D oriented bounding box dimensions"]) <= 4.0 - - -def test_compact_instances_keep_peak_co_visible_hypotheses_by_evidence(): - scene = _schema_scene() - weak = _schema_instance(4.0, 0.0, 0.5, 0.8, first_time=-1.0) - weak.update({"n": 4, "nframes": 1, "frames": {2}}) - strong = scene["instances"]["chair"][0] - strong.update({"n": 40, "nframes": 3, "frames": {0, 1, 2}}) - scene["instances"]["chair"] = [weak, strong] - scene["stats"]["chair"] = {"raw": 2, "merged": 2, "peak": 1} - - code, instances, *_ = geometric.build_spatial_code(scene, "compact") - - assert len(instances["chair"]) == 1 - assert instances["chair"][0]["nframes"] == 3 - assert instances["chair"][0]["first_time"] == -1.0 - assert len(code["objects"]["chair"]) == 1 - - -def test_compact_oriented_box_rejects_one_inconsistent_observation(): - ordinary = np.stack( - [ - np.linspace(-1.0, 1.0, 80), - np.zeros(80), - np.full(80, 0.5), - ], - axis=1, - ).astype(np.float32) - outlier = ordinary.copy() - outlier[:, 0] *= 20 - instance = { - "pts": np.concatenate([ordinary] * 4 + [outlier]), - "best_pts": ordinary, - "observations": [ordinary] * 4 + [outlier], - "conf": None, - } - - box = geometric._compact_oriented_box( - instance, - np.array([1.0, 0.0, 0.0]), - np.array([0.0, 1.0, 0.0]), - np.array([0.0, 0.0, 1.0]), - 0.0, - ) - - assert max(box["3D oriented bounding box dimensions"]) < 3.0 diff --git a/tests/test_encoder/test_ground_truth.py b/tests/test_encoder/test_ground_truth.py deleted file mode 100644 index a0608f0210c06fbcfd541b4a882b592cd3fb7d85..0000000000000000000000000000000000000000 --- a/tests/test_encoder/test_ground_truth.py +++ /dev/null @@ -1,327 +0,0 @@ -"""Tests for encoder/ground_truth.py -- spatial codes built from dataset annotations.""" - -import json -import math - -import numpy as np -import pytest - -from encoder import config, geometric -from encoder import ground_truth as gt - -IDENTITY_AXES = [1, 0, 0, 0, 1, 0, 0, 0, 1] - - -def _instance(centroid, dims, axes=None): - return { - "centroid": list(centroid), - "axesLengths": list(dims), - "normalizedAxes": list(axes if axes is not None else IDENTITY_AXES), - } - - -def _write_meta_info(tmp_path, scannet=None, arkitscenes=None, scannetpp=None): - meta_dir = tmp_path / "thinking-in-space" / "data" / "meta_info" - meta_dir.mkdir(parents=True) - for dataset, records in ( - ("scannet", scannet or {}), - ("arkitscenes", arkitscenes or {}), - ("scannetpp", scannetpp or {}), - ): - with open(meta_dir / f"{dataset}_meta_info_val.json", "w") as stream: - json.dump(records, stream) - return meta_dir - - -@pytest.fixture(autouse=True) -def _clear_ground_truth_caches(): - gt.load_meta_info.cache_clear() - gt._appearance_order_ranks_by_scene.cache_clear() - yield - gt.load_meta_info.cache_clear() - gt._appearance_order_ranks_by_scene.cache_clear() - - -def test_load_meta_info_merges_all_three_datasets_and_tags_dataset( - tmp_path, monkeypatch -): - _write_meta_info( - tmp_path, - scannet={"scene0001_00": {"room_size": 10.0, "object_bbox": {}}}, - arkitscenes={"41000000": {"room_size": 12.0, "object_bbox": {}}}, - scannetpp={"abc123": {"room_size": 14.0, "object_bbox": {}}}, - ) - monkeypatch.setattr( - gt, "META_INFO_DIR", tmp_path / "thinking-in-space" / "data" / "meta_info" - ) - merged = gt.load_meta_info() - assert merged["scene0001_00"]["dataset"] == "scannet" - assert merged["41000000"]["dataset"] == "arkitscenes" - assert merged["abc123"]["dataset"] == "scannetpp" - - -def test_floor_level_is_the_lowest_box_support_across_every_instance(): - object_bbox = { - "chair": [_instance([0, 0, 1.0], [1, 1, 0.4])], # spans z in [0.8, 1.2] - "table": [_instance([0, 0, 0.5], [1, 1, 1.0])], # spans z in [0.0, 1.0] - } - # table reaches lower (0.0) than chair (0.8) -> floor_level should be 0.0 - assert gt._floor_level(object_bbox) == pytest.approx(0.0) - - -def test_floor_level_accounts_for_tilted_box_support(): - # a box tilted 45 degrees around x has a lower support than its centroid_z - half_z - # would suggest if you ignored orientation. - axes = [ - [1, 0, 0], - [0, math.cos(math.pi / 4), math.sin(math.pi / 4)], - [0, -math.sin(math.pi / 4), math.cos(math.pi / 4)], - ] - flat_axes = [v for row in axes for v in row] - object_bbox = {"box": [_instance([0, 0, 1.0], [1, 2, 2], axes=flat_axes)]} - half_extent_z = ( - (1 / 2) * abs(0) - + (2 / 2) * abs(math.sin(math.pi / 4)) - + (2 / 2) * abs(math.cos(math.pi / 4)) - ) - assert gt._floor_level(object_bbox) == pytest.approx(1.0 - half_extent_z) - - -def test_floor_level_defaults_to_zero_for_empty_scene(): - assert gt._floor_level({}) == 0.0 - - -def test_gt_oriented_box_rebases_height_above_floor_and_passes_xy_through(): - instance = _instance([1.234, -2.345, 3.456], [1.0, 2.0, 3.0]) - box = gt._gt_oriented_box(instance, floor_level=1.0) - center = box["3D oriented bounding box center coordinates"] - assert center == [1.23, -2.35, 2.46] - assert box["3D oriented bounding box dimensions"] == [1.0, 2.0, 3.0] - assert box["3D oriented bounding box orientation unit vectors"] == [ - [1.0, 0.0, 0.0], - [0.0, 1.0, 0.0], - [0.0, 0.0, 1.0], - ] - - -def test_gt_oriented_box_renormalizes_orientation_vectors(): - axes = [2, 0, 0, 0, 2, 0, 0, 0, 2] # not unit length - instance = _instance([0, 0, 0], [1, 1, 1], axes=axes) - box = gt._gt_oriented_box(instance, floor_level=0.0) - for row in box["3D oriented bounding box orientation unit vectors"]: - assert np.linalg.norm(row) == pytest.approx(1.0) - - -def test_gt_floor_boundary_polygon_area_matches_room_size(): - polygons = gt._gt_floor_boundary_polygons( - room_size=16.0, room_center=[3.0, -2.0, 0.0] - ) - assert len(polygons) == 1 - area = geometric._compact_polygon_area(polygons[0]["outer boundary coordinates"]) - assert area == pytest.approx(16.0, abs=0.01) - assert polygons[0]["interior hole boundary coordinates"] == [] - - -def test_appearance_order_ranks_topological_across_multiple_questions( - tmp_path, monkeypatch -): - jsonl_path = tmp_path / "test.jsonl" - questions = [ - { - "scene_name": "scene1", - "question_type": "obj_appearance_order", - "ground_truth": "A", - "options": ["A. chair, table, lamp", "B. lamp, table, chair"], - }, - { - "scene_name": "scene1", - "question_type": "obj_appearance_order", - "ground_truth": "A", - "options": ["A. table, sofa", "B. sofa, table"], - }, - { - "scene_name": "scene2", - "question_type": "object_counting", - "ground_truth": "3", - "options": None, - }, - ] - with open(jsonl_path, "w") as stream: - for question in questions: - stream.write(json.dumps(question) + "\n") - monkeypatch.setattr(config, "JSONL", jsonl_path) - - ranks = gt._appearance_order_ranks_by_scene() - assert "scene2" not in ranks - scene1 = ranks["scene1"] - assert scene1["chair"] < scene1["table"] < scene1["lamp"] - assert scene1["table"] < scene1["sofa"] - - -def test_build_compact_ground_truth_spatial_code_uses_ranks_and_nulls_unranked( - tmp_path, monkeypatch -): - _write_meta_info( - tmp_path, - scannet={ - "scene1": { - "room_size": 9.0, - "room_center": [0.0, 0.0, 0.0], - "object_bbox": { - "chair": [_instance([0, 0, 0.5], [1, 1, 1])], - "lamp": [_instance([1, 1, 0.5], [0.2, 0.2, 0.2])], - }, - } - }, - ) - monkeypatch.setattr( - gt, "META_INFO_DIR", tmp_path / "thinking-in-space" / "data" / "meta_info" - ) - jsonl_path = tmp_path / "test.jsonl" - with open(jsonl_path, "w") as stream: - stream.write( - json.dumps( - { - "scene_name": "scene1", - "question_type": "obj_appearance_order", - "ground_truth": "A", - "options": ["A. chair, lamp"], - } - ) - + "\n" - ) - monkeypatch.setattr(config, "JSONL", jsonl_path) - - code = gt.build_compact_ground_truth_spatial_code("scene1") - assert code["spatial code schema"] is geometric.COMPACT_SPATIAL_CODE_SCHEMA - assert code["objects"]["chair"][0]["first visible time"] == 0.0 - assert code["objects"]["lamp"][0]["first visible time"] == 1.0 - - -def test_build_compact_ground_truth_spatial_code_nulls_untimed_classes( - tmp_path, monkeypatch -): - _write_meta_info( - tmp_path, - scannet={ - "scene1": { - "room_size": 9.0, - "room_center": [0.0, 0.0, 0.0], - "object_bbox": {"chair": [_instance([0, 0, 0.5], [1, 1, 1])]}, - } - }, - ) - monkeypatch.setattr( - gt, "META_INFO_DIR", tmp_path / "thinking-in-space" / "data" / "meta_info" - ) - monkeypatch.setattr(config, "JSONL", tmp_path / "empty.jsonl") - (tmp_path / "empty.jsonl").write_text("") - - code = gt.build_compact_ground_truth_spatial_code("scene1") - assert code["objects"]["chair"][0]["first visible time"] is None - - -def test_build_compact_ground_truth_spatial_code_raises_for_unknown_scene( - tmp_path, monkeypatch -): - _write_meta_info(tmp_path) - monkeypatch.setattr( - gt, "META_INFO_DIR", tmp_path / "thinking-in-space" / "data" / "meta_info" - ) - monkeypatch.setattr(config, "JSONL", tmp_path / "empty.jsonl") - (tmp_path / "empty.jsonl").write_text("") - with pytest.raises(KeyError): - gt.build_compact_ground_truth_spatial_code("nonexistent") - - -def test_build_explicit_ground_truth_spatial_code_is_derived_from_compact(monkeypatch): - compact_code = { - "spatial code schema": geometric.COMPACT_SPATIAL_CODE_SCHEMA, - "objects": { - "chair": [ - { - "3D oriented bounding box": { - "3D oriented bounding box center coordinates": [0, 0, 0.5], - "3D oriented bounding box dimensions": [1, 1, 1], - "3D oriented bounding box orientation unit vectors": [ - [1, 0, 0], - [0, 1, 0], - [0, 0, 1], - ], - }, - "first visible time": 0.0, - } - ] - }, - "room": {"floor boundary polygons": []}, - } - monkeypatch.setattr( - gt, "build_compact_ground_truth_spatial_code", lambda scene: compact_code - ) - explicit_code = gt.build_explicit_ground_truth_spatial_code("scene1") - assert ( - explicit_code["spatial code schema"] is geometric.EXPLICIT_SPATIAL_CODE_SCHEMA - ) - assert explicit_code["objects"]["chair"]["count"] == 1 - assert explicit_code["appearance order"] == ["chair"] - - -def test_build_ground_truth_spatial_code_dispatches_by_format(monkeypatch): - monkeypatch.setattr( - gt, "build_compact_ground_truth_spatial_code", lambda scene: "compact-code" - ) - monkeypatch.setattr( - gt, "build_explicit_ground_truth_spatial_code", lambda scene: "explicit-code" - ) - assert gt.build_ground_truth_spatial_code("scene1", "compact") == "compact-code" - assert gt.build_ground_truth_spatial_code("scene1", "explicit") == "explicit-code" - - -def test_build_ground_truth_spatial_code_rejects_unknown_format(): - with pytest.raises(ValueError, match="unknown spatial-code format"): - gt.build_ground_truth_spatial_code("scene1", "unknown") - - -def test_build_and_write_writes_to_the_ground_truth_path(tmp_path, monkeypatch): - monkeypatch.setattr(config, "CODES_ROOT", tmp_path / "codes") - monkeypatch.setattr( - gt, "build_ground_truth_spatial_code", lambda scene, fmt: {"objects": {}} - ) - path = gt.build_and_write("scene1", "explicit") - assert path.endswith("codes/ground truth/explicit/scene1.json") - assert json.loads(open(path).read()) == {"objects": {}} - - -def test_scenes_returns_sorted_meta_info_keys(tmp_path, monkeypatch): - _write_meta_info( - tmp_path, - scannet={"scene0002_00": {}, "scene0001_00": {}}, - arkitscenes={"41000000": {}}, - ) - monkeypatch.setattr( - gt, "META_INFO_DIR", tmp_path / "thinking-in-space" / "data" / "meta_info" - ) - assert gt.scenes() == ["41000000", "scene0001_00", "scene0002_00"] - - -def test_build_all_writes_every_scene_and_format(tmp_path, monkeypatch): - monkeypatch.setattr(config, "CODES_ROOT", tmp_path / "codes") - monkeypatch.setattr(gt, "scenes", lambda: ["scene1", "scene2"]) - monkeypatch.setattr( - gt, "build_ground_truth_spatial_code", lambda scene, fmt: {"objects": {}} - ) - written = gt.build_all() - assert len(written) == 4 - assert (tmp_path / "codes" / "ground truth" / "explicit" / "scene1.json").exists() - assert (tmp_path / "codes" / "ground truth" / "compact" / "scene2.json").exists() - - -def test_build_all_respects_explicit_scene_list_and_formats(tmp_path, monkeypatch): - monkeypatch.setattr(config, "CODES_ROOT", tmp_path / "codes") - monkeypatch.setattr( - gt, "build_ground_truth_spatial_code", lambda scene, fmt: {"objects": {}} - ) - written = gt.build_all(spatial_code_formats=("compact",), scene_list=["scene9"]) - assert written == [ - str(tmp_path / "codes" / "ground truth" / "compact" / "scene9.json") - ] diff --git a/tests/test_encoder/test_init.py b/tests/test_encoder/test_init.py deleted file mode 100644 index e8b95cf73b1554ca88509c5a76ea2c9943627a0c..0000000000000000000000000000000000000000 --- a/tests/test_encoder/test_init.py +++ /dev/null @@ -1,7 +0,0 @@ -"""Tests for encoder package importability.""" - -import encoder - - -def test_encoder_package_imports_without_data_or_checkpoints(): - assert encoder.__doc__ == "Spatial-code encoder package." diff --git a/tests/test_encoder/test_launch.py b/tests/test_encoder/test_launch.py deleted file mode 100644 index 26079d6d11c586198b1103c132f0c9913412de4b..0000000000000000000000000000000000000000 --- a/tests/test_encoder/test_launch.py +++ /dev/null @@ -1,7 +0,0 @@ -"""Tests for encoder/launch.py -- CPU-parallel batch driver.""" - -from encoder import launch - - -def test_encoder_launcher_imports(): - assert callable(launch.main) diff --git a/tests/test_encoder/test_render.py b/tests/test_encoder/test_render.py deleted file mode 100644 index 36ce6374bbc97424853e10b7b1cd136813e04db4..0000000000000000000000000000000000000000 --- a/tests/test_encoder/test_render.py +++ /dev/null @@ -1,9 +0,0 @@ -"""Tests for encoder/render.py -- spatial-code rendering entry point.""" - -from encoder import render - - -def test_render_exposes_tracking_and_format_dimensions(): - variables = render.write_spatial_code_for.__code__.co_varnames - assert "tracking" in variables - assert "spatial_code_format" not in variables diff --git a/tests/test_encoder/test_run.py b/tests/test_encoder/test_run.py deleted file mode 100644 index 6c9c463dd96a38c500c0a1b8cc73424559006e4d..0000000000000000000000000000000000000000 --- a/tests/test_encoder/test_run.py +++ /dev/null @@ -1,24 +0,0 @@ -"""Tests for encoder/run.py -- combined cache loading and source provenance.""" - -from encoder import run - - -def test_cache_or_load_exposes_explicit_dimensions(): - assert "frame_count" in run.cache_or_load.__code__.co_varnames - - -def test_video_mode_preserves_depth_and_tracking(): - assert run._effective_dimensions("relative", None, "tracking", True) == ( - "relative", - "video", - "tracking", - ) - - -def test_video_mode_selects_caches_for_requested_axes(tmp_path, monkeypatch): - monkeypatch.setattr(run.config, "CACHE_ROOT", tmp_path) - da3_path, sam3_path = run._cache_source_paths( - "scene", "relative", "video", "tracking", 32, True, None, None - ) - assert da3_path.endswith("depth-anything-3/relative/video/scene.npz") - assert sam3_path.endswith("sam3/tracking/video/scene.pkl.gz") diff --git a/tests/test_experiments/__init__.py b/tests/test_experiments/__init__.py deleted file mode 100644 index df1def1e2acc704d98559591559e25d77068d207..0000000000000000000000000000000000000000 --- a/tests/test_experiments/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Tests for the experiments package.""" diff --git a/tests/test_experiments/conftest.py b/tests/test_experiments/conftest.py deleted file mode 100644 index 06f2ab1af00b2b5b61d163761175c83246379d3e..0000000000000000000000000000000000000000 --- a/tests/test_experiments/conftest.py +++ /dev/null @@ -1 +0,0 @@ -"""Shared fixtures for experiment tests.""" diff --git a/tests/test_experiments/test_config.py b/tests/test_experiments/test_config.py deleted file mode 100644 index d088260673e3aa98f24e6705b707b80dc1f3de7a..0000000000000000000000000000000000000000 --- a/tests/test_experiments/test_config.py +++ /dev/null @@ -1,70 +0,0 @@ -import pytest - -from experiments import config - - -def test_spatial_code_path_has_all_dimensions(): - path = config.spatial_code_path( - "scene0000_00", - "A Human Readable Hypothesis", - "metric", - "tracking", - "uniform", - 64, - ) - assert ( - path - == config.CACHES_ROOT - / "spatial codes" - / "metric" - / "tracking" - / "uniform" - / "A Human Readable Hypothesis" - / "64" - / "explicit" - / "scene0000_00.json" - ) - - -def test_spatial_code_path_accepts_compact_format(): - path = config.spatial_code_path( - "scene0000_00", - "A Human Readable Hypothesis", - "metric", - "tracking", - "uniform", - 64, - spatial_code_format="compact", - ) - assert ( - path - == config.CACHES_ROOT - / "spatial codes" - / "metric" - / "tracking" - / "uniform" - / "A Human Readable Hypothesis" - / "64" - / "compact" - / "scene0000_00.json" - ) - - -def test_spatial_code_directory_rejects_unknown_format(): - with pytest.raises(ValueError): - config.spatial_code_directory( - "A Hypothesis", "metric", "tracking", "uniform", 64, "bogus" - ) - - -@pytest.mark.parametrize("name", ["../escape", "nested/name", "", ".", ".."]) -def test_hypothesis_name_cannot_escape_root(name): - with pytest.raises(ValueError): - config.normalize_hypothesis(name) - - -def test_result_path_is_experiment_local(): - path = config.result_directory( - "A Hypothesis", "symbolic", "metric", "tracking", "uniform", 64 - ) - assert path.is_relative_to(config.RESULTS_ROOT) diff --git a/tests/test_experiments/test_evaluate.py b/tests/test_experiments/test_evaluate.py deleted file mode 100644 index 13ac6b32c3349ef0500c38acf5e5f53c82ed8d91..0000000000000000000000000000000000000000 --- a/tests/test_experiments/test_evaluate.py +++ /dev/null @@ -1,48 +0,0 @@ -from experiments import config, evaluate - - -def test_configure_symbolic_evaluation_uses_experiment_paths(): - codes, results = evaluate.configure_symbolic_evaluation( - "A Hypothesis", "metric", "tracking", "uniform", 64 - ) - assert ( - codes - == config.CACHES_ROOT - / "spatial codes" - / "metric" - / "tracking" - / "uniform" - / "A Hypothesis" - / "64" - / "explicit" - ) - assert ( - results - == config.RESULTS_ROOT - / "symbolic" - / "metric" - / "tracking" - / "uniform" - / "A Hypothesis" - / "64" - / "explicit" - ) - assert evaluate.symbolic_launch.symbolic_run.SPATIAL_CODES_DIR == str(codes) - assert evaluate.symbolic_launch.symbolic_run.SPATIAL_CODES_FORMAT == "explicit" - assert evaluate.symbolic_launch.symbolic_run.results_dir_for_selection() == str( - results - ) - - -def test_configure_symbolic_evaluation_accepts_compact_format(): - codes, results = evaluate.configure_symbolic_evaluation( - "A Hypothesis", - "metric", - "tracking", - "uniform", - 64, - spatial_code_format="compact", - ) - assert codes.name == "compact" - assert results.name == "compact" - assert evaluate.symbolic_launch.symbolic_run.SPATIAL_CODES_FORMAT == "compact" diff --git a/tests/test_experiments/test_experiments.py b/tests/test_experiments/test_experiments.py deleted file mode 100644 index 7d63433ef8eceb8db6a358ec494c4bbee7039f17..0000000000000000000000000000000000000000 --- a/tests/test_experiments/test_experiments.py +++ /dev/null @@ -1,10 +0,0 @@ -from experiments import config, loader - - -def test_experiments_package_exposes_hypotheses_directory(): - assert config.EXPERIMENT_ROOT.name == "experiments" - assert config.HYPOTHESES_ROOT.is_dir() - - -def test_experiments_have_discoverable_hypotheses(): - assert loader.list_hypotheses() diff --git a/tests/test_experiments/test_hypotheses.py b/tests/test_experiments/test_hypotheses.py deleted file mode 100644 index 528922ebd81b31d7a61a6e837b7a6b32650531b5..0000000000000000000000000000000000000000 --- a/tests/test_experiments/test_hypotheses.py +++ /dev/null @@ -1,230 +0,0 @@ -import numpy as np - -from experiments import loader - - -def test_every_hypothesis_has_required_interface(): - names = loader.list_hypotheses() - assert names - for name in names: - module = loader.load_hypothesis(name) - for callable_name in loader.REQUIRED_CALLABLES: - assert callable( - getattr(module, callable_name, None) - ), f"{name} is missing {callable_name}()" - - -def test_size_percentile_hypotheses_preserve_baseline_centroid(): - smaller = np.stack( - [np.linspace(0.0, 1.0, 20), np.zeros(20), np.zeros(20)], axis=1 - ).astype(np.float32) - larger = np.stack( - [np.linspace(10.0, 12.0, 30), np.zeros(30), np.zeros(30)], axis=1 - ).astype(np.float32) - observations = [smaller, larger] - for name, percentile in ( - ("Estimate Object Size From the 65th Percentile Across Frames", 65), - ("Estimate Object Size From the 75th Percentile Across Frames", 75), - ("Estimate Object Size From the 90th Percentile Across Frames", 90), - ("Estimate Object Size From the 95th Percentile Across Frames", 95), - ("Estimate Object Size From the Maximum Across Frames", 100), - ): - module = loader.load_hypothesis(name) - expected, _, _ = module.robust_centroid_extent(larger, None) - actual, size, dims = module.estimate_track_geometry(observations, None) - frame_dims = np.stack( - [module.robust_centroid_extent(points, None)[2] for points in observations] - ) - expected_dims = np.sort(np.percentile(frame_dims, percentile, axis=0))[::-1] - np.testing.assert_allclose(actual, expected) - np.testing.assert_allclose(dims, expected_dims) - assert size == expected_dims.max() - - -def test_symmetric_surface_percentile_distance_is_density_independent(): - module = loader.load_hypothesis( - "Measure Absolute Object Distance Using Symmetric Surface Percentiles" - ) - points_a = np.asarray([[0.0, 0.0, 0.0], [10.0, 0.0, 0.0]], dtype=np.float32) - points_b = np.asarray([[1.0, 0.0, 0.0]], dtype=np.float32) - instances_a = [{"pts": points_a, "n": len(points_a)}] - instances_b = [{"pts": points_b, "n": len(points_b)}] - expected = 0.5 * (np.percentile([1.0, 9.0], 1.0) + 1.0) - - forward = module.answer_closest_distance(instances_a, instances_b) - reverse = module.answer_closest_distance(instances_b, instances_a) - canonical = module._canonical_answer_closest_distance(instances_a, instances_b) - - np.testing.assert_allclose(forward, expected) - np.testing.assert_allclose(reverse, expected) - np.testing.assert_allclose(canonical, expected) - - -def test_multi_view_oriented_box_distance_uses_complete_boxes(): - module = loader.load_hypothesis( - "Estimate Absolute Object Distance From Multi View Oriented Bounding Boxes" - ) - signs = np.asarray( - [[x, y, z] for x in (-1.0, 1.0) for y in (-0.5, 0.5) for z in (-0.25, 0.25)], - dtype=np.float32, - ) - angle = np.deg2rad(30.0) - rotation = np.asarray( - [ - [np.cos(angle), -np.sin(angle), 0.0], - [np.sin(angle), np.cos(angle), 0.0], - [0.0, 0.0, 1.0], - ], - dtype=np.float32, - ) - direction = rotation[:, 0] - points_a = signs @ rotation.T - points_b = points_a + 4.0 * direction - instances_a = [{"pts": points_a, "n": len(points_a)}] - instances_b = [{"pts": points_b, "n": len(points_b)}] - - distance = module.answer_closest_distance(instances_a, instances_b) - canonical = module._canonical_answer_closest_distance(instances_a, instances_b) - - np.testing.assert_allclose(distance, 2.0, atol=1e-5) - np.testing.assert_allclose(canonical, 2.0, atol=1e-5) - - -def test_projected_center_line_distance_uses_robust_directional_extents(): - module = loader.load_hypothesis( - "Estimate Absolute Object Distance Along the Line Between Object Centers" - ) - points_a = np.stack( - [np.linspace(-1.0, 1.0, 101), np.zeros(101), np.zeros(101)], axis=1 - ).astype(np.float32) - points_b = np.stack( - [np.linspace(4.0, 6.0, 101), np.zeros(101), np.zeros(101)], axis=1 - ).astype(np.float32) - instances_a = [{"pts": points_a, "n": len(points_a)}] - instances_b = [{"pts": points_b, "n": len(points_b)}] - expected = np.percentile(points_b[:, 0], 2.0) - np.percentile(points_a[:, 0], 98.0) - - projected = module._projected_center_line_distance(points_a, points_b) - forward = module.answer_closest_distance(instances_a, instances_b) - reverse = module.answer_closest_distance(instances_b, instances_a) - canonical = module._canonical_answer_closest_distance(instances_a, instances_b) - - np.testing.assert_allclose(projected, expected) - np.testing.assert_allclose(reverse, forward) - np.testing.assert_allclose(canonical, forward) - - -def test_half_percentile_surface_distance_is_registered(): - module = loader.load_hypothesis( - "Measure Absolute Object Distance Using the 0.5th Surface Percentile" - ) - assert module.SURFACE_DISTANCE_PERCENTILE == 0.5 - - -def test_quarter_percentile_surface_distance_is_registered(): - module = loader.load_hypothesis( - "Measure Absolute Object Distance Using the 0.25th Surface Percentile" - ) - assert module.SURFACE_DISTANCE_PERCENTILE == 0.25 - - -def test_maximum_object_size_scale_increases_dimensions_by_ten_percent(): - baseline = loader.load_hypothesis( - "Estimate Object Size From the Maximum Across Frames" - ) - scaled = loader.load_hypothesis( - "Increase Maximum Object Size Estimates by 10 Percent" - ) - points = np.stack( - [np.linspace(0.0, 1.0, 20), np.zeros(20), np.zeros(20)], axis=1 - ).astype(np.float32) - baseline_size, baseline_dims = baseline.aggregate_frame_extent([points], None) - scaled_size, scaled_dims = scaled.aggregate_frame_extent([points], None) - - np.testing.assert_allclose(scaled_size, 1.10 * baseline_size) - np.testing.assert_allclose(scaled_dims, 1.10 * baseline_dims) - - -def test_maximum_object_size_scale_increases_dimensions_by_fifteen_percent(): - baseline = loader.load_hypothesis( - "Estimate Object Size From the Maximum Across Frames" - ) - scaled = loader.load_hypothesis( - "Increase Maximum Object Size Estimates by 15 Percent" - ) - points = np.stack( - [np.linspace(0.0, 1.0, 20), np.zeros(20), np.zeros(20)], axis=1 - ).astype(np.float32) - baseline_size, baseline_dims = baseline.aggregate_frame_extent([points], None) - scaled_size, scaled_dims = scaled.aggregate_frame_extent([points], None) - - np.testing.assert_allclose(scaled_size, 1.15 * baseline_size) - np.testing.assert_allclose(scaled_dims, 1.15 * baseline_dims) - - -def test_maximum_object_size_scale_increases_dimensions_by_twelve_and_a_half_percent(): - baseline = loader.load_hypothesis( - "Estimate Object Size From the Maximum Across Frames" - ) - scaled = loader.load_hypothesis( - "Increase Maximum Object Size Estimates by 12.5 Percent" - ) - points = np.stack( - [np.linspace(0.0, 1.0, 20), np.zeros(20), np.zeros(20)], axis=1 - ).astype(np.float32) - baseline_size, baseline_dims = baseline.aggregate_frame_extent([points], None) - scaled_size, scaled_dims = scaled.aggregate_frame_extent([points], None) - - np.testing.assert_allclose(scaled_size, 1.125 * baseline_size) - np.testing.assert_allclose(scaled_dims, 1.125 * baseline_dims) - - -def test_surface_distance_blend_keeps_eighty_percent_of_the_minimum(): - module = loader.load_hypothesis( - "Blend the Minimum Surface Distance With 20 Percent of the First Percentile" - ) - assert module.SURFACE_PERCENTILE_BLEND == 0.20 - - -def test_surface_distance_blend_keeps_ninety_percent_of_the_minimum(): - module = loader.load_hypothesis( - "Blend the Minimum Surface Distance With 10 Percent of the First Percentile" - ) - assert module.SURFACE_PERCENTILE_BLEND == 0.10 - - -def test_minimum_surface_distance_scale_reduces_estimates_by_five_percent(): - module = loader.load_hypothesis( - "Reduce Minimum Surface Distance Estimates by 5 Percent" - ) - assert module.SURFACE_DISTANCE_SCALE == 0.95 - - -def test_inconsistent_frame_rejection_removes_a_distant_observation(): - module = loader.load_hypothesis( - "Reject Geometrically Inconsistent Frame Observations Before Measuring Object Distance" - ) - observations = [ - np.stack([np.linspace(0.0, 1.0, 20), np.zeros(20), np.zeros(20)], axis=1) - + offset - for offset in (0.0, 0.01, -0.01, 20.0) - ] - np.testing.assert_array_equal( - module._consistent_observation_indices(observations), [0, 1, 2] - ) - - -def test_consistent_frame_pair_distance_uses_lower_quartile(): - module = loader.load_hypothesis( - "Measure Object Distance From the Lower Quartile of Consistent Frame Pairs" - ) - first = {"pts": np.asarray([[0.0, 0.0, 0.0]], np.float32)} - second = { - "pts": np.asarray([[1.0, 0.0, 0.0]], np.float32), - "distance_observations": [ - np.asarray([[distance, 0.0, 0.0]], np.float32) - for distance in (1.0, 2.0, 3.0, 4.0) - ], - } - distances = module._observation_pair_distances(first, second) - np.testing.assert_allclose(np.percentile(distances, 25.0), 1.75) diff --git a/tests/test_experiments/test_launch.py b/tests/test_experiments/test_launch.py deleted file mode 100644 index 7ce89db24ac929820a0df3a7701f0a7de172a6f1..0000000000000000000000000000000000000000 --- a/tests/test_experiments/test_launch.py +++ /dev/null @@ -1,34 +0,0 @@ -import os - -import pytest - -from experiments import launch - - -def test_cpu_override(monkeypatch): - monkeypatch.setenv("VSI_CPU_WORKERS", "7") - assert launch.available_cpu_count() == 7 - - -def test_invalid_cpu_override(monkeypatch): - monkeypatch.setenv("VSI_CPU_WORKERS", "0") - with pytest.raises(ValueError): - launch.available_cpu_count() - - -def test_thread_budget_sets_all_numerical_controls(monkeypatch): - for name in ( - "OMP_NUM_THREADS", - "MKL_NUM_THREADS", - "OPENBLAS_NUM_THREADS", - "NUMEXPR_NUM_THREADS", - "VSI_KD_WORKERS", - ): - monkeypatch.delenv(name, raising=False) - launch.configure_numerical_threads(3) - assert os.environ["VSI_KD_WORKERS"] == "3" - assert os.environ["OMP_NUM_THREADS"] == "3" - - -def test_empty_batch_does_not_spawn_workers(): - assert launch.launch({}, [], workers=0) == {"built": 0, "loaded": 0, "failed": 0} diff --git a/tests/test_experiments/test_loader.py b/tests/test_experiments/test_loader.py deleted file mode 100644 index 0315bece622538fe473e794659b852e3361dbd10..0000000000000000000000000000000000000000 --- a/tests/test_experiments/test_loader.py +++ /dev/null @@ -1,20 +0,0 @@ -import pytest - -from experiments import loader - - -def test_lists_human_readable_hypotheses(): - names = loader.list_hypotheses() - assert "Compute Gravity Before Building Object Instances" in names - assert all(not name.endswith(".py") for name in names) - - -def test_loads_filename_with_spaces(): - module = loader.load_hypothesis("Compute Gravity Before Building Object Instances") - assert callable(module.build_spatial_code) - assert callable(module.dump_spatial_code) - - -def test_missing_hypothesis_has_clear_error(): - with pytest.raises(FileNotFoundError, match="hypothesis does not exist"): - loader.load_hypothesis("This Does Not Exist") diff --git a/tests/test_experiments/test_run.py b/tests/test_experiments/test_run.py deleted file mode 100644 index 33e3fdb629479e9c241f3b16545f2122f0097dc6..0000000000000000000000000000000000000000 --- a/tests/test_experiments/test_run.py +++ /dev/null @@ -1,76 +0,0 @@ -import json -import sys - -from experiments import run - - -class FakeGeometry: - @staticmethod - def build_spatial_code(scene): - return {"scene": scene["scene"]}, None - - @staticmethod - def dump_spatial_code(code, path): - with open(path, "w", encoding="utf-8") as stream: - json.dump(code, stream) - - -def test_run_scene_routes_to_experiment_cache(monkeypatch, tmp_path): - output = tmp_path / "spatial.json" - monkeypatch.setattr(run.config, "spatial_code_path", lambda *args: output) - monkeypatch.setattr(run, "load_existing_geometry", lambda *args: {"scene": args[0]}) - monkeypatch.setattr(run.loader, "load_hypothesis", lambda name: FakeGeometry) - code, status, path = run.run_scene("scene0000_00", "A Hypothesis", frame_count=64) - assert status == "built" - assert path == output - assert json.loads(output.read_text()) == code == {"scene": "scene0000_00"} - - -def test_run_scene_reuses_existing_spatial_code(monkeypatch, tmp_path): - output = tmp_path / "spatial.json" - output.write_text('{"cached": true}') - monkeypatch.setattr(run.config, "spatial_code_path", lambda *args: output) - monkeypatch.setattr( - run, - "load_existing_geometry", - lambda *args: (_ for _ in ()).throw(AssertionError("source cache was read")), - ) - code, status, _ = run.run_scene("scene0000_00", "A Hypothesis") - assert status == "loaded" - assert code == {"cached": True} - - -def test_load_existing_geometry_adapts_native_caches_in_memory(monkeypatch, tmp_path): - da3 = tmp_path / "scene.pkl" - sam3 = tmp_path / "scene.pt" - da3.touch() - sam3.touch() - monkeypatch.setattr( - run.encoder_config, "cache_file", lambda *args: tmp_path / "missing.pkl.gz" - ) - monkeypatch.setattr(run.encoder_config, "da3_cache_file", lambda *args: da3) - monkeypatch.setattr(run.encoder_config, "sam3_cache_file", lambda *args: sam3) - monkeypatch.setattr( - run.adapters, "adapt", lambda *args, **kwargs: {"scene": kwargs["scene"]} - ) - monkeypatch.setattr(run.adapters, "validate", lambda geometry: geometry) - geometry = run.load_existing_geometry( - "scene0000_00", "metric", "uniform", "tracking", 64 - ) - assert geometry == {"scene": "scene0000_00"} - - -def test_da3_pickle_compatibility_installs_expected_class(monkeypatch): - monkeypatch.delitem(sys.modules, "depth_anything_3", raising=False) - monkeypatch.delitem(sys.modules, "depth_anything_3.specs", raising=False) - monkeypatch.delitem(sys.modules, "addict", raising=False) - monkeypatch.delitem(sys.modules, "addict.addict", raising=False) - run.install_da3_pickle_compatibility() - assert sys.modules["depth_anything_3.specs"].Prediction is run.CachedDA3Prediction - assert sys.modules["addict.addict"].Dict is run.CachedAddictDict - - -def test_cached_addict_dict_does_not_invent_pickle_hooks(): - value = run.CachedAddictDict(answer=42) - assert value.answer == 42 - assert not hasattr(value, "__setstate__") diff --git a/tests/test_harness/__init__.py b/tests/test_harness/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/tests/test_harness/conftest.py b/tests/test_harness/conftest.py deleted file mode 100644 index 8a801f94b60da603c80287f186e31c5d32012e99..0000000000000000000000000000000000000000 --- a/tests/test_harness/conftest.py +++ /dev/null @@ -1,12 +0,0 @@ -"""Shared import setup for this test package.""" - -from pathlib import Path -import sys - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - - -def pytest_configure(config): - config.option.importmode = "importlib" diff --git a/tests/test_harness/test_harness.py b/tests/test_harness/test_harness.py deleted file mode 100644 index e0bfccb2b7bf39e509d5f54905974d7e37555bdd..0000000000000000000000000000000000000000 --- a/tests/test_harness/test_harness.py +++ /dev/null @@ -1,7 +0,0 @@ -"""Tests for the top-level harness namespace.""" - -import harness - - -def test_harness_package_imports_without_side_effects(): - assert "direct VLM-inference harnesses" in harness.__doc__ diff --git a/tests/test_inference/conftest.py b/tests/test_inference/conftest.py deleted file mode 100644 index f9ec18b7b744f760331ab814b7613c31c48978b6..0000000000000000000000000000000000000000 --- a/tests/test_inference/conftest.py +++ /dev/null @@ -1,13 +0,0 @@ -"""Shared import setup for inference tests.""" - -from pathlib import Path -import sys - -ROOT = Path(__file__).resolve().parents[2] -for path in (ROOT, ROOT / "encoder"): - if str(path) not in sys.path: - sys.path.insert(0, str(path)) - - -def pytest_configure(config): - config.option.importmode = "importlib" diff --git a/tests/test_inference/test_adapters.py b/tests/test_inference/test_adapters.py deleted file mode 100644 index 312f368a630b14ae63691b036dc72e126bef42e3..0000000000000000000000000000000000000000 --- a/tests/test_inference/test_adapters.py +++ /dev/null @@ -1,216 +0,0 @@ -"""Tests for inference/adapters.py -- inference backend registry and adapter dispatch.""" - -import numpy as np -import pytest - -from inference import adapters - - -def test_sam3_adapter_accepts_tracking_modes(): - assert adapters.get_adapter("SAM3", tracking="tracking").tracking == "tracking" - assert ( - adapters.get_adapter("SAM3", tracking="no tracking").tracking == "no tracking" - ) - - -def test_metric_adapter_is_registered(): - assert adapters._ADAPTERS["DA3NESTED-GIANT-LARGE-1.1"].depth_variant == "metric" - - -def test_relative_adapter_is_registered(): - assert adapters._ADAPTERS["DA3-LARGE-1.1"].depth_variant == "relative" - - -@pytest.mark.parametrize("algorithm", ["1", "2", "3", "4", "5"]) -def test_selector_algorithm_dispatch_is_registered(algorithm): - assert algorithm in adapters._SELECTOR_ALGORITHMS - assert callable(adapters._SELECTOR_ALGORITHMS[algorithm]) - - -def test_selector_algorithm_defaults_to_five(monkeypatch): - import importlib - - monkeypatch.delenv("VSI_SELECTOR_ALGORITHM", raising=False) - reloaded = importlib.reload(adapters) - try: - assert reloaded.SELECTOR_ALGORITHM == "5" - finally: - importlib.reload(adapters) - - -def test_select_video_frame_indices_rejects_unknown_algorithm(monkeypatch, tmp_path): - monkeypatch.setattr(adapters, "SELECTOR_ALGORITHM", "99") - monkeypatch.setattr(adapters, "SELECTED_FRAMES_CACHE", tmp_path) - video = tmp_path / "scene.mp4" - video.write_bytes(b"fake video bytes") - with pytest.raises(ValueError, match="unknown selector algorithm"): - adapters.select_video_frame_indices(str(video)) - - -# Every constant that affects an algorithm's behavior must be part of -# _selector_config()'s fingerprint, or a cache built before a constant change gets -# silently served as "fresh" after the change -- this bit us twice while tuning -# algorithm 3 (GLITCH_THUMBNAIL_WIDTH, then GLITCH_MINIMUM_OWN_KEYPOINTS were both -# added to the algorithm without being added to the fingerprint). -_ALGORITHM_TUNABLE_CONSTANTS = { - "1": [ - "REDUNDANCY_SSIM_THRESHOLD", - "MINIMUM_ALIGNMENT_MATCHES", - "MINIMUM_ALIGNMENT_INLIER_RATIO", - "MINIMUM_VALID_OVERLAP_FRACTION", - ], - "2": [ - "BLUR_RELATIVE_MEDIAN_FRACTION", - "BLUR_ABSOLUTE_FLOOR", - "BLUR_CANONICAL_WIDTH", - "DARK_MEAN_THRESHOLD", - "BRIGHT_MEAN_THRESHOLD", - "LOW_CONTRAST_STD_THRESHOLD", - ], - "3": [ - "BLACK_PIXEL_LUMINANCE_THRESHOLD", - "BLACK_FRAME_PIXEL_RATIO_THRESHOLD", - "GLITCH_MAX_NEIGHBOR_COVISIBILITY", - "GLITCH_THUMBNAIL_WIDTH", - "GLITCH_MINIMUM_OWN_KEYPOINTS", - "MINIMUM_ALIGNMENT_MATCHES", - ], - "4": [ - "COVISIBILITY_OVERLAP_THRESHOLD", - "MINIMUM_ALIGNMENT_MATCHES", - "REDUNDANCY_SSIM_THRESHOLD", - ], - "5": [ - "BLUR_RELATIVE_MEDIAN_FRACTION", - "BLUR_ABSOLUTE_FLOOR", - "BLUR_CANONICAL_WIDTH", - "DARK_MEAN_THRESHOLD", - "BRIGHT_MEAN_THRESHOLD", - "LOW_CONTRAST_STD_THRESHOLD", - "COVISIBILITY_OVERLAP_THRESHOLD", - "MINIMUM_ALIGNMENT_MATCHES", - "REDUNDANCY_SSIM_THRESHOLD", - ], -} - - -@pytest.mark.parametrize( - ("algorithm", "constant_name"), - [ - (algorithm, name) - for algorithm, names in _ALGORITHM_TUNABLE_CONSTANTS.items() - for name in names - ], -) -def test_selector_config_reflects_every_tunable_constant( - monkeypatch, algorithm, constant_name -): - monkeypatch.setattr(adapters, "SELECTOR_ALGORITHM", algorithm) - before = adapters._selector_config() - original_value = getattr(adapters, constant_name) - monkeypatch.setattr(adapters, constant_name, original_value * 2 + 1) - after = adapters._selector_config() - assert after != before - - -def test_cache_is_invalidated_when_selector_config_changes(tmp_path, monkeypatch): - monkeypatch.setattr(adapters, "SELECTED_FRAMES_CACHE", tmp_path) - monkeypatch.setattr(adapters, "SELECTOR_ALGORITHM", "2") - video = tmp_path / "scene.mp4" - video.write_bytes(b"fake video bytes") - - adapters._cache_selected_frame_indices(str(video), [1, 2, 3]) - assert adapters._load_selected_frame_indices(str(video)) == [1, 2, 3] - - monkeypatch.setattr( - adapters, "BLUR_ABSOLUTE_FLOOR", adapters.BLUR_ABSOLUTE_FLOOR + 5 - ) - assert adapters._load_selected_frame_indices(str(video)) is None - - -def _write_synthetic_video(path, frames, fps=10): - cv2 = pytest.importorskip("cv2") - height, width = frames[0].shape[:2] - writer = cv2.VideoWriter( - str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height) - ) - for frame in frames: - writer.write(frame) - writer.release() - - -def _textured_frame(shape=(90, 160, 3), seed=0, circles=40): - cv2 = pytest.importorskip("cv2") - rng = np.random.default_rng(seed) - frame = np.zeros(shape, np.uint8) - for _ in range(circles): - x, y = int(rng.integers(0, shape[1])), int(rng.integers(0, shape[0])) - radius = int(rng.integers(3, 8)) - color = tuple(int(value) for value in rng.integers(50, 255, 3)) - cv2.circle(frame, (x, y), radius, color, -1) - return frame - - -def test_algorithm_3_catches_injected_corruption_without_false_positives(tmp_path): - cv2 = pytest.importorskip("cv2") - if not hasattr(cv2, "VideoWriter"): - pytest.skip("real OpenCV video I/O is not installed") - base = _textured_frame(seed=0) - rng = np.random.default_rng(1) - corrupt_frames = {20, 45} - frames = [ - ( - rng.integers(0, 255, base.shape, dtype=np.uint8) - if i in corrupt_frames - else base - ) - for i in range(60) - ] - path = tmp_path / "synthetic_corrupt.mp4" - _write_synthetic_video(path, frames) - - kept = set(adapters._select_indices_algorithm_3(str(path))) - discarded = set(range(len(frames))) - kept - - assert corrupt_frames.issubset(discarded) - assert discarded - corrupt_frames == set() - - -def test_algorithm_4_compresses_static_redundancy_at_least_as_well_as_algorithm_1( - tmp_path, -): - cv2 = pytest.importorskip("cv2") - if not hasattr(cv2, "VideoWriter"): - pytest.skip("real OpenCV video I/O is not installed") - base = _textured_frame(seed=2) - rng = np.random.default_rng(3) - # A static camera with tiny per-frame sensor noise -- exactly the appearance-level - # jitter that fragmented algorithm 1's SSIM-based groups on real static footage. - frames = [ - np.clip(base.astype(np.int16) + rng.integers(-3, 3, base.shape), 0, 255).astype( - np.uint8 - ) - for _ in range(80) - ] - path = tmp_path / "static_scene.mp4" - _write_synthetic_video(path, frames) - - kept1 = adapters._select_indices_algorithm_1(str(path)) - kept4 = adapters._select_indices_algorithm_4(str(path)) - - assert len(kept4) <= len(kept1) - - -def test_algorithm_5_output_is_subset_of_algorithm_2_output(tmp_path): - cv2 = pytest.importorskip("cv2") - if not hasattr(cv2, "VideoWriter"): - pytest.skip("real OpenCV video I/O is not installed") - base = _textured_frame(seed=4) - frames = [base for _ in range(60)] - path = tmp_path / "scene.mp4" - _write_synthetic_video(path, frames) - - kept2 = set(adapters._select_indices_algorithm_2(str(path))) - kept5 = set(adapters._select_indices_algorithm_5(str(path))) - - assert kept5.issubset(kept2) diff --git a/tests/test_inference/test_inference.py b/tests/test_inference/test_inference.py deleted file mode 100644 index 64cd4d1a885eee4011b7c2beaa2a4777c169b83a..0000000000000000000000000000000000000000 --- a/tests/test_inference/test_inference.py +++ /dev/null @@ -1,22 +0,0 @@ -"""Tests for inference/__init__.py and run.py -- model registry and cache path layout.""" - -from inference import adapters -from inference import run - - -def test_model_registry_uses_explicit_names(): - assert adapters.available_models() == ( - "DA3-LARGE-1.1", - "DA3NESTED-GIANT-LARGE-1.1", - "SAM3", - ) - - -def test_output_paths_include_frame_hierarchy(tmp_path, monkeypatch): - monkeypatch.setattr(run.inference_config, "CACHE_ROOT", tmp_path) - assert run.output_path( - "scene1", "SAM3", "uniform", "tracking", frame_count=64 - ).endswith("sam3/tracking/frames/uniform/64/scene1.pt") - assert run.output_path( - "scene1", "DA3NESTED-GIANT-LARGE-1.1", "uniform", frame_count=64 - ).endswith("depth-anything-3/metric/frames/uniform/64/scene1.pkl") diff --git a/tests/test_inference/test_init.py b/tests/test_inference/test_init.py deleted file mode 100644 index e6399f811281f53da00592dfeb59aa1ca10201e8..0000000000000000000000000000000000000000 --- a/tests/test_inference/test_init.py +++ /dev/null @@ -1,55 +0,0 @@ -"""Tests for inference package path helpers.""" - -from pathlib import Path - -import pytest - -import inference - - -def test_video_path_finds_exact_dataset_match(tmp_path, monkeypatch): - root = tmp_path / "VSI-Bench" - video = root / "scannet" / "scene1.mp4" - video.parent.mkdir(parents=True) - video.write_bytes(b"fake video") - monkeypatch.setattr(inference, "VSI_ROOT", root) - - assert inference.video_path("scene1") == str(video) - assert inference.video_path("scene1", "scannet") == str(video) - - -def test_video_path_reports_missing_unknown_and_ambiguous_datasets( - tmp_path, monkeypatch -): - root = tmp_path / "VSI-Bench" - for dataset in ("scannet", "arkitscenes"): - path = root / dataset / "scene1.mp4" - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(b"fake video") - monkeypatch.setattr(inference, "VSI_ROOT", root) - - with pytest.raises(ValueError, match="unknown VSI dataset"): - inference.video_path("scene1", "badset") - with pytest.raises(RuntimeError, match="multiple datasets"): - inference.video_path("scene1") - with pytest.raises(FileNotFoundError, match="searched"): - inference.video_path("missing", "scannet") - - -def test_cache_dir_helpers_validate_axes_and_include_dimensions(tmp_path, monkeypatch): - monkeypatch.setattr(inference, "CACHE_ROOT", tmp_path) - - assert inference.model_cache_dir( - "depth-anything-3", "uniform", 16, "metric" - ) == str(tmp_path / "depth-anything-3" / "metric" / "frames" / "uniform" / "16") - assert inference.sam3_cache_dir("no tracking", "selective", 8) == str( - tmp_path / "sam3" / "no tracking" / "frames" / "selective" / "8" - ) - assert inference.parse_sam3_frame_mode("uniform-tracking") == ( - "uniform", - "tracking", - ) - with pytest.raises(ValueError, match="frame count"): - inference.model_cache_dir("x", "uniform", 0) - with pytest.raises(ValueError, match="unknown tracking"): - inference.sam3_cache_dir("bad", "uniform") diff --git a/tests/test_inference/test_launch.py b/tests/test_inference/test_launch.py deleted file mode 100644 index f1a30d94ea430c3daf5579b41b16641fd2a31713..0000000000000000000000000000000000000000 --- a/tests/test_inference/test_launch.py +++ /dev/null @@ -1,7 +0,0 @@ -"""Tests for inference/launch.py -- multi-GPU/CPU batch driver.""" - -from inference import launch - - -def test_launcher_imports(): - assert callable(launch.main) diff --git a/tests/test_inference/test_prompts.py b/tests/test_inference/test_prompts.py deleted file mode 100644 index 294e9eb58299911e813238432e7102b13b329a56..0000000000000000000000000000000000000000 --- a/tests/test_inference/test_prompts.py +++ /dev/null @@ -1,30 +0,0 @@ -"""Tests for inference/prompts.py -- dataset object prompt selection.""" - -from pathlib import Path - -import pytest - -from inference import prompts - - -def test_dataset_from_video_path_matches_one_dataset_case_insensitively(): - assert ( - prompts.dataset_from_video_path(Path("/data/VSI-Bench/ScanNet/scene.mp4")) - == "scannet" - ) - - -def test_dataset_from_video_path_rejects_missing_or_ambiguous_dataset(): - with pytest.raises(ValueError, match="cannot determine"): - prompts.dataset_from_video_path("/data/unknown/scene.mp4") - with pytest.raises(ValueError, match="cannot determine"): - prompts.dataset_from_video_path("/data/scannet/arkitscenes/scene.mp4") - - -def test_object_prompts_are_immutable_and_dataset_specific(): - scannet = prompts.object_prompts_for_video("/data/scannet/scene.mp4") - arkit = prompts.object_prompts_for_video("/data/arkitscenes/scene.mp4") - assert isinstance(scannet, tuple) - assert "chair" in scannet - assert "dishwasher" in arkit - assert scannet is prompts.DATASET_OBJECT_PROMPTS["scannet"] diff --git a/tests/test_inference/test_run.py b/tests/test_inference/test_run.py deleted file mode 100644 index e6655345b870f117520e3aab04f58696e93e79c6..0000000000000000000000000000000000000000 --- a/tests/test_inference/test_run.py +++ /dev/null @@ -1,41 +0,0 @@ -"""Optional real-model validation; enable with VSI_RUN_GPU_TESTS=1.""" - -import json -import os - -import pytest - -from inference import adapters -from inference import run - - -@pytest.mark.skipif( - os.environ.get("VSI_RUN_GPU_TESTS") != "1", - reason="set VSI_RUN_GPU_TESTS=1 to run real SegVGGT inference", -) -def test_real_segvggt_scene_preserves_native_prediction_dictionary(tmp_path): - torch = pytest.importorskip("torch") - with open(run.inference_config.JSONL) as manifest: - scene = str(json.loads(next(manifest))["scene_name"]) - adapter = adapters.get_adapter("segvggt") - adapter.load_model("cuda:0") - output = tmp_path / f"{scene}.pt" - adapter.run_scene( - run.inference_config.video_path(scene), - str(output), - run.inference_config.FRAMES_PER_VIDEO, - ) - cache = torch.load(output, map_location="cpu", weights_only=False) - assert isinstance(cache, dict) - assert { - "pose_enc", - "depth", - "world_points", - "instance_maps", - "instance_labels", - }.issubset(cache) - assert all( - value.device.type == "cpu" - for value in cache.values() - if isinstance(value, torch.Tensor) - ) diff --git a/tests/test_symbolic/conftest.py b/tests/test_symbolic/conftest.py deleted file mode 100644 index 51af0cf8764c55fbb1a8a526d1da69f55f1a2265..0000000000000000000000000000000000000000 --- a/tests/test_symbolic/conftest.py +++ /dev/null @@ -1,83 +0,0 @@ -"""Shared import setup and fixtures for symbolic tests.""" - -import importlib.util -from pathlib import Path -from types import ModuleType -import sys - -import pytest - -ROOT = Path(__file__).resolve().parents[2] -SYMBOLIC_ROOT = ROOT / "symbolic" -ENCODER_ROOT = ROOT / "encoder" - - -def pytest_configure(config): - config.option.importmode = "importlib" - - -if str(SYMBOLIC_ROOT) not in sys.path: - sys.path.insert(0, str(SYMBOLIC_ROOT)) -sys.modules.setdefault("utils", ModuleType("utils")) - -launch_spec = importlib.util.spec_from_file_location( - "symbolic_launch_tests", SYMBOLIC_ROOT / "launch.py" -) -symbolic_launch = importlib.util.module_from_spec(launch_spec) -sys.modules["symbolic_launch_tests"] = symbolic_launch -launch_spec.loader.exec_module(symbolic_launch) -sys.modules["symbolic_run_tests"] = symbolic_launch.symbolic_run -sys.modules["symbolic_solver_tests"] = symbolic_launch.symbolic_run.sym - -if str(SYMBOLIC_ROOT) in sys.path: - sys.path.remove(str(SYMBOLIC_ROOT)) -if str(ENCODER_ROOT) not in sys.path: - sys.path.insert(0, str(ENCODER_ROOT)) - - -@pytest.fixture -def spatial_code(): - def object_record(x, y, size="1.0 meters", count=1): - return { - "count": count, - "instances": [ - { - "position": { - "x coordinate": f"{x} meters", - "y coordinate": f"{y} meters", - "height above floor": "0.5 meters", - }, - "longest dimension": size, - } - ], - } - - return { - "objects": { - "chair": object_record(0, 0, "0.8 meters", count=2), - "table": object_record(0, 1, "1.2 meters"), - "lamp": object_record(-1, 1, "0.4 meters"), - "sofa": object_record(1, 1, "2.0 meters"), - }, - "room": {"floor area": "12.5 square meters"}, - "appearance order": ["chair", "table", "lamp", "sofa"], - "closest classes distance meters from": { - "chair": { - "table": {"distance": "1.0 meters", "closeness rank": 1}, - "lamp": {"distance": "1.4 meters", "closeness rank": 2}, - "sofa": {"distance": "1.5 meters", "closeness rank": 3}, - }, - # Ranks deliberately order lamp < sofa < chair (matching these distances): - # answer_object_rel_distance reads the rank field, not the distance values - # (since the 2026-07-25 second amendment the printed distance is the - # corrected primary-instance value, which may legitimately disagree with - # the raw-min rank order), so the ranks are what the test exercises. - "table": { - "chair": {"distance": "1.0 meters", "closeness rank": 3}, - "lamp": {"distance": "0.8 meters", "closeness rank": 1}, - "sofa": {"distance": "0.9 meters", "closeness rank": 2}, - }, - "lamp": {"table": {"distance": "0.8 meters", "closeness rank": 1}}, - "sofa": {"table": {"distance": "0.9 meters", "closeness rank": 1}}, - }, - } diff --git a/tests/test_symbolic/test_adapters.py b/tests/test_symbolic/test_adapters.py deleted file mode 100644 index f90297823b1b66aab9ed2b3c38a9199e6445bb12..0000000000000000000000000000000000000000 --- a/tests/test_symbolic/test_adapters.py +++ /dev/null @@ -1,237 +0,0 @@ -"""Tests for symbolic/adapters.py -- compact/explicit spatial-code adaptation.""" - -import math - -import pytest - -import symbolic_solver_tests as solver -from symbolic import adapters - - -def _instance(center, dimensions, first_time=0.0, orientation=None): - orientation = orientation or [[1, 0, 0], [0, 1, 0], [0, 0, 1]] - return { - "3D oriented bounding box": { - "3D oriented bounding box center coordinates": center, - "3D oriented bounding box dimensions": dimensions, - "3D oriented bounding box orientation unit vectors": orientation, - }, - "first visible time": first_time, - } - - -def _compact_code(): - return { - "spatial code schema": {"objects": {}, "room": {}}, - "objects": { - "chair": [ - _instance([0, 0, 0.5], [2, 2, 1], first_time=1.0), - _instance([10, 0, 0.5], [2, 2, 1], first_time=0.5), - ], - "table": [_instance([4, 0, 0.5], [2, 2, 1], first_time=2.0)], - "lamp": [_instance([4, 4, 0.5], [1, 1, 1], first_time=3.0)], - }, - "room": { - "floor boundary polygons": [ - { - "outer boundary coordinates": [[0, 0], [4, 0], [4, 4], [0, 4]], - "interior hole boundary coordinates": [ - [[1, 1], [3, 1], [3, 3], [1, 3]] - ], - } - ] - }, - } - - -def test_oriented_box_distance_is_surface_to_surface(): - first = _instance([0, 0, 0], [2, 2, 2]) - separated = _instance([5, 0, 0], [2, 2, 2]) - touching = _instance([2, 0, 0], [2, 2, 2]) - assert adapters.oriented_box_distance(first, separated) == pytest.approx(3.0) - assert adapters.oriented_box_distance(first, touching) == pytest.approx(0.0) - - -def test_oriented_box_distance_uses_corresponding_rotated_axes(): - diagonal = math.sqrt(0.5) - rotated = _instance( - [0, 0, 0], - [4, 2, 2], - orientation=[ - [diagonal, diagonal, 0], - [-diagonal, diagonal, 0], - [0, 0, 1], - ], - ) - point = _instance([4, 0, 0], [0, 0, 0]) - expected = math.sqrt((4 - 3 / math.sqrt(2)) ** 2 + (1 / math.sqrt(2)) ** 2) - assert adapters.oriented_box_distance(rotated, point) == pytest.approx( - expected, abs=1e-7 - ) - - -def test_compact_adapter_derives_solver_values_from_primitives(): - adapted = adapters.adapt_spatial_code(_compact_code(), "compact") - assert adapted["objects"]["chair"]["count"] == 2 - assert adapted["objects"]["chair"]["instances"][0]["longest dimension"] == 2.0 - assert adapted["appearance order"] == ["chair", "table", "lamp"] - assert adapted["room"]["floor area"] == 12.0 - chair_to_table = adapted["closest classes distance meters from"]["chair"]["table"] - assert chair_to_table["distance"] == pytest.approx(2.0) - assert chair_to_table["closeness rank"] == 1 - - -def test_compact_adapter_treats_none_first_visible_time_as_unknown(): - code = _compact_code() - code["objects"]["lamp"][0]["first visible time"] = None - adapted = adapters.adapt_spatial_code(code, "compact") - # "lamp" has no timed instance at all -> sorts after every timed class, but still - # appears (not dropped) in "appearance order". - assert adapted["appearance order"] == ["chair", "table", "lamp"] - - -def test_compact_adapter_ignores_none_instances_within_a_partially_timed_class(): - code = _compact_code() - code["objects"]["chair"][0]["first visible time"] = None - adapted = adapters.adapt_spatial_code(code, "compact") - # chair's other instance is still timed at 0.5 -> chair keeps its real rank. - assert adapted["appearance order"] == ["chair", "table", "lamp"] - - -def test_symbolic_solver_answers_numeric_categories_from_compact_code(): - adapted = adapters.adapt_spatial_code(_compact_code()) - assert ( - solver.answer( - "object_counting", "How many chair(s) are in this room?", None, adapted - ) - == 2 - ) - assert ( - solver.answer( - "object_size_estimation", - "What is the longest dimension of the table, measured in centimeters?", - None, - adapted, - ) - == 200.0 - ) - assert ( - solver.answer( - "object_abs_distance", - "What is the distance between the chair and the table (in meters)?", - None, - adapted, - ) - == 2.0 - ) - assert ( - solver.answer( - "room_size_estimation", "What is the size of this room?", None, adapted - ) - == 12.0 - ) - - -def test_symbolic_solver_answers_relative_distance_and_order_from_compact_code(): - adapted = adapters.adapt_spatial_code(_compact_code()) - assert ( - solver.answer( - "object_rel_distance", - "Which of these objects is closest to the table?", - ["A. lamp", "B. chair"], - adapted, - ) - == "B" - ) - assert ( - solver.answer( - "obj_appearance_order", - "What is the first-time appearance order of the categories?", - ["A. lamp, table, chair", "B. chair, table, lamp"], - adapted, - ) - == "B" - ) - - -def test_symbolic_solver_answers_all_direction_levels_from_compact_code(): - adapted = adapters.adapt_spatial_code(_compact_code()) - question = ( - "If I am standing by the chair and facing the table, is the lamp to my left?" - ) - assert ( - solver.answer( - "object_rel_direction_easy", - question, - ["A. left", "B. right"], - adapted, - ) - == "A" - ) - assert ( - solver.answer( - "object_rel_direction_medium", - question, - ["A. back", "B. right", "C. left"], - adapted, - ) - == "C" - ) - assert ( - solver.answer( - "object_rel_direction_hard", - question, - ["A. front-left", "B. front-right", "C. back-left", "D. back-right"], - adapted, - ) - == "A" - ) - - -def test_symbolic_solver_answers_route_planning_from_compact_code(): - adapted = adapters.adapt_spatial_code(_compact_code()) - question = ( - "You are a robot beginning at the chair facing the table. Actions: " - "1. Go forward until the table 2. [please fill in] " - "3. Go forward until the lamp." - ) - assert ( - solver.answer( - "route_planning", - question, - ["A. Turn Left", "B. Turn Right", "C. Turn Back"], - adapted, - ) - == "A" - ) - - -def test_explicit_adapter_preserves_existing_solver_shape(spatial_code): - assert adapters.adapt_spatial_code(spatial_code, "explicit") is spatial_code - - -def test_adapter_rejects_format_mismatch(): - with pytest.raises(ValueError, match="expected 'explicit'"): - adapters.adapt_spatial_code(_compact_code(), "explicit") - - -def test_floor_area_sums_disconnected_polygons_and_subtracts_all_holes(): - polygons = [ - { - "outer boundary coordinates": [[0, 0], [5, 0], [5, 4], [0, 4]], - "interior hole boundary coordinates": [ - [[1, 1], [2, 1], [2, 2], [1, 2]], - [[3, 1], [4, 1], [4, 3], [3, 3]], - ], - }, - { - "outer boundary coordinates": [[10, 0], [13, 0], [13, 2], [10, 2]], - "interior hole boundary coordinates": [], - }, - ] - assert adapters._floor_area(polygons) == 23.0 - - -def test_polygon_area_implicitly_closes_ordered_boundary(): - boundary = [[0.25, 0.5], [2.75, 0.5], [2.75, 2.0], [0.25, 2.0]] - assert adapters._polygon_area(boundary) == 3.75 diff --git a/tests/test_symbolic/test_launch.py b/tests/test_symbolic/test_launch.py deleted file mode 100644 index c1a00d7198ff8fbea1ad336e94ac4dea5e31c6fc..0000000000000000000000000000000000000000 --- a/tests/test_symbolic/test_launch.py +++ /dev/null @@ -1,7 +0,0 @@ -"""Tests for symbolic/launch.py -- multi-scene orchestrator.""" - -from symbolic import launch - - -def test_symbolic_launcher_imports(): - assert callable(launch.main) diff --git a/tests/test_symbolic/test_run.py b/tests/test_symbolic/test_run.py deleted file mode 100644 index 23ae0361904a24257318f199b177e27bf014735f..0000000000000000000000000000000000000000 --- a/tests/test_symbolic/test_run.py +++ /dev/null @@ -1,110 +0,0 @@ -"""Tests for symbolic/run.py -- spatial-code selection, fetch, and result writing.""" - -import json - -import pytest - -from symbolic import run - - -def test_symbolic_selection_uses_new_hierarchy(tmp_path, monkeypatch): - monkeypatch.setattr(run, "SPATIAL_CODES_ROOT", str(tmp_path)) - run.select_spatial_codes("metric", "uniform", "no tracking", 64, "explicit") - assert run.SPATIAL_CODES_DIR.endswith("no tracking/frames/uniform/64/explicit") - assert run.results_dir_for_selection().endswith( - "no tracking/frames/uniform/64/explicit" - ) - - -def test_symbolic_video_selection_uses_encoder_hierarchy(tmp_path, monkeypatch): - monkeypatch.setattr(run, "SPATIAL_CODES_ROOT", str(tmp_path)) - run.select_spatial_codes("metric", "video", "no tracking", None, "explicit") - assert run.SPATIAL_CODES_DIR.endswith("no tracking/video/explicit") - assert run.results_dir_for_selection().endswith("no tracking/video/explicit") - assert run.SPATIAL_CODES_INPUT == "video" - assert run.SPATIAL_CODES_FRAMES is None - - -def test_symbolic_selection_isolates_compact_codes(tmp_path, monkeypatch): - monkeypatch.setattr(run, "SPATIAL_CODES_ROOT", str(tmp_path)) - run.select_spatial_codes("relative", "selective", "tracking", 96, "compact") - assert run.SPATIAL_CODES_DIR.endswith("tracking/frames/selective/96/compact") - assert run.SPATIAL_CODES_FORMAT == "compact" - - -def test_select_ground_truth_spatial_codes_points_at_the_ground_truth_directory( - tmp_path, monkeypatch -): - monkeypatch.setattr(run, "SPATIAL_CODES_ROOT", str(tmp_path)) - run.select_ground_truth_spatial_codes("compact") - assert run.SPATIAL_CODES_DIR.endswith("ground truth/compact") - assert run.SPATIAL_CODES_FORMAT == "compact" - assert run.SPATIAL_CODES_GROUND_TRUTH is True - - -def test_select_ground_truth_spatial_codes_rejects_unknown_format( - tmp_path, monkeypatch -): - monkeypatch.setattr(run, "SPATIAL_CODES_ROOT", str(tmp_path)) - with pytest.raises(ValueError, match="unknown spatial-code format"): - run.select_ground_truth_spatial_codes("bogus") - - -def test_results_dir_for_selection_uses_ground_truth_layout(tmp_path, monkeypatch): - monkeypatch.setattr(run, "SPATIAL_CODES_ROOT", str(tmp_path)) - monkeypatch.setattr(run, "RESULTS_DIR", str(tmp_path / "results")) - run.select_ground_truth_spatial_codes("explicit") - assert run.results_dir_for_selection() == str( - tmp_path / "results" / "ground truth" / "explicit" - ) - - -def test_select_spatial_codes_clears_ground_truth_flag(tmp_path, monkeypatch): - monkeypatch.setattr(run, "SPATIAL_CODES_ROOT", str(tmp_path)) - run.select_ground_truth_spatial_codes("explicit") - assert run.SPATIAL_CODES_GROUND_TRUTH is True - run.select_spatial_codes("metric", "uniform", "tracking", 32, "compact") - assert run.SPATIAL_CODES_GROUND_TRUTH is False - - -def test_write_question_result_nulls_perception_fields_under_ground_truth( - tmp_path, monkeypatch -): - monkeypatch.setattr(run, "SPATIAL_CODES_ROOT", str(tmp_path)) - monkeypatch.setattr(run, "RESULTS_DIR", str(tmp_path / "results")) - run.select_ground_truth_spatial_codes("explicit") - pq = { - "question_id": 1, - "dataset": "scannet", - "question_type": "object_counting", - "question": "How many chairs?", - "options": None, - "engine_answer": 4, - "ground_truth": "4", - "score": 1.0, - } - path = run.write_question_result("scene1", pq, code={"objects": {}}) - record = json.loads(open(path).read()) - assert record["condition"] == "ground truth:explicit" - assert record["depth"] is None - assert record["tracking"] is None - assert record["input"] is None - assert record["number_of_frames"] is None - assert record["spatial_code_model"] is None - assert record["spatial_code_format"] == "explicit" - - -def test_fetch_spatial_code_uses_selected_format_adapter(tmp_path, monkeypatch): - path = tmp_path / "scene.json" - path.write_text(json.dumps({"objects": {}})) - monkeypatch.setattr(run, "SPATIAL_CODES_DIR", str(tmp_path)) - monkeypatch.setattr(run, "SPATIAL_CODES_FORMAT", "explicit") - seen = {} - - def fake_adapter(code, expected_format): - seen.update(code=code, expected_format=expected_format) - return {"adapted": True} - - monkeypatch.setattr(run.adapters, "adapt_spatial_code", fake_adapter) - assert run.fetch_spatial_code("scene") == {"adapted": True} - assert seen == {"code": {"objects": {}}, "expected_format": "explicit"} diff --git a/tests/test_symbolic/test_solver.py b/tests/test_symbolic/test_solver.py deleted file mode 100644 index f619d64451ad1e90cfda2cc8d36bc9da1b03c1ea..0000000000000000000000000000000000000000 --- a/tests/test_symbolic/test_solver.py +++ /dev/null @@ -1,190 +0,0 @@ -"""Tests for symbolic/solver.py -- deterministic VSI-Bench question answering.""" - -import pytest - -import symbolic_solver_tests as solver - - -def test_unit_parsers_accept_strings_and_numbers(): - assert solver._parse_meters("-1.25 meters") == -1.25 - assert solver._parse_square_meters("12.5 square meters") == 12.5 - assert solver._parse_meters(3) == 3.0 - with pytest.raises(ValueError, match="could not parse"): - solver._parse_meters("unknown") - - -def test_direct_numeric_answers(spatial_code): - assert ( - solver.answer( - "object_counting", "How many chair(s) are in this room?", None, spatial_code - ) - == 2 - ) - assert ( - solver.answer( - "object_size_estimation", - "What is the longest dimension of the table, measured in centimeters?", - None, - spatial_code, - ) - == 120.0 - ) - assert ( - solver.answer( - "room_size_estimation", "What is the size of this room?", None, spatial_code - ) - == 12.5 - ) - assert ( - solver.answer( - "object_abs_distance", - "What is the distance between the chair and the table (in meters)?", - None, - spatial_code, - ) - == 1.0 - ) - - -def test_multiple_choice_distance_and_order_answers(spatial_code): - assert ( - solver.answer( - "object_rel_distance", - "Which of these objects is closest to the table?", - ["A. sofa", "B. lamp", "C. chair"], - spatial_code, - ) - == "B" - ) - assert ( - solver.answer( - "obj_appearance_order", - "What is the first-time appearance order of the categories?", - ["A. table, chair, lamp", "B. chair, table, lamp"], - spatial_code, - ) - == "B" - ) - - -def test_direction_answers_use_floor_coordinates(spatial_code): - question = ( - "If I am standing by the chair and facing the table, is the lamp to my left?" - ) - assert ( - solver.answer( - "object_rel_direction_hard", - question, - ["A. front-left", "B. front-right", "C. back-left", "D. back-right"], - spatial_code, - ) - == "A" - ) - assert ( - solver.answer( - "object_rel_direction_easy", - question, - ["A. left", "B. right"], - spatial_code, - ) - == "A" - ) - - -def test_route_planning_chains_turns(spatial_code): - question = ( - "You are a robot beginning at the chair facing the table. Actions: " - "1. Go forward until the table 2. [please fill in] " - "3. Go forward until the lamp." - ) - assert ( - solver.answer( - "route_planning", - question, - ["A. Turn Left", "B. Turn Right", "C. Turn Back"], - spatial_code, - ) - == "A" - ) - - -def test_dispatch_returns_none_for_unknown_or_missing_data(spatial_code): - assert solver.answer("unknown", "question", None, spatial_code) is None - assert ( - solver.answer( - "object_counting", - "How many cabinet(s) are in this room?", - None, - spatial_code, - ) - == 0 - ) - assert solver.pairwise_swap_distance(["a", "b", "c"], ["b", "a", "c"]) == 1 - assert solver.pairwise_swap_distance(["a"], ["b"]) is None - - -def test_answer_snapshots_operation_counts_per_question(): - """H25 instrumentation: LAST_ANSWER_OPS reflects only the LAST question, and a - multi-step distance question costs strictly more operations than a pure count - lookup. Counting must never change any answer (every other test in this file - still passing is the guarantee).""" - from symbolic import adapters, solver - - code = adapters.adapt_spatial_code( - { - "spatial code schema": {}, - "objects": { - "chair": [ - { - "3D oriented bounding box": { - "3D oriented bounding box center coordinates": [ - 0.0, - 0.0, - 0.5, - ], - "3D oriented bounding box dimensions": [1.0, 1.0, 1.0], - "3D oriented bounding box orientation unit vectors": [ - [1.0, 0.0, 0.0], - [0.0, 0.0, 1.0], - [0.0, -1.0, 0.0], - ], - }, - "first visible time": 0.0, - } - ], - "table": [ - { - "3D oriented bounding box": { - "3D oriented bounding box center coordinates": [ - 3.0, - 0.0, - 0.5, - ], - "3D oriented bounding box dimensions": [2.0, 1.0, 1.0], - "3D oriented bounding box orientation unit vectors": [ - [1.0, 0.0, 0.0], - [0.0, 0.0, 1.0], - [0.0, -1.0, 0.0], - ], - }, - "first visible time": 1.0, - } - ], - }, - "room": {"floor boundary polygons": []}, - } - ) - - solver.answer("object_counting", "How many chair(s) are in this room?", None, code) - counting_ops = dict(solver.LAST_ANSWER_OPS) - assert counting_ops["total"] >= 1 - - solver.answer( - "object_abs_distance", - "Measuring from the closest point of each object, what is the direct distance " - "between the chair and the table (in meters)?", - None, - code, - ) - distance_ops = dict(solver.LAST_ANSWER_OPS) - assert distance_ops["total"] > counting_ops["total"] diff --git a/tests/test_symbolic/test_symbolic.py b/tests/test_symbolic/test_symbolic.py deleted file mode 100644 index ab7773979db0aa36fe0191f0d64ae79ef183f6a0..0000000000000000000000000000000000000000 --- a/tests/test_symbolic/test_symbolic.py +++ /dev/null @@ -1,13 +0,0 @@ -"""Folder-level contract tests for the symbolic package.""" - -import symbolic_launch_tests as launch -import symbolic_run_tests as run -import symbolic_solver_tests as solver - - -def test_symbolic_folder_modules_are_wired_together(): - assert launch.symbolic_run is run - assert run.sym is solver - assert callable(run.score_scene) - assert callable(launch.run_all) - assert callable(solver.answer)