Spaces:
Running on Zero

File size: 6,798 Bytes
a863b67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Geometry blocks: the DINOv2 ViT-g backbone with alternating frame-wise / global attention of
# Depth Anything 3 and 4RC.
#
# Adapted from DINOv2 (https://github.com/facebookresearch/dinov2, Apache-2.0),
# Depth Anything 3 (https://github.com/ByteDance-Seed/Depth-Anything-3, Apache-2.0)
# and 4RC (https://github.com/Luo-Yihang/4RC, S-Lab License 1.0).
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# Changes w.r.t. 4RC: no camera token and no reference-view selection/reordering (the
# input frame order is kept); intermediate layers are returned without concatenating
# frame-wise tokens; generic ViT sizes, register tokens, masking and drop-path removed; the
# `pretrained` wrapper module is dropped (weight names `backbone.pretrained.*` -> `geometry_blocks.*`).

import math
from typing import List, Tuple

import torch
import torch.nn as nn
from einops import rearrange
from torch.utils.checkpoint import checkpoint

from .layers import Block, PatchEmbed, PositionGetter, RotaryPositionEmbedding2D, SwiGLUFFN


class GeometryBlocks(nn.Module):
    """ViT-g/14. Blocks with index >= `alt_start` alternate between within-view (even) and
    cross-view (odd) attention; a learned time token is inserted at `alt_start`.

    Input: images (B, S, 3, H, W) in [0, 1].
    Output: for each read-out layer, a tuple
        (patch_tokens (B, S, P, C) after the final norm, cls_token (B, S, C), time_token (B, S, C)).
    """

    patch_start_idx = 2  # [cls, time, patches...]

    def __init__(self, readout_layers: List[int] = (19, 27, 33, 39), alt_start: int = 13, qknorm_start: int = 13,
                 rope_start: int = 13, rope_freq: float = 100, img_size: int = 518, patch_size: int = 14,
                 embed_dim: int = 1536, depth: int = 40, num_heads: int = 24, mlp_ratio: float = 4.0,
                 interpolate_offset: float = 0.1):
        super().__init__()
        self.readout_layers = list(readout_layers)
        self.embed_dim = embed_dim
        self.patch_size = patch_size
        self.alt_start = alt_start
        self.rope_start = rope_start
        self.interpolate_offset = interpolate_offset

        self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size, embed_dim=embed_dim)
        num_patches = self.patch_embed.num_patches
        self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
        self.time_token = nn.Parameter(torch.randn(1, 1, embed_dim))
        self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))

        self.rope = RotaryPositionEmbedding2D(frequency=rope_freq)
        self.position_getter = PositionGetter()
        self.blocks = nn.ModuleList([
            Block(
                dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, ffn_layer=SwiGLUFFN, init_values=1.0,
                qk_norm=i >= qknorm_start, rope=self.rope if i >= rope_start else None, ln_eps=1e-6,
            )
            for i in range(depth)
        ])
        self.norm = nn.LayerNorm(embed_dim)

    def interpolate_pos_encoding(self, x, h, w):
        previous_dtype = x.dtype
        npatch = x.shape[1] - 1
        N = self.pos_embed.shape[1] - 1
        if npatch == N and w == h:
            return self.pos_embed
        pos_embed = self.pos_embed.float()
        class_pos_embed = pos_embed[:, 0]
        patch_pos_embed = pos_embed[:, 1:]
        dim = x.shape[-1]
        h0, w0 = h // self.patch_size, w // self.patch_size
        M = int(math.sqrt(N))
        assert N == M * M
        # DINOv2 adds a small offset to avoid floating point errors in the interpolation
        scale_factor = (float(h0 + self.interpolate_offset) / M, float(w0 + self.interpolate_offset) / M)
        patch_pos_embed = nn.functional.interpolate(
            patch_pos_embed.reshape(1, M, M, dim).permute(0, 3, 1, 2),
            mode="bicubic", antialias=False, scale_factor=scale_factor,
        )
        assert (h0, w0) == patch_pos_embed.shape[-2:]
        patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
        return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype)

    def prepare_tokens(self, x):
        B, S, _, H, W = x.shape
        x = self.patch_embed(x.flatten(0, 1))
        x = torch.cat((self.cls_token.expand(B * S, -1, -1), x), dim=1)
        x = x + self.interpolate_pos_encoding(x, H, W)
        return rearrange(x, "(b s) n c -> b s n c", b=B, s=S)

    def prepare_rope(self, B, S, H, W, device):
        """Positions for frame-wise attention (patch grid) and global attention (all patches
        share one position, so RoPE only separates special tokens from patches)."""
        pos = self.position_getter(B * S, H // self.patch_size, W // self.patch_size, device=device)
        pos = rearrange(pos, "(b s) n c -> b s n c", b=B)
        pos_special = torch.zeros(B, S, self.patch_start_idx, 2, device=device, dtype=pos.dtype)
        pos_local = torch.cat([pos_special, pos + 1], dim=2)
        pos_global = torch.cat([pos_special, torch.ones_like(pos)], dim=2)
        return pos_local, pos_global

    def run_block(self, x, block, attn_type, pos):
        b, s = x.shape[:2]
        if attn_type == "local":
            x, pos = x.flatten(0, 1), pos.flatten(0, 1) if pos is not None else None
        else:
            x, pos = x.flatten(1, 2), pos.flatten(1, 2) if pos is not None else None

        if self.training:
            x = checkpoint(block, x, pos, use_reentrant=False)
        else:
            x = block(x, pos=pos)

        if attn_type == "local":
            return rearrange(x, "(b s) n c -> b s n c", b=b, s=s)
        return rearrange(x, "b (s n) c -> b s n c", b=b, s=s)

    def forward(self, x: torch.Tensor) -> List[Tuple[torch.Tensor, torch.Tensor, torch.Tensor]]:
        B, S, _, H, W = x.shape
        x = self.prepare_tokens(x)
        pos_local, pos_global = self.prepare_rope(B, S, H, W, x.device)

        outputs = []
        for i, blk in enumerate(self.blocks):
            if i == self.alt_start:  # insert the time token after the cls token
                time_token = self.time_token.expand(B, S, -1).unsqueeze(2)
                x = torch.cat([x[:, :, :1], time_token, x[:, :, 1:]], dim=2)

            use_rope = i >= self.rope_start
            if i >= self.alt_start and i % 2 == 1:
                x = self.run_block(x, blk, "global", pos_global if use_rope else None)
            else:
                x = self.run_block(x, blk, "local", pos_local if use_rope else None)

            if i in self.readout_layers:
                outputs.append(x)

        # special tokens are returned before the final norm, patch tokens after
        return [
            (self.norm(out)[:, :, self.patch_start_idx:], out[:, :, 0], out[:, :, 1])
            for out in outputs
        ]