File size: 10,256 Bytes
e8055cf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 | """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])
|