# Transformer building blocks shared by the geometry blocks and the motion blocks. # # 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. the sources: merged into one file, removed options that are unused by # Flow4RT (dropout, drop-path / stochastic depth, xFormers, LoRA, attention masks, # returning attention weights, RoPE in cross-attention). from typing import Dict, Optional, Tuple import torch import torch.nn.functional as F from torch import Tensor, nn class Mlp(nn.Module): def __init__(self, in_features: int, hidden_features: int, bias: bool = True) -> None: super().__init__() self.fc1 = nn.Linear(in_features, hidden_features, bias=bias) self.act = nn.GELU() self.fc2 = nn.Linear(hidden_features, in_features, bias=bias) def forward(self, x: Tensor) -> Tensor: return self.fc2(self.act(self.fc1(x))) class SwiGLUFFN(nn.Module): """SwiGLU FFN with the hidden size rounding of DINOv2's `SwiGLUFFNFused`.""" def __init__(self, in_features: int, hidden_features: int, bias: bool = True) -> None: super().__init__() hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8 self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias) self.w3 = nn.Linear(hidden_features, in_features, bias=bias) def forward(self, x: Tensor) -> Tensor: x1, x2 = self.w12(x).chunk(2, dim=-1) return self.w3(F.silu(x1) * x2) class LayerScale(nn.Module): def __init__(self, dim: int, init_values: float) -> None: super().__init__() self.gamma = nn.Parameter(init_values * torch.ones(dim)) def forward(self, x: Tensor) -> Tensor: return x * self.gamma class PatchEmbed(nn.Module): """(B, 3, H, W) image -> (B, H*W / patch_size**2, D) patch tokens.""" def __init__(self, img_size: int, patch_size: int, in_chans: int = 3, embed_dim: int = 768) -> None: super().__init__() self.patch_size = patch_size self.num_patches = (img_size // patch_size) ** 2 self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) def forward(self, x: Tensor) -> Tensor: H, W = x.shape[-2:] assert H % self.patch_size == 0 and W % self.patch_size == 0, \ f"Image size {H}x{W} is not a multiple of the patch size {self.patch_size}" return self.proj(x).flatten(2).transpose(1, 2) # -------------------------------------------------------------------------------------- # 2D rotary position embedding # -------------------------------------------------------------------------------------- class PositionGetter: """Generates and caches the (y, x) grid positions of patches.""" def __init__(self): self.position_cache: Dict[Tuple[int, int], Tensor] = {} def __call__(self, batch_size: int, height: int, width: int, device: torch.device) -> Tensor: if (height, width) not in self.position_cache: y_coords = torch.arange(height, device=device) x_coords = torch.arange(width, device=device) self.position_cache[height, width] = torch.cartesian_prod(y_coords, x_coords) positions = self.position_cache[height, width] return positions.view(1, height * width, 2).expand(batch_size, -1, -1).clone() class RotaryPositionEmbedding2D(nn.Module): """2D RoPE: the first half of the channels encodes y, the second half x.""" def __init__(self, frequency: float = 100.0): super().__init__() self.base_frequency = frequency self.frequency_cache: Dict[Tuple, Tuple[Tensor, Tensor]] = {} def _compute_frequency_components(self, dim, seq_len, device, dtype): cache_key = (dim, seq_len, device, dtype) if cache_key not in self.frequency_cache: exponents = torch.arange(0, dim, 2, device=device).float() / dim inv_freq = 1.0 / (self.base_frequency**exponents) positions = torch.arange(seq_len, device=device, dtype=inv_freq.dtype) angles = torch.einsum("i,j->ij", positions, inv_freq).to(dtype) angles = torch.cat((angles, angles), dim=-1) self.frequency_cache[cache_key] = (angles.cos().to(dtype), angles.sin().to(dtype)) return self.frequency_cache[cache_key] @staticmethod def _rotate_features(x: Tensor) -> Tensor: x1, x2 = x.chunk(2, dim=-1) return torch.cat((-x2, x1), dim=-1) def _apply_1d_rope(self, tokens, positions, cos_comp, sin_comp): cos = F.embedding(positions, cos_comp)[:, None, :, :] sin = F.embedding(positions, sin_comp)[:, None, :, :] return (tokens * cos) + (self._rotate_features(tokens) * sin) def forward(self, tokens: Tensor, positions: Tensor) -> Tensor: """tokens: (B, heads, N, C); positions: (B, N, 2) integer (y, x).""" feature_dim = tokens.size(-1) // 2 max_position = int(positions.max()) + 1 cos_comp, sin_comp = self._compute_frequency_components(feature_dim, max_position, tokens.device, tokens.dtype) vertical, horizontal = tokens.chunk(2, dim=-1) vertical = self._apply_1d_rope(vertical, positions[..., 0], cos_comp, sin_comp) horizontal = self._apply_1d_rope(horizontal, positions[..., 1], cos_comp, sin_comp) return torch.cat((vertical, horizontal), dim=-1) # -------------------------------------------------------------------------------------- # Attention # -------------------------------------------------------------------------------------- class Attention(nn.Module): def __init__(self, dim: int, num_heads: int, qkv_bias: bool = True, qk_norm: bool = False, rope=None) -> None: super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.q_norm = nn.LayerNorm(head_dim) if qk_norm else nn.Identity() self.k_norm = nn.LayerNorm(head_dim) if qk_norm else nn.Identity() self.proj = nn.Linear(dim, dim) self.rope = rope def forward(self, x: Tensor, pos: Optional[Tensor] = None) -> Tensor: B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] q, k = self.q_norm(q), self.k_norm(k) if self.rope is not None and pos is not None: q = self.rope(q, pos) k = self.rope(k, pos) x = F.scaled_dot_product_attention(q, k, v) x = x.transpose(1, 2).reshape(B, N, C) return self.proj(x) class CrossAttention(nn.Module): def __init__(self, dim: int, num_heads: int, qkv_bias: bool = True, qk_norm: bool = False) -> None: super().__init__() self.num_heads = num_heads self.head_dim = dim // num_heads self.toq = nn.Linear(dim, dim, bias=qkv_bias) self.tok = nn.Linear(dim, dim, bias=qkv_bias) self.tov = nn.Linear(dim, dim, bias=qkv_bias) self.q_norm = nn.LayerNorm(self.head_dim) if qk_norm else nn.Identity() self.k_norm = nn.LayerNorm(self.head_dim) if qk_norm else nn.Identity() self.proj = nn.Linear(dim, dim) def forward(self, x: Tensor, y: Tensor) -> Tensor: B, Nx, C = x.shape Ny = y.shape[1] q = self.toq(x).reshape(B, Nx, self.num_heads, self.head_dim).permute(0, 2, 1, 3) k = self.tok(y).reshape(B, Ny, self.num_heads, self.head_dim).permute(0, 2, 1, 3) v = self.tov(y).reshape(B, Ny, self.num_heads, self.head_dim).permute(0, 2, 1, 3) q, k = self.q_norm(q), self.k_norm(k) x = F.scaled_dot_product_attention(q, k, v) x = x.transpose(1, 2).reshape(B, Nx, C) return self.proj(x) # -------------------------------------------------------------------------------------- # Transformer blocks # -------------------------------------------------------------------------------------- class Block(nn.Module): """Pre-norm self-attention block with LayerScale (DINOv2).""" def __init__(self, dim: int, num_heads: int, mlp_ratio: float = 4.0, ffn_layer=Mlp, init_values=None, qk_norm: bool = False, rope=None, ln_eps: float = 1e-5) -> None: super().__init__() self.norm1 = nn.LayerNorm(dim, eps=ln_eps) self.attn = Attention(dim, num_heads=num_heads, qk_norm=qk_norm, rope=rope) self.ls1 = LayerScale(dim, init_values) if init_values else nn.Identity() self.norm2 = nn.LayerNorm(dim, eps=ln_eps) self.mlp = ffn_layer(dim, int(dim * mlp_ratio)) self.ls2 = LayerScale(dim, init_values) if init_values else nn.Identity() def forward(self, x: Tensor, pos: Optional[Tensor] = None) -> Tensor: x = x + self.ls1(self.attn(self.norm1(x), pos=pos)) x = x + self.ls2(self.mlp(self.norm2(x))) return x def modulate(x: Tensor, shift: Tensor, scale: Tensor) -> Tensor: return x * (1 + scale.unsqueeze(-2)) + shift.unsqueeze(-2) class AdaLNBlock(nn.Module): """Self-attention block whose LayerNorms are modulated by a condition vector (DiT-style adaLN-Zero).""" def __init__(self, dim: int, num_heads: int, mlp_ratio: float = 4.0, qk_norm: bool = False) -> None: super().__init__() self.norm1 = nn.LayerNorm(dim) self.attn = Attention(dim, num_heads=num_heads, qk_norm=qk_norm) self.norm2 = nn.LayerNorm(dim) self.mlp = Mlp(dim, int(dim * mlp_ratio)) self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(dim, 6 * dim, bias=True)) nn.init.zeros_(self.adaLN_modulation[-1].weight) nn.init.zeros_(self.adaLN_modulation[-1].bias) def forward(self, x: Tensor, cond: Tensor) -> Tensor: """x: (B, N, C); cond: (B, C).""" shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(cond).chunk(6, dim=-1) x = x + gate_msa.unsqueeze(-2) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa)) x = x + gate_mlp.unsqueeze(-2) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp)) return x class CrossBlock(nn.Module): """Pre-norm cross-attention block: tokens `x` attend to tokens `y`.""" def __init__(self, dim: int, num_heads: int, mlp_ratio: float = 4.0, init_values: float = 0.01, qk_norm: bool = False) -> None: super().__init__() self.norm1 = nn.LayerNorm(dim) self.normy = nn.LayerNorm(dim) self.attn = CrossAttention(dim, num_heads=num_heads, qk_norm=qk_norm) self.ls1 = LayerScale(dim, init_values) self.norm2 = nn.LayerNorm(dim) self.mlp = Mlp(dim, int(dim * mlp_ratio)) self.ls2 = LayerScale(dim, init_values) def forward(self, x: Tensor, y: Tensor) -> Tensor: x = x + self.ls1(self.attn(self.norm1(x), self.normy(y))) x = x + self.ls2(self.mlp(self.norm2(x))) return x