Download examples/visualizer_code/source/nets/ucpe_cd50/backbone.py from facebook/SCALE4D: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/facebook/SCALE4D/resolve/main/examples/visualizer_code/source/nets/ucpe_cd50/backbone.py
- Command line
-
hf download hf://facebook/SCALE4D/examples/visualizer_code/source/nets/ucpe_cd50/backbone.py
-
curl -L -o backbone.py https://huggingface.co/facebook/SCALE4D/resolve/main/examples/visualizer_code/source/nets/ucpe_cd50/backbone.py
12.2 kB
| # (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, | |
| ) | |