diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..b3e6dee61311f2de0e466b631d7d133c0c3c98fe --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,48 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_A/conftest.py b/tests/test_A/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..9b2e5b391443b0e130a6ef1a62715ad5dac8a90d --- /dev/null +++ b/tests/test_A/conftest.py @@ -0,0 +1,12 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..9a9f5e65a520f43ba4ef2d9f6457c2690a2e8a39 --- /dev/null +++ b/tests/test_A/test_A.py @@ -0,0 +1,68 @@ +"""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(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_explicit_budget_overrides_are_preserved(): + args = Namespace(reasoning_budget=1024, force_budget=8) + A.resolve_protocol_budgets(ArgumentParser(), args) + assert args.reasoning_budget == 1024 + assert args.force_budget == 8 + + +@pytest.mark.parametrize("flag", ["reasoning_budget", "force_budget"]) +def test_nonpositive_budget_overrides_are_rejected(flag): + args = Namespace(reasoning_budget=None, force_budget=None) + setattr(args, flag, 0) + 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 new file mode 100644 index 0000000000000000000000000000000000000000..72483e70c8437eb054776910c046d9b4e119356b --- /dev/null +++ b/tests/test_A/test_frames.py @@ -0,0 +1,79 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..8aa32cd0de235f0e9ecfffe4161da78cae382df9 --- /dev/null +++ b/tests/test_A/test_init.py @@ -0,0 +1,62 @@ +"""Tests for harness/A/__init__.py -- shared config constants.""" + +from pathlib import Path + +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_root_results(): + assert A.RESULTS_DIR == Path("/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 new file mode 100644 index 0000000000000000000000000000000000000000..a324b60ddafd730667795b914b85b9b9a3dc0952 --- /dev/null +++ b/tests/test_A/test_launch.py @@ -0,0 +1,90 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..6d4a419461bbaf2942f880322820b3425333ad95 --- /dev/null +++ b/tests/test_A/test_models.py @@ -0,0 +1,114 @@ +"""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 numpy as np +import pytest + +from harness import A +from harness.A import models as vlm_models + + +def test_all_four_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_decode_new_tokens_preserves_clean_and_raw_text(): + adapter = vlm_models.get_adapter("qwen3.5-2b") + + class Processor: + def decode(self, token_ids, skip_special_tokens): + if skip_special_tokens: + return "step one, step two, answer B" + return "step one, step twoB" + + adapter.processor = Processor() + token_ids, hit_limit, text, raw = adapter._decode_new_tokens( + np.array([[10, 11, 21, 22, 2]]), 2, 2048, [2] + ) + assert token_ids == [21, 22, 2] + assert hit_limit is False + assert text == "step one, step two, answer B" + assert raw == "step one, step twoB" + + +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 new file mode 100644 index 0000000000000000000000000000000000000000..2f4462857d5e22fd5c3d8f495195466f86812f1d --- /dev/null +++ b/tests/test_A/test_prompts.py @@ -0,0 +1,57 @@ +"""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 vsi_prompts.STEP_BY_STEP_REASONING_PROMPT in 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 vsi_prompts.STEP_BY_STEP_REASONING_PROMPT in 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 new file mode 100644 index 0000000000000000000000000000000000000000..e21c9c3f20c7aec452b364f72044e5290f40f942 --- /dev/null +++ b/tests/test_A/test_run.py @@ -0,0 +1,231 @@ +"""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_raw"] == "long reasoning about the scene<|im_end|>" + assert record["reasoning_token_ids"] == list(range(50)) + 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 new file mode 100644 index 0000000000000000000000000000000000000000..ad3c0b8308854149f8478ab92ef6bae28b2b092d --- /dev/null +++ b/tests/test_A/test_sweep.py @@ -0,0 +1,69 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_B/conftest.py b/tests/test_B/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..cff300cdd89d64dac0aa52d10f2982c6fcbbe74d --- /dev/null +++ b/tests/test_B/conftest.py @@ -0,0 +1,12 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..ad4bc9206f95e5af7a9f103c1e4cdb2763864b28 --- /dev/null +++ b/tests/test_B/test_B.py @@ -0,0 +1,35 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..ad4bc9206f95e5af7a9f103c1e4cdb2763864b28 --- /dev/null +++ b/tests/test_B/test_init.py @@ -0,0 +1,35 @@ +"""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_launch.py b/tests/test_B/test_launch.py new file mode 100644 index 0000000000000000000000000000000000000000..598fa4e72abf4cc301473153f1c818df3d694b2f --- /dev/null +++ b/tests/test_B/test_launch.py @@ -0,0 +1,85 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..036649e08528f0ae9e4518e08afa1811ac15f54a --- /dev/null +++ b/tests/test_B/test_prompts.py @@ -0,0 +1,146 @@ +"""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._question_legend("object_counting")) + projected = code_prompts._project_for_question( + _CODE, "object_counting", "How many chairs?" + ) + assert json.dumps(projected, 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._question_legend(question_type)) + + +@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._question_legend(question_type)) + + +_RICH_CODE = { + "spatial code schema": {"version": 2}, + "objects": { + "chair": { + "count": 2, + "instances": [{ + "longest_dimension_meters": 0.8, + "position": {"floor_x_meters": 1.0}, + "irrelevant": "drop me", + }], + }, + "table": {"count": 1, "instances": []}, + }, + "room": {"floor_area_square_meters": 12.5, "outline": [1, 2]}, + "closest_classes_from": {"chair": {"table": {"distance_meters": 1.2}}}, + "appearance_order": ["chair", "table"], + "camera_trajectory": {"waypoints": [1]}, +} + + +def test_counting_projection_keeps_only_counts_for_every_class(): + projected = code_prompts._project_for_question( + _RICH_CODE, "object_counting", "How many chairs?" + ) + assert projected == { + "objects": {"chair": {"count": 2}, "table": {"count": 1}} + } + + +def test_size_projection_keeps_only_instance_dimensions(): + projected = code_prompts._project_for_question( + _RICH_CODE, "object_size_estimation", "How large is the chair?" + ) + assert projected == { + "objects": { + "chair": {"instances": [{"longest_dimension_meters": 0.8}]}, + "table": {"instances": []}, + } + } + + +def test_room_projection_keeps_only_floor_area(): + projected = code_prompts._project_for_question( + _RICH_CODE, "room_size_estimation", "How large is the room?" + ) + assert projected == {"room": {"floor_area_square_meters": 12.5}} + + +@pytest.mark.parametrize( + "question_type", ["object_abs_distance", "object_rel_distance"] +) +def test_distance_projections_keep_only_the_complete_distance_matrix(question_type): + projected = code_prompts._project_for_question( + _RICH_CODE, question_type, "distance?", ["A. x", "B. y"] + ) + assert projected == { + "closest_classes_from": _RICH_CODE["closest_classes_from"] + } + + +@pytest.mark.parametrize( + "question_type", + [ + "object_rel_direction_easy", + "object_rel_direction_medium", + "object_rel_direction_hard", + "route_planning", + ], +) +def test_direction_and_route_projections_keep_only_positions(question_type): + projected = code_prompts._project_for_question( + _RICH_CODE, question_type, "direction?", ["A. x", "B. y"] + ) + assert projected == { + "objects": { + "chair": {"instances": [{"position": {"floor_x_meters": 1.0}}]}, + "table": {"instances": []}, + } + } + + +def test_appearance_projection_keeps_only_appearance_order(): + projected = code_prompts._project_for_question( + _RICH_CODE, "obj_appearance_order", "which appeared first?", ["A. x"] + ) + assert projected == {"appearance_order": ["chair", "table"]} diff --git a/tests/test_B/test_run.py b/tests/test_B/test_run.py new file mode 100644 index 0000000000000000000000000000000000000000..269dc7cabf429e732c78eb334d833fdeb8d98c52 --- /dev/null +++ b/tests/test_B/test_run.py @@ -0,0 +1,191 @@ +"""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"] == "thinking: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["reasoning_raw"] == "long reasoning about the spatial code<|im_end|>" + assert record["reasoning_token_ids"] == list(range(50)) + 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", "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 new file mode 100644 index 0000000000000000000000000000000000000000..ae26c07a952b13eb2c61f9efe7623b0a226a9223 --- /dev/null +++ b/tests/test_B/test_spatial_codes.py @@ -0,0 +1,48 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..bcafb68aa6df20989f7667a32859e439bd017aa0 --- /dev/null +++ b/tests/test_B/test_sweep.py @@ -0,0 +1,67 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_C/conftest.py b/tests/test_C/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..3abc76e01c01cd0bfbddf3345cf7422f6c71fe53 --- /dev/null +++ b/tests/test_C/conftest.py @@ -0,0 +1,12 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..14f3b72ba8d26def86d9b63337d7e4d3e544689a --- /dev/null +++ b/tests/test_C/test_C.py @@ -0,0 +1,27 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..14f3b72ba8d26def86d9b63337d7e4d3e544689a --- /dev/null +++ b/tests/test_C/test_init.py @@ -0,0 +1,27 @@ +"""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_launch.py b/tests/test_C/test_launch.py new file mode 100644 index 0000000000000000000000000000000000000000..8ef65e3d7664c5e316651f42a09bde2d9f18c5ac --- /dev/null +++ b/tests/test_C/test_launch.py @@ -0,0 +1,69 @@ +"""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_prompts.py b/tests/test_C/test_prompts.py new file mode 100644 index 0000000000000000000000000000000000000000..3de92ac0908716ef60048060968e3f18ce5033d3 --- /dev/null +++ b/tests/test_C/test_prompts.py @@ -0,0 +1,70 @@ +"""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.B import prompts as code_prompts +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.FRAMES_NOTE.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.FRAMES_NOTE) + projected = code_prompts._project_for_question( + _CODE, "object_counting", "How many chairs?" + ) + code_pos = prompt.find(json.dumps(projected, indent=1)) + question_pos = prompt.find("How many chairs?") + post_pos = prompt.find(code_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(code_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.FRAMES_NOTE) + + +@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.FRAMES_NOTE) + + +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 new file mode 100644 index 0000000000000000000000000000000000000000..71df7b295144ee7b74a59e734e337178422a20c0 --- /dev/null +++ b/tests/test_C/test_run.py @@ -0,0 +1,180 @@ +"""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["reasoning_raw"] == "long reasoning about the frames and spatial code<|im_end|>" + assert record["reasoning_token_ids"] == list(range(50)) + assert record["reasoning_token_count"] == 50 + assert record["reasoning_hit_limit"] is True + 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 new file mode 100644 index 0000000000000000000000000000000000000000..c497f4f29f912024ad425bc513c0438c2e8752c2 --- /dev/null +++ b/tests/test_C/test_sweep.py @@ -0,0 +1,67 @@ +"""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_F/__init__.py b/tests/test_F/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_F/conftest.py b/tests/test_F/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..8a801f94b60da603c80287f186e31c5d32012e99 --- /dev/null +++ b/tests/test_F/conftest.py @@ -0,0 +1,12 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..bab18510998a1a4f6610b195409163f0d297285c --- /dev/null +++ b/tests/test_F/test_F.py @@ -0,0 +1,20 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..7b52d804e37f83c137001510c9f91533f86fb69b --- /dev/null +++ b/tests/test_F/test_launch.py @@ -0,0 +1,7 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..5006cd1d37632566a05d4c9a39f5241af33670aa --- /dev/null +++ b/tests/test_F/test_run.py @@ -0,0 +1,19 @@ +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 new file mode 100644 index 0000000000000000000000000000000000000000..95fa360e1106fe50593b284f19cb7a49ea42453e --- /dev/null +++ b/tests/test_F/test_sweep.py @@ -0,0 +1,14 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_analysis/conftest.py b/tests/test_analysis/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..126f811cb075cab9a44b8d2b97db54fafef16859 --- /dev/null +++ b/tests/test_analysis/conftest.py @@ -0,0 +1,118 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..273c4f9218f4f0fffcdf8def6e636de9d36f881a --- /dev/null +++ b/tests/test_analysis/test_A_reports.py @@ -0,0 +1,11 @@ +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 new file mode 100644 index 0000000000000000000000000000000000000000..19a06743b73f83c7256b8a8c4c52da8057fe4f3b --- /dev/null +++ b/tests/test_analysis/test_B_reports.py @@ -0,0 +1,11 @@ +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 new file mode 100644 index 0000000000000000000000000000000000000000..35cf3f5c014ddd304f787e1bc09f4f4a1ea56977 --- /dev/null +++ b/tests/test_analysis/test_C_reports.py @@ -0,0 +1,11 @@ +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_F_reports.py b/tests/test_analysis/test_F_reports.py new file mode 100644 index 0000000000000000000000000000000000000000..5862c066b0999e55501084a0d6b9710027a1a9b1 --- /dev/null +++ b/tests/test_analysis/test_F_reports.py @@ -0,0 +1,15 @@ +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 new file mode 100644 index 0000000000000000000000000000000000000000..69c91bab64cb4e8d7e729b83ba33ba1b879c2d34 --- /dev/null +++ b/tests/test_analysis/test_analysis.py @@ -0,0 +1,12 @@ +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 new file mode 100644 index 0000000000000000000000000000000000000000..78f4bab503b285f3f5ae2a35815084e64f5eca81 --- /dev/null +++ b/tests/test_analysis/test_letters_reports.py @@ -0,0 +1,55 @@ +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 new file mode 100644 index 0000000000000000000000000000000000000000..36152265db767b88d0ecb87aefddab8a67007c6c --- /dev/null +++ b/tests/test_backup.py @@ -0,0 +1,47 @@ +"""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_encoder/conftest.py b/tests/test_encoder/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..a77755f02a82953721899262a97085395ba8e213 --- /dev/null +++ b/tests/test_encoder/conftest.py @@ -0,0 +1,13 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..b5bcdebbb32981b327f5ccbb4bbf7efb6115bd15 --- /dev/null +++ b/tests/test_encoder/test_adapters.py @@ -0,0 +1,311 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..cb2a852a69729a41d811bdd8ff32b6c3726e63c6 --- /dev/null +++ b/tests/test_encoder/test_config.py @@ -0,0 +1,44 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..cf9a89521c777a8cf0989dbec38b639dd2b63d9d --- /dev/null +++ b/tests/test_encoder/test_encoder.py @@ -0,0 +1,73 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..b2e60ce74e62a492fcd023ef32d29c5352037623 --- /dev/null +++ b/tests/test_encoder/test_geometric.py @@ -0,0 +1,387 @@ +"""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_init.py b/tests/test_encoder/test_init.py new file mode 100644 index 0000000000000000000000000000000000000000..e8b95cf73b1554ca88509c5a76ea2c9943627a0c --- /dev/null +++ b/tests/test_encoder/test_init.py @@ -0,0 +1,7 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..26079d6d11c586198b1103c132f0c9913412de4b --- /dev/null +++ b/tests/test_encoder/test_launch.py @@ -0,0 +1,7 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..36ce6374bbc97424853e10b7b1cd136813e04db4 --- /dev/null +++ b/tests/test_encoder/test_render.py @@ -0,0 +1,9 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..6c9c463dd96a38c500c0a1b8cc73424559006e4d --- /dev/null +++ b/tests/test_encoder/test_run.py @@ -0,0 +1,24 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..df1def1e2acc704d98559591559e25d77068d207 --- /dev/null +++ b/tests/test_experiments/__init__.py @@ -0,0 +1 @@ +"""Tests for the experiments package.""" diff --git a/tests/test_experiments/conftest.py b/tests/test_experiments/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..06f2ab1af00b2b5b61d163761175c83246379d3e --- /dev/null +++ b/tests/test_experiments/conftest.py @@ -0,0 +1 @@ +"""Shared fixtures for experiment tests.""" diff --git a/tests/test_experiments/test_config.py b/tests/test_experiments/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..d088260673e3aa98f24e6705b707b80dc1f3de7a --- /dev/null +++ b/tests/test_experiments/test_config.py @@ -0,0 +1,70 @@ +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 new file mode 100644 index 0000000000000000000000000000000000000000..13ac6b32c3349ef0500c38acf5e5f53c82ed8d91 --- /dev/null +++ b/tests/test_experiments/test_evaluate.py @@ -0,0 +1,48 @@ +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 new file mode 100644 index 0000000000000000000000000000000000000000..7d63433ef8eceb8db6a358ec494c4bbee7039f17 --- /dev/null +++ b/tests/test_experiments/test_experiments.py @@ -0,0 +1,10 @@ +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 new file mode 100644 index 0000000000000000000000000000000000000000..528922ebd81b31d7a61a6e837b7a6b32650531b5 --- /dev/null +++ b/tests/test_experiments/test_hypotheses.py @@ -0,0 +1,230 @@ +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 new file mode 100644 index 0000000000000000000000000000000000000000..7ce89db24ac929820a0df3a7701f0a7de172a6f1 --- /dev/null +++ b/tests/test_experiments/test_launch.py @@ -0,0 +1,34 @@ +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 new file mode 100644 index 0000000000000000000000000000000000000000..0315bece622538fe473e794659b852e3361dbd10 --- /dev/null +++ b/tests/test_experiments/test_loader.py @@ -0,0 +1,20 @@ +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 new file mode 100644 index 0000000000000000000000000000000000000000..33e3fdb629479e9c241f3b16545f2122f0097dc6 --- /dev/null +++ b/tests/test_experiments/test_run.py @@ -0,0 +1,76 @@ +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 new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_harness/conftest.py b/tests/test_harness/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..8a801f94b60da603c80287f186e31c5d32012e99 --- /dev/null +++ b/tests/test_harness/conftest.py @@ -0,0 +1,12 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..e0bfccb2b7bf39e509d5f54905974d7e37555bdd --- /dev/null +++ b/tests/test_harness/test_harness.py @@ -0,0 +1,7 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..f9ec18b7b744f760331ab814b7613c31c48978b6 --- /dev/null +++ b/tests/test_inference/conftest.py @@ -0,0 +1,13 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..312f368a630b14ae63691b036dc72e126bef42e3 --- /dev/null +++ b/tests/test_inference/test_adapters.py @@ -0,0 +1,216 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..64cd4d1a885eee4011b7c2beaa2a4777c169b83a --- /dev/null +++ b/tests/test_inference/test_inference.py @@ -0,0 +1,22 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..e6399f811281f53da00592dfeb59aa1ca10201e8 --- /dev/null +++ b/tests/test_inference/test_init.py @@ -0,0 +1,55 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..f1a30d94ea430c3daf5579b41b16641fd2a31713 --- /dev/null +++ b/tests/test_inference/test_launch.py @@ -0,0 +1,7 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..294e9eb58299911e813238432e7102b13b329a56 --- /dev/null +++ b/tests/test_inference/test_prompts.py @@ -0,0 +1,30 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..e6655345b870f117520e3aab04f58696e93e79c6 --- /dev/null +++ b/tests/test_inference/test_run.py @@ -0,0 +1,41 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..51af0cf8764c55fbb1a8a526d1da69f55f1a2265 --- /dev/null +++ b/tests/test_symbolic/conftest.py @@ -0,0 +1,83 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..f90297823b1b66aab9ed2b3c38a9199e6445bb12 --- /dev/null +++ b/tests/test_symbolic/test_adapters.py @@ -0,0 +1,237 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..c1a00d7198ff8fbea1ad336e94ac4dea5e31c6fc --- /dev/null +++ b/tests/test_symbolic/test_launch.py @@ -0,0 +1,7 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..23ae0361904a24257318f199b177e27bf014735f --- /dev/null +++ b/tests/test_symbolic/test_run.py @@ -0,0 +1,110 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..f619d64451ad1e90cfda2cc8d36bc9da1b03c1ea --- /dev/null +++ b/tests/test_symbolic/test_solver.py @@ -0,0 +1,190 @@ +"""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 new file mode 100644 index 0000000000000000000000000000000000000000..ab7773979db0aa36fe0191f0d64ae79ef183f6a0 --- /dev/null +++ b/tests/test_symbolic/test_symbolic.py @@ -0,0 +1,13 @@ +"""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)