Download examples/visualizer_code/source/tests/test_scale4d_inference.py from facebook/SCALE4D: direct link, hf CLI and curl.
- Browser
- Download file 7.01 kB
-
https://huggingface.co/facebook/SCALE4D/resolve/main/examples/visualizer_code/source/tests/test_scale4d_inference.py
- Command line
-
hf download hf://facebook/SCALE4D/examples/visualizer_code/source/tests/test_scale4d_inference.py
-
curl -L -o test_scale4d_inference.py https://huggingface.co/facebook/SCALE4D/resolve/main/examples/visualizer_code/source/tests/test_scale4d_inference.py
7.01 kB
| import copy | |
| import json | |
| import tempfile | |
| import unittest | |
| from pathlib import Path | |
| from unittest.mock import patch | |
| import numpy as np | |
| import torch | |
| from safetensors.torch import save_file | |
| from torch import nn | |
| from evaluation.scale4d_inputs import array_clip, video_clip | |
| from nets.scale4d import CONFIG_PATH, HF_REVISION, load_model | |
| class SmallModel(nn.Module): | |
| def __init__(self): | |
| super().__init__() | |
| self.encoder = nn.Linear(2, 2) | |
| self.decoder = nn.Linear(2, 1) | |
| def set_checkpoint_step(self, step): | |
| self.step = step | |
| class CheckpointLoadingTest(unittest.TestCase): | |
| def test_bare_torch_and_safetensors_use_packaged_140k_config(self): | |
| expected = SmallModel().state_dict() | |
| with tempfile.TemporaryDirectory() as temporary: | |
| root = Path(temporary) | |
| torch.save({"state_dict": expected}, root / "weights.pt") | |
| save_file(expected, str(root / "weights.safetensors")) | |
| for path in (root / "weights.pt", root / "weights.safetensors"): | |
| with ( | |
| self.subTest(path=path), | |
| patch( | |
| "nets.scale4d.UCPECD50StableModel.from_config", | |
| side_effect=lambda *args, **kwargs: SmallModel(), | |
| ) as builder, | |
| ): | |
| model, info = load_model(path, use_flash_attn=False) | |
| builder.assert_called_once_with(CONFIG_PATH, use_flash_attn=False) | |
| self.assertEqual(model.step, 140000) | |
| self.assertIsNone(info.ucpe_transition) | |
| self.assertEqual(info.encoder["extent_scale_injection"], "ucpe_bias") | |
| self.assertTrue(info.encoder["selective_ucpe_rows"]) | |
| for name, tensor in expected.items(): | |
| torch.testing.assert_close( | |
| model.state_dict()[name], tensor, rtol=0, atol=0 | |
| ) | |
| def test_missing_weights_fail_strict_loading(self): | |
| weights = SmallModel().state_dict() | |
| weights.pop("encoder.weight") | |
| with tempfile.TemporaryDirectory() as temporary: | |
| path = Path(temporary) / "weights.safetensors" | |
| save_file(weights, str(path)) | |
| with ( | |
| patch( | |
| "nets.scale4d.UCPECD50StableModel.from_config", | |
| return_value=SmallModel(), | |
| ), | |
| self.assertRaisesRegex(RuntimeError, "encoder.weight"), | |
| ): | |
| load_model(path) | |
| def test_native_checkpoint_rejects_conflicting_explicit_config(self): | |
| config = json.loads(CONFIG_PATH.read_text()) | |
| recorded = { | |
| "trainer": { | |
| "type": "mv_trainer_stable_ucpe_forge_v00.MVTrainerConfig", | |
| "encoder": { | |
| "type": "videomae_stable_ucpe_v00.VideoMAEEncoderConfig", | |
| **config["encoder"], | |
| }, | |
| "decoder": { | |
| "type": "d4rt_fp32_v00.D4RTDecoderConfig", | |
| **config["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, | |
| }, | |
| }, | |
| "ucpe_transition": None, | |
| } | |
| with tempfile.TemporaryDirectory() as temporary: | |
| root = Path(temporary) | |
| checkpoint = root / "native.pt" | |
| torch.save( | |
| {"format_version": 1, "global_step": 140000, "run_config": recorded}, | |
| checkpoint, | |
| ) | |
| with patch( | |
| "nets.scale4d.load_checkpoint", return_value=("model", "info") | |
| ) as native_loader: | |
| self.assertEqual(load_model(checkpoint), ("model", "info")) | |
| native_loader.assert_called_once() | |
| for section, key, value in ( | |
| ("encoder", "extent_scale_injection", "aspect"), | |
| ("encoder", "selective_ucpe_rows", False), | |
| (None, "ucpe_transition", {"start_step": 408777, "warmup_steps": 1000}), | |
| ): | |
| conflicting = copy.deepcopy(config) | |
| target = conflicting if section is None else conflicting[section] | |
| target[key] = value | |
| path = root / "config.json" | |
| path.write_text(json.dumps(conflicting)) | |
| with ( | |
| self.subTest(key=key), | |
| self.assertRaisesRegex(ValueError, "differs"), | |
| ): | |
| load_model(checkpoint, config_path=path) | |
| def test_default_hub_release_is_pinned(self): | |
| with tempfile.TemporaryDirectory() as temporary: | |
| root = Path(temporary) | |
| save_file(SmallModel().state_dict(), str(root / "model.safetensors")) | |
| with ( | |
| patch( | |
| "nets.scale4d.snapshot_download", return_value=str(root) | |
| ) as download, | |
| patch( | |
| "nets.scale4d.UCPECD50StableModel.from_config", | |
| return_value=SmallModel(), | |
| ), | |
| ): | |
| load_model() | |
| self.assertEqual(download.call_args.kwargs["revision"], HF_REVISION) | |
| class InputPreparationTest(unittest.TestCase): | |
| def test_array_grid_and_calibration(self): | |
| clip = array_clip(np.zeros((48, 3, 12, 20), np.uint8), grid_size=2) | |
| self.assertEqual(clip.rgbs.shape, (1, 48, 3, 12, 20)) | |
| torch.testing.assert_close( | |
| clip.query_uv, | |
| torch.tensor([[0, 0], [19, 0], [0, 11], [19, 11]], dtype=torch.float32), | |
| ) | |
| self.assertEqual(clip.metadata["camera_calibration"], "synthetic") | |
| self.assertTrue( | |
| torch.equal(clip.query_times, torch.zeros(4, dtype=torch.int64)) | |
| ) | |
| def test_video_records_sampling_and_short_video_repeats(self): | |
| import cv2 | |
| with tempfile.TemporaryDirectory() as temporary: | |
| path = Path(temporary) / "clip.avi" | |
| writer = cv2.VideoWriter( | |
| str(path), cv2.VideoWriter_fourcc(*"MJPG"), 24, (20, 12) | |
| ) | |
| self.assertTrue(writer.isOpened()) | |
| for value in (20, 80, 140): | |
| writer.write(np.full((12, 20, 3), value, np.uint8)) | |
| writer.release() | |
| clip = video_clip(path, grid_size=1) | |
| self.assertEqual(clip.rgbs.shape[1], 48) | |
| indices = clip.metadata["source_frame_indices"] | |
| self.assertEqual((indices[0], indices[-1]), (0, 2)) | |
| self.assertEqual(len(indices), 48) | |
| if __name__ == "__main__": | |
| unittest.main() | |