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
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE-VGGT file in the root directory of this source tree.

import logging
import torch
from torch import nn, Tensor
from torch.utils.checkpoint import checkpoint
from typing import List, Callable
from dataclasses import dataclass

from einops import repeat

from vggt.layers.block import drop_add_residual_stochastic_depth
from vggt.layers.rope import RotaryPositionEmbedding2D, PositionGetter

from vggt.layers.attention import Attention
from vggt.layers.drop_path import DropPath
from vggt.layers.layer_scale import LayerScale
from vggt.layers.mlp import Mlp

logger = logging.getLogger(__name__)


@dataclass
class ModulationOut:
    shift: Tensor
    scale: Tensor
    gate: Tensor


class Modulation(nn.Module):
    def __init__(self, dim: int, double: bool):
        super().__init__()
        self.is_double = double
        self.multiplier = 6 if double else 3
        self.lin = nn.Linear(dim, self.multiplier * dim, bias=True)

    def forward(self, vec: Tensor) -> tuple[ModulationOut, ModulationOut | None]:
        out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1)

        return (
            ModulationOut(*out[:3]),
            ModulationOut(*out[3:]) if self.is_double else None,
        )


class ConditionalBlock(nn.Module):
    def __init__(
        self,
        dim: int,
        num_heads: int,
        mlp_ratio: float = 4.0,
        qkv_bias: bool = True,
        proj_bias: bool = True,
        ffn_bias: bool = True,
        drop: float = 0.0,
        attn_drop: float = 0.0,
        init_values=None,
        drop_path: float = 0.0,
        act_layer: Callable[..., nn.Module] = nn.GELU,
        norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
        attn_class: Callable[..., nn.Module] = Attention,
        ffn_layer: Callable[..., nn.Module] = Mlp,
        qk_norm: bool = False,
        fused_attn: bool = True,  # use F.scaled_dot_product_attention or not
        rope=None,
    ) -> None:
        super().__init__()

        self.norm1 = norm_layer(dim, elementwise_affine=False)
        self.modulation = Modulation(dim, double=False)

        self.attn = attn_class(
            dim,
            num_heads=num_heads,
            qkv_bias=qkv_bias,
            proj_bias=proj_bias,
            attn_drop=attn_drop,
            proj_drop=drop,
            qk_norm=qk_norm,
            fused_attn=fused_attn,
            rope=rope,
        )

        self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()

        self.norm2 = norm_layer(dim)
        mlp_hidden_dim = int(dim * mlp_ratio)
        self.mlp = ffn_layer(
            in_features=dim,
            hidden_features=mlp_hidden_dim,
            act_layer=act_layer,
            drop=drop,
            bias=ffn_bias,
        )
        self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
        self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()

        self.sample_drop_ratio = drop_path

    def forward(self, x: Tensor, pos=None, cond=None, is_global=False) -> Tensor:
        B, S = cond.shape[:2]
        C = x.shape[-1]
        if is_global:
            P = x.shape[1] // S
        cond = cond.view(B * S, C)
        mod, _ = self.modulation(cond)

        def attn_residual_func(x: Tensor, pos=None) -> Tensor:
            """
            conditional attention following DiT implementation from Flux
            https://github.com/black-forest-labs/flux/blob/main/src/flux/modules/layers.py#L194-L239
            """
            def prepare_for_mod(y):
                """reshape to modulate the patch tokens with correct conditioning one"""
                return y.view(B, S, P, C).view(B * S, P, C) if is_global else y
            def restore_after_mod(y):
                """reshape back to global sequence"""
                return y.view(B, S, P, C).view(B, S * P, C) if is_global else y

            x = prepare_for_mod(x)
            x = (1 + mod.scale) * self.norm1(x) + mod.shift
            x = restore_after_mod(x)

            x = self.attn(x, pos=pos)

            x = prepare_for_mod(x)
            x = mod.gate * x
            x = restore_after_mod(x)

            return x

        def ffn_residual_func(x: Tensor) -> Tensor:
            return self.ls2(self.mlp(self.norm2(x)))

        if self.training and self.sample_drop_ratio > 0.1:
            # the overhead is compensated only for a drop path rate larger than 0.1
            x = drop_add_residual_stochastic_depth(
                x,
                pos=pos,
                residual_func=attn_residual_func,
                sample_drop_ratio=self.sample_drop_ratio,
            )
            x = drop_add_residual_stochastic_depth(
                x,
                residual_func=ffn_residual_func,
                sample_drop_ratio=self.sample_drop_ratio,
            )
        elif self.training and self.sample_drop_ratio > 0.0:
            x = x + self.drop_path1(attn_residual_func(x, pos=pos))
            x = x + self.drop_path1(ffn_residual_func(x))  # FIXME: drop_path2
        else:
            x = x + attn_residual_func(x, pos=pos)
            x = x + ffn_residual_func(x)
        return x


class Decoder(nn.Module):
    """Attention blocks after encoder per DPT input feature
    to generate point maps at a given time.
    """

    def __init__(
        self,
        cfg,
        dim_in: int,
        intermediate_layer_idx: List[int] = [4, 11, 17, 23],
        patch_size=14,
        embed_dim=1024,
        depth=2,
        num_heads=16,
        mlp_ratio=4.0,
        block_fn=ConditionalBlock,
        qkv_bias=True,
        proj_bias=True,
        ffn_bias=True,
        aa_order=["frame", "global"],
        aa_block_size=1,
        qk_norm=True,
        rope_freq=100,
        init_values=0.01,
    ):
        super().__init__()
        self.cfg = cfg
        self.intermediate_layer_idx = intermediate_layer_idx

        self.depth = depth
        self.aa_order = aa_order
        self.patch_size = patch_size
        self.aa_block_size = aa_block_size

        # Validate that depth is divisible by aa_block_size
        if self.depth % self.aa_block_size != 0:
            raise ValueError(f"depth ({depth}) must be divisible by aa_block_size ({aa_block_size})")

        self.aa_block_num = self.depth // self.aa_block_size

        self.rope = (
            RotaryPositionEmbedding2D(frequency=rope_freq) if rope_freq > 0 else None
        )
        self.position_getter = PositionGetter() if self.rope is not None else None

        self.dim_in = dim_in

        self.old_decoder = False
        if self.old_decoder:
            self.frame_blocks = nn.ModuleList(
                [
                    block_fn(
                        dim=embed_dim*2,
                        num_heads=num_heads,
                        mlp_ratio=mlp_ratio,
                        qkv_bias=qkv_bias,
                        proj_bias=proj_bias,
                        ffn_bias=ffn_bias,
                        init_values=init_values,
                        qk_norm=qk_norm,
                        rope=self.rope,
                    )
                    for _ in range(depth)
                ]
            )
            self.global_blocks = nn.ModuleList(
                [
                    block_fn(
                        dim=embed_dim*2,
                        num_heads=num_heads,
                        mlp_ratio=mlp_ratio,
                        qkv_bias=qkv_bias,
                        proj_bias=proj_bias,
                        ffn_bias=ffn_bias,
                        init_values=init_values,
                        qk_norm=qk_norm,
                        rope=self.rope,
                    )
                    for _ in range(depth)
                ]
            )
        else:
            depths = [depth]
            self.frame_blocks = nn.ModuleList([
                nn.ModuleList([
                    block_fn(
                        dim=embed_dim*2,
                        num_heads=num_heads,
                        mlp_ratio=mlp_ratio,
                        qkv_bias=qkv_bias,
                        proj_bias=proj_bias,
                        ffn_bias=ffn_bias,
                        init_values=init_values,
                        qk_norm=qk_norm,
                        rope=self.rope,
                    )
                    for _ in range(d)
                ])
                for d in depths
            ])

            self.global_blocks = nn.ModuleList([
                nn.ModuleList([
                    block_fn(
                        dim=embed_dim*2,
                        num_heads=num_heads,
                        mlp_ratio=mlp_ratio,
                        qkv_bias=qkv_bias,
                        proj_bias=proj_bias,
                        ffn_bias=ffn_bias,
                        init_values=init_values,
                        qk_norm=qk_norm,
                        rope=self.rope,
                    )
                    for _ in range(d)
                ])
                for d in depths
            ])

        self.use_reentrant = False # hardcoded to False

    def get_condition_tokens(
        self,
        aggregated_tokens_list: List[torch.Tensor],
        cond_view_idxs: torch.Tensor
    ):
        # Use tokens from the last block for conditioning
        tokens_last = aggregated_tokens_list[-1]  # [B S N_tok D]
        # Extract the camera tokens
        cond_token_idx = 1
        camera_tokens = tokens_last[:, :, [cond_token_idx]]  # [B S D]

        cond_view_idxs = cond_view_idxs.to(camera_tokens.device)
        cond_view_idxs = repeat(
            cond_view_idxs,
            "b s -> b s c d",
            c=camera_tokens.shape[2],
            d=camera_tokens.shape[3],
        )
        cond_tokens = torch.gather(camera_tokens, 1, cond_view_idxs)

        return cond_tokens

    def forward(
        self,
        images: torch.Tensor,
        aggregated_tokens_list: List[torch.Tensor],
        patch_start_idx: int,
        cond_view_idxs: torch.Tensor,
    ):
        B, S, _, H, W = images.shape

        cond_tokens = self.get_condition_tokens(
            aggregated_tokens_list, cond_view_idxs
        )

        input_tokens = []
        for k, layer_idx in enumerate(self.intermediate_layer_idx):
            layer_tokens = aggregated_tokens_list[layer_idx].clone()
            input_tokens.append(layer_tokens)

        _, _, P, C = input_tokens[0].shape

        pos = None
        if self.rope is not None:
            pos = self.position_getter(
                B * S, H // self.patch_size, W // self.patch_size, device=images.device
            )
        if patch_start_idx > 0:
            # do not use position embedding for special tokens (camera and register tokens)
            # so set pos to 0 for the special tokens
            pos = pos + 1
            pos_special = torch.zeros(B * S, patch_start_idx, 2).to(images.device).to(pos.dtype)
            pos = torch.cat([pos_special, pos], dim=1)

        frame_idx = 0
        global_idx = 0
        depth = len(self.frame_blocks[0])
        N = len(input_tokens)
        # stack all intermediate layer tokens along batch dimension
        # they are all processed by the same decoder
        s_tokens = torch.cat(input_tokens)
        s_cond_tokens = torch.cat([cond_tokens] * N, dim=0)
        s_pos = torch.cat([pos] * N, dim=0)

        # perform time conditioned attention
        for _ in range(depth):
            for attn_type in self.aa_order:
                token_idx = 0

                if attn_type == "frame":
                    s_tokens, frame_idx, _ = self._process_frame_attention(
                        s_tokens, s_cond_tokens, B * N, S, P, C, frame_idx, pos=s_pos, token_idx=token_idx
                    )
                elif attn_type == "global":
                    s_tokens, global_idx, _ = self._process_global_attention(
                        s_tokens, s_cond_tokens, B * N, S, P, C, global_idx, pos=s_pos, token_idx=token_idx
                    )
                else:
                    raise ValueError(f"Unknown attention type: {attn_type}")
        processed = [t.view(B, S, P, C) for t in s_tokens.split(B, dim=0)]

        return processed

    def _process_frame_attention(self, tokens, cond_tokens, B, S, P, C, frame_idx, pos=None, token_idx=0):
        """
        Process frame attention blocks. We keep tokens in shape (B*S, P, C).
        """
        # If needed, reshape tokens or positions:
        if tokens.shape != (B * S, P, C):
            tokens = tokens.view(B, S, P, C).view(B * S, P, C)

        if pos is not None and pos.shape != (B * S, P, 2):
            pos = pos.view(B, S, P, 2).view(B * S, P, 2)

        intermediates = []
        # by default, self.aa_block_size=1, which processes one block at a time
        for _ in range(self.aa_block_size):
            if self.training:
                tokens = checkpoint(self.frame_blocks[token_idx][frame_idx], tokens, pos, cond_tokens, use_reentrant=self.use_reentrant)
            else:
                if self.old_decoder:
                    tokens = self.frame_blocks[frame_idx](tokens, pos=pos, cond=cond_tokens)
                else:
                    tokens = self.frame_blocks[0][frame_idx](tokens, pos=pos, cond=cond_tokens)

            frame_idx += 1
            intermediates.append(tokens.view(B, S, P, C))

        return tokens, frame_idx, intermediates

    def _process_global_attention(self, tokens, cond_tokens, B, S, P, C, global_idx, pos=None, token_idx=0):
        """
        Process global attention blocks. We keep tokens in shape (B, S*P, C).
        """
        if tokens.shape != (B, S * P, C):
            tokens = tokens.view(B, S, P, C).view(B, S * P, C)

        if pos is not None and pos.shape != (B, S * P, 2):
            pos = pos.view(B, S, P, 2).view(B, S * P, 2)

        intermediates = []

        # by default, self.aa_block_size=1, which processes one block at a time
        for _ in range(self.aa_block_size):
            if self.training:
                tokens = checkpoint(self.global_blocks[token_idx][global_idx], tokens, pos, cond_tokens, True, use_reentrant=self.use_reentrant)
            else:
                if self.old_decoder:
                    tokens = self.global_blocks[global_idx](tokens, pos=pos, cond=cond_tokens, is_global=True)
                else:
                    tokens = self.global_blocks[0][global_idx](tokens, pos=pos, cond=cond_tokens, is_global=True)
            global_idx += 1
            intermediates.append(tokens.view(B, S, P, C))

        return tokens, global_idx, intermediates