import copy import json import tempfile import unittest from pathlib import Path from types import SimpleNamespace from unittest.mock import patch import numpy as np import torch from torch import nn from evaluation.scale4d import SCALE4D from evaluation.ucpe_checkpoint import recorded_model_config from evaluation.ucpe_inference import UCPEEvaluator, camera_xyz_from_uv_depth from evaluation.ucpe_inputs import ClipInput, ClipLabels, load_clip, pstudio_camera_ids from evaluation.ucpe_scores import aggregate_cells, score_tracks class FakeDecoder(nn.Module): def __init__(self): super().__init__() self.image_patch_embed = nn.Linear(3 * 3 * 3, 1) def forward(self, **kwargs): uv = kwargs["uv"] xyz = torch.cat([torch.full_like(uv, 99), torch.full_like(uv[..., :1], 2)], -1) logits = torch.zeros_like(uv[..., :1]) return xyz, torch.full_like(uv, 0.5), logits, xyz, xyz, logits class FakeModel(nn.Module): def __init__(self): super().__init__() self.decoder = FakeDecoder() self.encoder = SimpleNamespace( num_frames=48, model=SimpleNamespace(patch_embed=SimpleNamespace(img_size=(16, 16))), ) def encode(self, video, poses, intrinsics, **kwargs): self.encoded = video, poses, intrinsics, kwargs return torch.zeros(1, video.shape[1], 3) def clip(frames=48): return ClipInput( rgbs=torch.zeros(3, frames, 3, 12, 20, dtype=torch.uint8), cameras_to_world=torch.eye(4).expand(3, frames, 4, 4).clone(), intrinsics=torch.tensor([[10.0, 0.0, 9.5], [0.0, 10.0, 5.5], [0.0, 0.0, 1.0]]) .expand(3, frames, 3, 3) .clone(), query_uv=torch.tensor([[8.0, 4.0], [12.0, 6.0]]), query_times=torch.tensor([0, 4]), query_views=torch.zeros(2, dtype=torch.int64), world_up=torch.tensor([0.0, -1.0, 0.0]), metadata={ "dataset_type": "dexycb_mv" if frames != 48 else "pstudio", "camera_ids": [5, 26, 12], }, ) class InferenceContractTest(unittest.TestCase): def test_public_api_saves_predictions_and_recorded_config(self): from evaluation.ucpe_checkpoint import CheckpointInfo info = CheckpointInfo( 140000, 1891, {"extent_scale_injection": "ucpe_bias"}, {}, None ) with patch("evaluation.scale4d.load_model", return_value=(FakeModel(), info)): tracker = SCALE4D("local.pt", device="cpu") result = tracker.predict_clip(clip(), views=3, camera="on") with tempfile.TemporaryDirectory() as temporary: path = Path(temporary) / "tracks.npz" result.save(path) with np.load(path, allow_pickle=False) as data: self.assertEqual(data["xyz"].shape, (48, 2, 3)) self.assertTrue( np.array_equal(data["query_times"], clip().query_times.numpy()) ) metadata = json.loads(str(data["metadata_json"].item())) with self.assertRaises(FileExistsError): result.save(path) self.assertEqual(metadata["checkpoint_step"], 140000) self.assertEqual( metadata["model_config"]["encoder"]["extent_scale_injection"], "ucpe_bias" ) self.assertEqual(metadata["encoded_camera_ids"], [5, 26, 12]) def test_public_api_requires_calibration_for_camera_on(self): from evaluation.ucpe_checkpoint import CheckpointInfo info = CheckpointInfo(140000, 1891, {}, {}, None) with patch("evaluation.scale4d.load_model", return_value=(FakeModel(), info)): tracker = SCALE4D("local.pt", device="cpu") with self.assertRaisesRegex(ValueError, "requires"): tracker.predict(torch.zeros(48, 3, 12, 20, dtype=torch.uint8), camera="on") def test_cam_off_preserves_depth_and_uses_intrinsics(self): model = FakeModel() result = UCPEEvaluator(model, "cpu").predict(clip(), views=3, camera="off") torch.testing.assert_close(result.xyz[..., :2], torch.full((48, 2, 2), 99.0)) torch.testing.assert_close(result.uv_depth[..., :2], torch.zeros(48, 2, 2)) self.assertTrue(torch.equal(result.xyz[..., 2], result.uv_depth[..., 2])) self.assertFalse(bool(model.encoded[3]["camera_condition_mask"].any())) self.assertEqual(result.camera_ids, [5, 26, 12]) self.assertTrue(bool((result.visibility == 0.5).all())) def test_single_view_and_half_pixel_intrinsics(self): model = FakeModel() UCPEEvaluator(model, "cpu").predict(clip(), views=1) video, _, k, _ = model.encoded self.assertEqual(video.shape[:4], (1, 1, 3, 48)) self.assertAlmostEqual(float(k[0, 0, 0, 0, 2]), 7.5) self.assertAlmostEqual(float(k[0, 0, 0, 1, 2]), 7.5) def test_dexycb_padding_is_inference_only(self): model = FakeModel() result = UCPEEvaluator(model, "cpu").predict(clip(24), views=3) self.assertEqual(model.encoded[0].shape[3], 48) self.assertEqual(result.xyz.shape, (24, 2, 3)) def test_backprojection_handles_skew_and_preserves_z(self): result = camera_xyz_from_uv_depth( torch.tensor([[[2.5, 2.5]]]), torch.tensor([[3.0]]), torch.tensor([[4.0, 1.0, 1.5], [0.0, 2.0, 0.5], [0.0, 0.0, 1.0]]), ) torch.testing.assert_close(result, torch.tensor([[[0.0, 3.0, 3.0]]])) def test_backprojection_rejects_invalid_calibration(self): with self.assertRaises(ValueError): camera_xyz_from_uv_depth( torch.zeros(2, 1, 2), torch.ones(2, 1), torch.eye(3)[None] ) with self.assertRaises(ValueError): camera_xyz_from_uv_depth( torch.full((1, 1, 2), torch.nan), torch.ones(1, 1), torch.eye(3) ) def test_pstudio_target_then_nearest_camera_centers(self): centers = { 5: np.zeros(3), 12: np.array([1.3, 0, 0]), 26: np.array([1.2, 0, 0]), 2: np.array([9.0, 0, 0]), } self.assertEqual(pstudio_camera_ids(5, centers), [5, 26, 12]) def test_frozen_npz_keeps_labels_separate_from_inference(self): value = clip() with tempfile.TemporaryDirectory() as temporary: path = Path(temporary) / "clip.npz" np.savez( path, **{ name: getattr(value, name).numpy() for name in ( "rgbs", "cameras_to_world", "intrinsics", "query_uv", "query_times", "query_views", "world_up", ) }, metadata_json=json.dumps({**value.metadata, "format_version": 1}), gt_tracks_target_camera=np.zeros((48, 2, 3), np.float32), gt_visibility=np.ones((48, 2), bool), ) inputs, labels = load_clip(path) self.assertFalse(hasattr(inputs, "tracks_target_camera")) self.assertEqual(labels.tracks_target_camera.shape, (48, 2, 3)) class MetricsContractTest(unittest.TestCase): def test_metric_never_fits_scale_nonmetric_does(self): gt = np.array([[[0.0, 0.0, 2.0]]], dtype=np.float32) result = score_tracks( ClipLabels(gt, np.ones((1, 1), bool)), gt / 2, np.ones((1, 1)) ) self.assertEqual(result["metric"]["aj"], 0.0) self.assertEqual(result["non_metric"]["aj"], 100.0) self.assertEqual(result["non_metric_scale"], 2.0) self.assertEqual(result["metric"]["oa"], result["non_metric"]["oa"]) def test_fixed_threshold_ladder_and_occluded_false_positives(self): gt = np.zeros((1, 2, 3), np.float32) predicted = gt.copy() predicted[0, 0, 0] = 0.075 result = score_tracks( ClipLabels(gt, np.array([[True, False]])), predicted, np.ones((1, 2)) ) self.assertEqual(result["metric"]["apd"], 75.0) self.assertEqual(result["metric"]["aj"], 37.5) self.assertEqual(result["metric"]["oa"], 50.0) def test_mean_is_per_clip(self): cells = [ { "dataset": "pstudio", "views": 1, "camera": "on", "scores": { "uv_depth": { mode: {"aj": value, "apd": value, "oa": value, "epe": value} for mode in ("metric", "non_metric") } }, } for value in (20.0, 80.0) ] self.assertEqual(aggregate_cells(cells)[0]["aj"], 50.0) class RecordedConfigurationTest(unittest.TestCase): def configuration(self): preset = json.loads( ( Path(__file__).parents[1] / "nets/ucpe_cd50_stable/model_config_ft440k_ucpe_bias.json" ).read_text() ) return { "trainer": { "type": "mv_trainer_stable_ucpe_v00.MVTrainerConfig", "encoder": { "type": "videomae_stable_ucpe_v00.VideoMAEEncoderConfig", **preset["encoder"], }, "decoder": { "type": "d4rt_fp32_v00.D4RTDecoderConfig", **preset["decoder"], }, "fusion": {"type": "none_v00.NoFusionConfig"}, "decoder_use_t_cam": True, "decoder_t_cam_mode": "target", "losses": {"pos_3d_scale_mode": "none", "metric_pos_3d_symlog": False}, "batch": { "use_all_views": True, "input_len": None, "input_view_num": None, "max_view_num": 3, "image_win_size": 9, }, } } def test_recorded_injection_route_is_preserved(self): encoder, _ = recorded_model_config(self.configuration()) self.assertEqual(encoder["extent_scale_injection"], "ucpe_bias") def test_forge_trainer_preserves_the_inference_configuration(self): config = self.configuration() expected = recorded_model_config(config) config["trainer"]["type"] = "mv_trainer_stable_ucpe_forge_v00.MVTrainerConfig" self.assertEqual(recorded_model_config(config), expected) def test_inference_export_preserves_weights_and_omits_training_state(self): from safetensors.torch import load_file from d4rt_scripts.export_scale4d import export_checkpoint weights = { "encoder.weight": torch.arange(6, dtype=torch.float32).reshape(2, 3), "decoder.bias": torch.tensor([0.25, -0.5]), } payload = { "format_version": 1, "global_step": 140000, "run_config": { **self.configuration(), "training_data": "private_training_state", }, "modules": { "encoder": {"weight": weights["encoder.weight"]}, "decoder": {"bias": weights["decoder.bias"]}, }, "optimizers": {"moment": torch.ones(4)}, "rng_states": {"private": "private_training_state"}, } with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) checkpoint = root / "native.pt" torch.save(payload, checkpoint) receipt = export_checkpoint(checkpoint, root / "export") actual = load_file(str(root / "export/model.safetensors")) self.assertEqual(set(actual), set(weights)) for name, value in weights.items(): self.assertTrue(torch.equal(actual[name], value)) config_text = (root / "export/config.json").read_text() self.assertNotIn("private_training_state", config_text) config = json.loads(config_text) self.assertEqual(config["checkpoint_step"], 140000) self.assertEqual(config["encoder"]["checkpoint_path"], "") self.assertEqual(receipt["tensor_count"], 2) def test_wrong_architecture_and_output_transform_fail(self): original = self.configuration() for section, key, value in ( ("encoder", "type", "other.Encoder"), ("losses", "metric_pos_3d_symlog", True), ("decoder", "use_t_cam", False), ): config = copy.deepcopy(original) config["trainer"][section][key] = value with self.assertRaises(ValueError): recorded_model_config(config) if __name__ == "__main__": unittest.main()