| """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]) |
|
|