Spaces:
Running on Zero

File size: 8,917 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
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
# DPT head predicting a pointmap and a confidence map from multi-level ViT tokens.
#
# Adapted from VGGT (https://github.com/facebookresearch/vggt) and Depth Anything 3
# (https://github.com/ByteDance-Seed/Depth-Anything-3, Apache-2.0); both inspired by
# Depth Anything V2 (https://github.com/DepthAnything/Depth-Anything-V2).
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# Changes w.r.t. the sources: the output convolutions are replaced by the memory-efficient
# variant of VGGT-Omega (a 1x1 projection to sub-pixels at the fused resolution followed by
# pixel shuffle; the low-channel logits are then resized to the image size since Flow4RT
# uses 14x14 patches); fusion blocks are gradient-checkpointed during training.

from typing import List, Tuple

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint


class DPTHead(nn.Module):
    """Decodes tokens of 4 read-out layers into a point map (B, H, W, 3) and a raw per-pixel
    scalar (B, H, W), whose activation depends on the branch (confidence or rigidity)."""

    def __init__(self, dim_in: int, patch_size: int = 14, output_dim: int = 4, features: int = 256,
                 out_channels: List[int] = (256, 512, 1024, 1024)) -> None:
        super().__init__()
        self.patch_size = patch_size
        self.output_dim = output_dim

        self.norm = nn.LayerNorm(dim_in)
        self.projects = nn.ModuleList([nn.Conv2d(dim_in, oc, kernel_size=1) for oc in out_channels])
        self.resize_layers = nn.ModuleList([
            nn.ConvTranspose2d(out_channels[0], out_channels[0], kernel_size=4, stride=4),
            nn.ConvTranspose2d(out_channels[1], out_channels[1], kernel_size=2, stride=2),
            nn.Identity(),
            nn.Conv2d(out_channels[3], out_channels[3], kernel_size=3, stride=2, padding=1),
        ])

        self.scratch = nn.Module()
        for i, oc in enumerate(out_channels):
            setattr(self.scratch, f"layer{i + 1}_rn", nn.Conv2d(oc, features, kernel_size=3, padding=1, bias=False))
        # in-place ReLUs would overwrite checkpointed inputs before recomputation
        self.scratch.refinenet1 = FeatureFusionBlock(features)
        self.scratch.refinenet2 = FeatureFusionBlock(features)
        self.scratch.refinenet3 = FeatureFusionBlock(features)
        self.scratch.refinenet4 = FeatureFusionBlock(features, has_residual=False)

        self.shuffle_factor = max(1, patch_size // 4)
        self.scratch.output_conv2 = nn.Conv2d(features, output_dim * self.shuffle_factor**2, kernel_size=1)

    def forward(self, tokens_list: List[torch.Tensor], image_size: Tuple[int, int],
                frames_chunk_size: int = 8) -> Tuple[torch.Tensor, torch.Tensor]:
        """tokens_list: 4 tensors (B, P, C) from different levels; processed in chunks of frames."""
        B = tokens_list[0].shape[0]
        if frames_chunk_size is None or frames_chunk_size >= B:
            return self._forward_impl(tokens_list, image_size)
        preds = [self._forward_impl([t[s:s + frames_chunk_size] for t in tokens_list], image_size)
                 for s in range(0, B, frames_chunk_size)]
        return tuple(torch.cat(p, dim=0) for p in zip(*preds))

    def _forward_impl(self, tokens_list, image_size):
        H, W = image_size
        patch_h, patch_w = H // self.patch_size, W // self.patch_size

        out = []
        for i, x in enumerate(tokens_list):
            x = self.norm(x)
            x = x.permute(0, 2, 1).reshape(x.shape[0], x.shape[-1], patch_h, patch_w)
            x = self.projects[i](x)
            x = _apply_pos_embed(x, W, H)
            x = self.resize_layers[i](x)
            out.append(x)

        out = self._fuse(out)
        out = _apply_pos_embed(out, W, H)
        out = self.scratch.output_conv2(out)
        out = F.pixel_shuffle(out, self.shuffle_factor)
        out = custom_interpolate(out, (patch_h * self.patch_size, patch_w * self.patch_size))
        out = out.permute(0, 2, 3, 1)  # B, H, W, C

        pts3d, scalar = out.split([3, 1], dim=-1)
        return norm_exp_transform(pts3d), scalar.squeeze(-1)

    def _fuse(self, features: List[torch.Tensor]) -> torch.Tensor:
        layers_rn = [getattr(self.scratch, f"layer{i + 1}_rn")(f) for i, f in enumerate(features)]
        sizes = [x.shape[2:] for x in layers_rn]
        s = self.scratch

        out = self._run(lambda x: s.refinenet4(x, size=sizes[2]), layers_rn[3])
        out = self._run(lambda x, r: s.refinenet3(x, r, size=sizes[1]), out, layers_rn[2])
        out = self._run(lambda x, r: s.refinenet2(x, r, size=sizes[0]), out, layers_rn[1])
        out = self._run(lambda x, r: s.refinenet1(x, r, size=sizes[0]), out, layers_rn[0])
        return out

    def _run(self, fn, *args):
        if self.training:
            return checkpoint(fn, *args, use_reentrant=False)
        return fn(*args)


def norm_exp_transform(x: torch.Tensor) -> torch.Tensor:
    """Maps the network output to a point: keeps the direction, exponentiates the norm."""
    d = x.norm(dim=-1, keepdim=True).clamp(min=1e-8)
    return x / d * torch.expm1(d)


class ResidualConvUnit(nn.Module):
    def __init__(self, features: int):
        super().__init__()
        self.conv1 = nn.Conv2d(features, features, kernel_size=3, padding=1, bias=True)
        self.conv2 = nn.Conv2d(features, features, kernel_size=3, padding=1, bias=True)
        self.activation = nn.ReLU(inplace=False)

    def forward(self, x):
        out = self.conv1(self.activation(x))
        out = self.conv2(self.activation(out))
        return out + x


class FeatureFusionBlock(nn.Module):
    def __init__(self, features: int, has_residual: bool = True):
        super().__init__()
        self.out_conv = nn.Conv2d(features, features, kernel_size=1, bias=True)
        self.has_residual = has_residual
        if has_residual:
            self.resConfUnit1 = ResidualConvUnit(features)
        self.resConfUnit2 = ResidualConvUnit(features)

    def forward(self, x, residual=None, size=None):
        if self.has_residual:
            x = x + self.resConfUnit1(residual)
        x = self.resConfUnit2(x)
        x = custom_interpolate(x, size)
        return self.out_conv(x)


def custom_interpolate(x: torch.Tensor, size: Tuple[int, int]) -> torch.Tensor:
    """Bilinear interpolation (align_corners=True), chunked to avoid INT_MAX issues."""
    INT_MAX = 1610612736
    input_elements = size[0] * size[1] * x.shape[0] * x.shape[1]
    if input_elements > INT_MAX:
        chunks = torch.chunk(x, chunks=(input_elements // INT_MAX) + 1, dim=0)
        return torch.cat([F.interpolate(c, size=size, mode="bilinear", align_corners=True) for c in chunks]).contiguous()
    return F.interpolate(x, size=size, mode="bilinear", align_corners=True)


def _apply_pos_embed(x: torch.Tensor, W: int, H: int, ratio: float = 0.1) -> torch.Tensor:
    patch_h, patch_w = x.shape[-2:]
    pos_embed = create_uv_grid(patch_w, patch_h, aspect_ratio=W / H, dtype=x.dtype, device=x.device)
    pos_embed = position_grid_to_embed(pos_embed, x.shape[1]) * ratio
    return x + pos_embed.permute(2, 0, 1)[None].expand(x.shape[0], -1, -1, -1)


def position_grid_to_embed(pos_grid: torch.Tensor, embed_dim: int, omega_0: float = 100) -> torch.Tensor:
    """(H, W, 2) grid -> (H, W, embed_dim) sinusoidal embedding."""
    H, W, _ = pos_grid.shape
    pos_flat = pos_grid.reshape(-1, 2)
    emb_x = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 0], omega_0=omega_0)
    emb_y = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 1], omega_0=omega_0)
    return torch.cat([emb_x, emb_y], dim=-1).view(H, W, embed_dim)


def make_sincos_pos_embed(embed_dim: int, pos: torch.Tensor, omega_0: float = 100) -> torch.Tensor:
    device = pos.device
    omega = torch.arange(embed_dim // 2, dtype=torch.float32 if device.type == "mps" else torch.double, device=device)
    omega /= embed_dim / 2.0
    omega = 1.0 / omega_0**omega
    out = torch.einsum("m,d->md", pos.reshape(-1), omega)
    return torch.cat([torch.sin(out), torch.cos(out)], dim=1).float()


def create_uv_grid(width: int, height: int, aspect_ratio: float, dtype=None, device=None) -> torch.Tensor:
    """(width, height, 2) UV grid spanning the image plane normalized by its diagonal
    (from MoGe, https://github.com/microsoft/moge)."""
    diag_factor = (aspect_ratio**2 + 1.0) ** 0.5
    span_x = aspect_ratio / diag_factor
    span_y = 1.0 / diag_factor
    left_x, right_x = -span_x * (width - 1) / width, span_x * (width - 1) / width
    top_y, bottom_y = -span_y * (height - 1) / height, span_y * (height - 1) / height
    x_coords = torch.linspace(left_x, right_x, steps=width, dtype=dtype, device=device)
    y_coords = torch.linspace(top_y, bottom_y, steps=height, dtype=dtype, device=device)
    uu, vv = torch.meshgrid(x_coords, y_coords, indexing="xy")
    return torch.stack((uu, vv), dim=-1)