File size: 4,372 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
"""Build and run the encoder and decoder with the exported model settings."""

from __future__ import annotations

import json
from pathlib import Path

import torch
from torch import nn

from nets.ucpe_cd50.decoder import D4RTDecoder, D4RTDecoderConfig
from nets.ucpe_cd50.encoder import VideoMAEEncoder, VideoMAEEncoderConfig
from nets.ucpe_cd50.transition import (
    UCPETransitionConfig,
    restore_ucpe_transition_for_evaluation,
    set_ucpe_transition_scale,
)


class UCPECD50Model(nn.Module):
    def __init__(
        self,
        encoder: VideoMAEEncoder,
        decoder: D4RTDecoder,
        transition: UCPETransitionConfig | None = None,
    ) -> None:
        super().__init__()
        self.encoder = encoder
        self.decoder = decoder
        self.transition = transition or UCPETransitionConfig(408777, 1000)
        self.transition.validate()

    @classmethod
    def from_config(
        cls,
        config_path: str | Path | None = None,
        *,
        use_flash_attn: bool = True,
    ) -> UCPECD50Model:
        path = (
            Path(config_path)
            if config_path
            else Path(__file__).with_name("model_config.json")
        )
        config = json.loads(path.read_text())
        encoder_options = dict(config["encoder"])
        encoder_options["use_flash_attn"] = use_flash_attn
        encoder = VideoMAEEncoderConfig(**encoder_options).build()
        decoder = D4RTDecoderConfig(**config["decoder"]).build(
            encoder.embed_dim
        )
        return cls(
            encoder,
            decoder,
            UCPETransitionConfig(**config["ucpe_transition"]),
        )

    def set_global_step(self, step: int) -> None:
        """Set the transition used for a training step."""
        set_ucpe_transition_scale(self.encoder, self.transition.scale_at(step))

    def set_checkpoint_step(self, step: int) -> None:
        """Restore evaluation's transition from the next-step counter."""
        restore_ucpe_transition_for_evaluation(
            self.encoder, self.transition, step
        )

    def encode(
        self,
        video: torch.Tensor,
        T_world_cam: torch.Tensor,
        T_pix_cam: torch.Tensor,
        *,
        aspect_ratio: torch.Tensor | None = None,
        camera_condition_mask: torch.Tensor | None = None,
        world_up: torch.Tensor | None = None,
        world_up_valid: torch.Tensor | None = None,
    ) -> torch.Tensor:
        """Flatten tokens from normalized RGB shaped (B, V, 3, T, H, W)."""
        if video.ndim != 6:
            raise ValueError("video must have shape (B, V, 3, T, H, W)")
        if aspect_ratio is None:
            focal_x = T_pix_cam[..., 0, 0].abs()
            focal_y = T_pix_cam[..., 1, 1].abs()
            ratio = focal_y / focal_x.clamp_min(torch.finfo(focal_x.dtype).eps)
            aspect_ratio = ratio.median(dim=2).values.unsqueeze(-1)
        tokens = self.encoder(
            video,
            T_world_cam=T_world_cam,
            T_pix_cam=T_pix_cam,
            aspect_ratio=aspect_ratio,
            camera_condition_mask=camera_condition_mask,
            world_up=world_up,
            world_up_valid=world_up_valid,
        )
        return tokens.flatten(1, 2)

    def forward(
        self,
        video: torch.Tensor,
        T_world_cam: torch.Tensor,
        T_pix_cam: torch.Tensor,
        uv: torch.Tensor,
        t_src: torch.Tensor,
        t_tgt: torch.Tensor,
        image_patch: torch.Tensor,
        v_src: torch.Tensor,
        *,
        aspect_ratio: torch.Tensor | None = None,
        camera_condition_mask: torch.Tensor | None = None,
        world_up: torch.Tensor | None = None,
        world_up_valid: torch.Tensor | None = None,
    ) -> tuple[torch.Tensor, ...]:
        """Return the six decoder heads in their native output spaces."""
        tokens = self.encode(
            video,
            T_world_cam,
            T_pix_cam,
            aspect_ratio=aspect_ratio,
            camera_condition_mask=camera_condition_mask,
            world_up=world_up,
            world_up_valid=world_up_valid,
        )
        return self.decoder(
            uv=uv,
            t_src=t_src,
            t_tgt=t_tgt,
            image_patch=image_patch,
            y=tokens,
            num_views=video.shape[1],
            v_src=v_src,
            t_cam=t_tgt,
        )