File size: 7,007 Bytes
9c890d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()