File size: 8,932 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
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
# (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.

"""Tubelet queries attend to camera geometry from both RGB frames."""

from __future__ import annotations

import torch
import torch.nn.functional as F

from nets.ucpe_cd50.ucpe import RelativeRayAttention as _SingleFrameAttention
from nets.ucpe_cd50.ucpe import (
    _apply_ucpe_transform,
    _invert_se3,
    _rope_coefficients,
    _validate_camera_inputs,
)
from nets.ucpe_cd50.ucpe import build_lat_up_encoding as _frame_lat_up
from nets.ucpe_cd50.ucpe import (
    build_relative_ray_transforms as _frame_ray_transforms,
)


def _group_frames(
    value: torch.Tensor, tubelet_size: int, patches: int
) -> torch.Tensor:
    batch = value.shape[0]
    grouped = value.reshape(batch, -1, tubelet_size, patches, *value.shape[2:])
    order = (0, 1, 3, 2, *range(4, grouped.ndim))
    return grouped.permute(order).reshape(
        batch, -1, tubelet_size, *value.shape[2:]
    )


def _ungroup_frames(value: torch.Tensor, patches: int) -> torch.Tensor:
    (batch, _, frames) = value.shape[:3]
    grouped = value.reshape(batch, -1, patches, frames, *value.shape[3:])
    order = (0, 1, 3, 2, *range(4, grouped.ndim))
    return grouped.permute(order).flatten(1, 3)


def build_relative_ray_transforms(
    T_world_cam: torch.Tensor,
    T_pix_cam: torch.Tensor,
    *,
    image_height: int,
    image_width: int,
    patch_size: int,
    tubelet_size: int,
) -> torch.Tensor:
    (_, frames) = _validate_camera_inputs(T_world_cam, T_pix_cam)
    if min(image_height, image_width, patch_size, tubelet_size) <= 0:
        raise ValueError("geometry dimensions must be positive")
    complete_frames = frames // tubelet_size * tubelet_size
    rays = _frame_ray_transforms(
        T_world_cam[:, :complete_frames],
        T_pix_cam[:, :complete_frames],
        image_height=image_height,
        image_width=image_width,
        patch_size=patch_size,
        tubelet_size=1,
    )
    patches = image_height // patch_size * (image_width // patch_size)
    return _group_frames(rays, tubelet_size, patches)


def build_lat_up_encoding(
    T_world_cam: torch.Tensor,
    T_pix_cam: torch.Tensor,
    *,
    world_up: torch.Tensor,
    image_height: int,
    image_width: int,
    patch_size: int,
    tubelet_size: int,
) -> torch.Tensor:
    (_, frames) = _validate_camera_inputs(T_world_cam, T_pix_cam)
    if min(image_height, image_width, patch_size, tubelet_size) <= 0:
        raise ValueError("geometry dimensions must be positive")
    complete_frames = frames // tubelet_size * tubelet_size
    lat_up = _frame_lat_up(
        T_world_cam[:, :complete_frames],
        T_pix_cam[:, :complete_frames],
        world_up=world_up,
        image_height=image_height,
        image_width=image_width,
        patch_size=patch_size,
        tubelet_size=1,
    )
    patches = image_height // patch_size * (image_width // patch_size)
    return _group_frames(lat_up, tubelet_size, patches)


class RelativeRayAttention(_SingleFrameAttention):
    def _oriented_tokens(
        self,
        tokens: torch.Tensor,
        lat_up: torch.Tensor | None,
        valid: torch.Tensor | None,
    ) -> torch.Tensor:
        if lat_up is None:
            return tokens
        if self.lat_up_proj is None:
            raise ValueError("latitude/up requires absolute orientation")
        if valid is not None:
            if valid.shape != (tokens.shape[0],) or valid.dtype != torch.bool:
                raise ValueError("lat_up_valid must be bool with shape [batch]")
            if valid.device != tokens.device:
                raise ValueError(
                    "latitude/up validity must share the token device"
                )
            lat_up = torch.where(valid[:, None, None], lat_up, 0.0)
        bias = self.lat_up_proj(lat_up.to(dtype=tokens.dtype))
        if valid is not None:
            bias = torch.where(valid[:, None, None], bias, 0.0)
        return tokens + bias

    def _rope(
        self, features: torch.Tensor, spatial_height: int, spatial_width: int
    ) -> tuple[
        tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor, torch.Tensor]
    ]:
        frames = features.shape[2] // (spatial_height * spatial_width)
        x = (
            torch.arange(
                spatial_width, device=features.device, dtype=torch.float32
            )
            .repeat(spatial_height)
            .repeat(frames)
        )
        y = (
            torch.arange(
                spatial_height, device=features.device, dtype=torch.float32
            )
            .repeat_interleave(spatial_width)
            .repeat(frames)
        )
        return (
            _rope_coefficients(x, self.head_dim // 4),
            _rope_coefficients(y, self.head_dim // 4),
        )

    def _attend(
        self,
        q: torch.Tensor,
        k: torch.Tensor,
        v: torch.Tensor,
        anchors: torch.Tensor,
        frames: torch.Tensor,
        spatial_height: int,
        spatial_width: int,
    ) -> torch.Tensor:
        query_rope = self._rope(q, spatial_height, spatial_width)
        frame_rope = self._rope(k, spatial_height, spatial_width)
        with torch.amp.autocast(device_type=q.device.type, enabled=False):
            anchors = anchors.float()
            inverse_frames = _invert_se3(frames.float())
        q = _apply_ucpe_transform(q, anchors.transpose(-1, -2), *query_rope)
        k = _apply_ucpe_transform(k, inverse_frames, *frame_rope)
        v = _apply_ucpe_transform(v, inverse_frames, *frame_rope)
        output = F.scaled_dot_product_attention(
            q, k, v, dropout_p=self.dropout if self.training else 0.0
        )
        return _apply_ucpe_transform(
            output, anchors, *query_rope, inverse_rope=True
        )

    def _validate_geometry(
        self,
        tokens: torch.Tensor,
        ray_transforms: torch.Tensor,
        spatial_height: int,
        spatial_width: int,
        lat_up_encoding: torch.Tensor | None,
    ) -> tuple[int, int, int, int]:
        if tokens.ndim != 3 or tokens.shape[-1] != self.dim:
            raise ValueError(
                f"tokens must have shape [batch, length, {self.dim}]"
            )
        (batch, length, _) = tokens.shape
        if (
            ray_transforms.ndim != 5
            or ray_transforms.shape[:2] != (batch, length)
            or ray_transforms.shape[-2:] != (4, 4)
            or (ray_transforms.shape[2] <= 0)
        ):
            raise ValueError(
                "ray transforms must have shape [batch, length, frames, 4, 4]"
            )
        if ray_transforms.device != tokens.device:
            raise ValueError("tokens and ray transforms must share the device")
        patches = spatial_height * spatial_width
        if min(spatial_height, spatial_width) <= 0 or length % patches != 0:
            raise ValueError("token length must contain complete spatial grids")
        frames_per_tubelet = ray_transforms.shape[2]
        if lat_up_encoding is not None and (
            lat_up_encoding.shape != (batch, length, frames_per_tubelet, 3)
            or lat_up_encoding.device != tokens.device
        ):
            raise ValueError(
                "latitude/up must have shape [batch, length, frames, 3]"
            )
        return (batch, length, frames_per_tubelet, patches)

    def forward(
        self,
        tokens: torch.Tensor,
        ray_transforms: torch.Tensor,
        *,
        spatial_height: int,
        spatial_width: int,
        lat_up_encoding: torch.Tensor | None = None,
        lat_up_valid: torch.Tensor | None = None,
    ) -> torch.Tensor:
        (batch, length, frames_per_tubelet, patches) = self._validate_geometry(
            tokens,
            ray_transforms,
            spatial_height,
            spatial_width,
            lat_up_encoding,
        )
        frame_tokens = _ungroup_frames(
            tokens[:, :, None].expand(-1, -1, frames_per_tubelet, -1), patches
        )
        query_lat_up = (
            None if lat_up_encoding is None else lat_up_encoding[:, :, 0]
        )
        frame_lat_up = (
            None
            if lat_up_encoding is None
            else _ungroup_frames(lat_up_encoding, patches)
        )
        query_tokens = self._oriented_tokens(tokens, query_lat_up, lat_up_valid)
        frame_tokens = self._oriented_tokens(
            frame_tokens, frame_lat_up, lat_up_valid
        )
        output = self._attend(
            self._project(self.q_proj(query_tokens)),
            self._project(self.k_proj(frame_tokens)),
            self._project(self.v_proj(frame_tokens)),
            ray_transforms[:, :, 0],
            _ungroup_frames(ray_transforms, patches),
            spatial_height,
            spatial_width,
        )
        output = output.transpose(1, 2).reshape(
            batch, length, self.attention_dim
        )
        return self.out_proj(output)