File size: 12,162 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 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 | # (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.
# Based on VideoMAE v2, BEiT, timm, DINO and DeiT code bases:
# https://github.com/OpenGVLab/VideoMAEv2
# https://github.com/microsoft/unilm/tree/master/beit
# https://github.com/rwightman/pytorch-image-models/tree/master/timm
# https://github.com/facebookresearch/deit
# https://github.com/facebookresearch/dino
"""VideoMAE v2 ViT-Giant backbone used by the UCPE CD50 model."""
from __future__ import annotations
from functools import partial
from typing import Callable, Tuple
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.models.layers import drop_path, to_2tuple, trunc_normal_
from nets.attention import memory_efficient_attention as flash_attn_func
GIANT_PATCH_SIZE = 14
GIANT_EMBED_DIM = 1408
GIANT_DEPTH = 40
GIANT_NUM_HEADS = 16
GIANT_MLP_RATIO = 48 / 11
class DropPath(nn.Module):
def __init__(self, drop_prob: float | None = None) -> None:
super().__init__()
self.drop_prob = drop_prob
def forward(self, x: torch.Tensor) -> torch.Tensor:
return drop_path(x, self.drop_prob or 0.0, self.training)
def extra_repr(self) -> str:
return f"p={self.drop_prob}"
class Mlp(nn.Module):
def __init__(
self,
in_features: int,
hidden_features: int | None = None,
out_features: int | None = None,
act_layer: Callable[..., nn.Module] = nn.GELU,
drop: float = 0.0,
) -> None:
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.drop(self.fc2(self.act(self.fc1(x))))
class Attention(nn.Module):
def __init__(
self,
dim: int,
num_heads: int = 8,
qkv_bias: bool = False,
qk_scale: float | None = None,
attn_drop: float = 0.0,
proj_drop: float = 0.0,
attn_head_dim: int | None = None,
use_flash_attn: bool = True,
) -> None:
super().__init__()
self.num_heads = num_heads
head_dim = (
attn_head_dim if attn_head_dim is not None else dim // num_heads
)
all_head_dim = head_dim * self.num_heads
self.head_dim = head_dim
self.scale = qk_scale or head_dim ** (-0.5)
self.use_flash_attn = use_flash_attn
self.attn_drop_rate = attn_drop
self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False)
self.q_bias: nn.Parameter | None
self.v_bias: nn.Parameter | None
if qkv_bias:
self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
else:
self.q_bias = None
self.v_bias = None
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(all_head_dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x: torch.Tensor) -> torch.Tensor:
(B, N, _) = x.shape
qkv_bias = None
(q_bias, v_bias) = (self.q_bias, self.v_bias)
if q_bias is not None and v_bias is not None:
qkv_bias = torch.cat(
(q_bias, torch.zeros_like(v_bias, requires_grad=False), v_bias)
)
qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
if self.use_flash_attn:
qkv = qkv.reshape(B, N, 3, self.num_heads, self.head_dim)
(q, k, v) = (qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2])
original_dtype = q.dtype
if original_dtype not in (torch.float16, torch.bfloat16):
q = q.to(torch.bfloat16)
k = k.to(torch.bfloat16)
v = v.to(torch.bfloat16)
dropout_p = self.attn_drop_rate if self.training else 0.0
x = flash_attn_func(
q, k, v, dropout_p=dropout_p, softmax_scale=self.scale
)
if original_dtype not in (torch.float16, torch.bfloat16):
x = x.to(original_dtype)
x = x.reshape(B, N, -1)
else:
qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(
2, 0, 3, 1, 4
)
(q, k, v) = (qkv[0], qkv[1], qkv[2])
attn = q * self.scale @ k.transpose(-2, -1)
attn = self.attn_drop(attn.softmax(dim=-1))
x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
return self.proj_drop(self.proj(x))
class Block(nn.Module):
def __init__(
self,
dim: int,
num_heads: int,
mlp_ratio: float = 4.0,
qkv_bias: bool = False,
qk_scale: float | None = None,
drop: float = 0.0,
attn_drop: float = 0.0,
drop_path_rate: float = 0.0,
init_values: float | None = None,
act_layer: Callable[..., nn.Module] = nn.GELU,
norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
attn_head_dim: int | None = None,
use_flash_attn: bool = True,
) -> None:
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(
dim,
num_heads=num_heads,
qkv_bias=qkv_bias,
qk_scale=qk_scale,
attn_drop=attn_drop,
proj_drop=drop,
attn_head_dim=attn_head_dim,
use_flash_attn=use_flash_attn,
)
self.drop_path = (
DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
)
self.norm2 = norm_layer(dim)
self.mlp = Mlp(
in_features=dim,
hidden_features=int(dim * mlp_ratio),
act_layer=act_layer,
drop=drop,
)
if init_values is not None and init_values > 0:
self.gamma_1 = nn.Parameter(init_values * torch.ones(dim))
self.gamma_2 = nn.Parameter(init_values * torch.ones(dim))
else:
(self.gamma_1, self.gamma_2) = (None, None)
def forward(self, x: torch.Tensor) -> torch.Tensor:
if self.gamma_1 is None:
x = x + self.drop_path(self.attn(self.norm1(x)))
return x + self.drop_path(self.mlp(self.norm2(x)))
x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x)))
return x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
class PatchEmbed(nn.Module):
def __init__(
self,
img_size: int = 224,
patch_size: int = 16,
in_chans: int = 3,
embed_dim: int = 768,
num_frames: int = 16,
tubelet_size: int = 2,
) -> None:
super().__init__()
img_size_tuple: Tuple[int, int] = to_2tuple(img_size)
patch_size_tuple: Tuple[int, int] = to_2tuple(patch_size)
spatial_patches = (
img_size_tuple[0]
// patch_size_tuple[0]
* (img_size_tuple[1] // patch_size_tuple[1])
)
self.img_size = img_size_tuple
self.tubelet_size = tubelet_size
self.patch_size = patch_size_tuple
self.num_patches = spatial_patches * (num_frames // tubelet_size)
self.proj = nn.Conv3d(
in_channels=in_chans,
out_channels=embed_dim,
kernel_size=(
tubelet_size,
patch_size_tuple[0],
patch_size_tuple[1],
),
stride=(tubelet_size, patch_size_tuple[0], patch_size_tuple[1]),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
(_, _, _, height, width) = x.shape
if height != self.img_size[0] or width != self.img_size[1]:
raise ValueError(
(
f"input {height}x{width} does not match the patch "
f"embedding's {self.img_size[0]}x{self.img_size[1]}"
)
)
return self.proj(x).flatten(2).transpose(1, 2)
def get_sinusoid_encoding_table(n_position: int, d_hid: int) -> torch.Tensor:
positions = np.arange(n_position)[:, None]
hidden_dims = np.arange(d_hid)[None, :]
table = positions / np.power(10000, 2 * (hidden_dims // 2) / d_hid)
table[:, 0::2] = np.sin(table[:, 0::2])
table[:, 1::2] = np.cos(table[:, 1::2])
return torch.from_numpy(table).float().unsqueeze(0)
class VisionTransformer(nn.Module):
def __init__(
self,
img_size: int = 224,
patch_size: int = 16,
in_chans: int = 3,
embed_dim: int = 768,
depth: int = 12,
num_heads: int = 12,
mlp_ratio: float = 4.0,
qkv_bias: bool = False,
qk_scale: float | None = None,
drop_rate: float = 0.0,
attn_drop_rate: float = 0.0,
drop_path_rate: float = 0.0,
norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
init_values: float = 0.0,
all_frames: int = 16,
tubelet_size: int = 2,
use_flash_attn: bool = True,
no_pluecker_rays: bool = False,
) -> None:
super().__init__()
self.num_features = self.embed_dim = embed_dim
self.tubelet_size = tubelet_size
self.no_pluecker_rays = no_pluecker_rays
self.patch_embed = PatchEmbed(
img_size=img_size,
patch_size=patch_size,
in_chans=in_chans,
embed_dim=embed_dim,
num_frames=all_frames,
tubelet_size=tubelet_size,
)
if not no_pluecker_rays:
self.patch_embed_pluecker_rays = PatchEmbed(
img_size=img_size,
patch_size=patch_size,
in_chans=6,
embed_dim=embed_dim,
num_frames=all_frames,
tubelet_size=tubelet_size,
)
else:
self.patch_embed_pluecker_rays = None
self.pos_embed = get_sinusoid_encoding_table(
self.patch_embed.num_patches, embed_dim
)
self.pos_drop = nn.Dropout(p=drop_rate)
decay = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]
self.blocks = nn.ModuleList(
[
Block(
dim=embed_dim,
num_heads=num_heads,
mlp_ratio=mlp_ratio,
qkv_bias=qkv_bias,
qk_scale=qk_scale,
drop=drop_rate,
attn_drop=attn_drop_rate,
drop_path_rate=decay[i],
norm_layer=norm_layer,
init_values=init_values,
use_flash_attn=use_flash_attn,
)
for i in range(depth)
]
)
self.fc_norm = norm_layer(embed_dim)
self.apply(self._init_weights)
def _init_weights(self, module: nn.Module) -> None:
if isinstance(module, nn.Linear):
trunc_normal_(module.weight, std=0.02)
if module.bias is not None:
nn.init.constant_(module.bias, 0)
elif isinstance(module, nn.LayerNorm):
nn.init.constant_(module.bias, 0)
nn.init.constant_(module.weight, 1.0)
def get_num_layers(self) -> int:
return len(self.blocks)
def vit_giant_patch14_224(
img_size: int = 224,
all_frames: int = 48,
tubelet_size: int = 2,
drop_path_rate: float = 0.0,
use_flash_attn: bool = True,
no_pluecker_rays: bool = False,
) -> VisionTransformer:
return VisionTransformer(
img_size=img_size,
patch_size=GIANT_PATCH_SIZE,
embed_dim=GIANT_EMBED_DIM,
depth=GIANT_DEPTH,
num_heads=GIANT_NUM_HEADS,
mlp_ratio=GIANT_MLP_RATIO,
qkv_bias=True,
norm_layer=partial(nn.LayerNorm, eps=1e-06),
all_frames=all_frames,
tubelet_size=tubelet_size,
drop_path_rate=drop_path_rate,
use_flash_attn=use_flash_attn,
no_pluecker_rays=no_pluecker_rays,
)
|