import torch.nn as nn import torch.nn.functional as F from typing import Callable import collections from itertools import repeat def _ntuple(n): def parse(x): if isinstance(x, collections.abc.Iterable) and not isinstance(x, str): return tuple(x) return tuple(repeat(x, n)) return parse def exists(val): return val is not None def default(val, d): return val if exists(val) else d to_2tuple = _ntuple(2) class Mlp(nn.Module): """MLP as used in Vision Transformer, MLP-Mixer and related networks""" def __init__( self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, bias=True, drop=0.0, ): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features bias = to_2tuple(bias) drop_probs = to_2tuple(drop) self.fc1 = nn.Linear(in_features, hidden_features, bias=bias[0]) self.act = act_layer() self.drop1 = nn.Dropout(drop_probs[0]) self.fc2 = nn.Linear(hidden_features, out_features, bias=bias[1]) self.drop2 = nn.Dropout(drop_probs[1]) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop1(x) x = self.fc2(x) x = self.drop2(x) return x class Attention(nn.Module): def __init__( self, query_dim, context_dim=None, num_heads=8, dim_head=48, qkv_bias=False ): super().__init__() self.inner_dim = dim_head * num_heads context_dim = default(context_dim, query_dim) self.heads = num_heads self.dim_head = dim_head self.to_q = nn.Linear(query_dim, self.inner_dim, bias=qkv_bias) self.to_kv = nn.Linear(context_dim, self.inner_dim * 2, bias=qkv_bias) self.to_out = nn.Linear(self.inner_dim, query_dim) def forward(self, x, context=None, attn_bias=None): B, N1, C = x.shape h = self.heads d = self.dim_head q = self.to_q(x).reshape(B, N1, h, d).permute(0, 2, 1, 3) context = default(context, x) k, v = self.to_kv(context).chunk(2, dim=-1) N2 = context.shape[1] k = k.reshape(B, N2, h, d).permute(0, 2, 1, 3) v = v.reshape(B, N2, h, d).permute(0, 2, 1, 3) attn_output = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_bias) x = attn_output.transpose(1, 2).reshape(B, N1, self.inner_dim) return self.to_out(x) class AttnBlock(nn.Module): def __init__( self, hidden_size, num_heads, attn_class: Callable[..., nn.Module] = Attention, mlp_ratio=4.0, **block_kwargs ): super().__init__() self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.attn = attn_class( hidden_size, num_heads=num_heads, qkv_bias=True, **block_kwargs ) self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) mlp_hidden_dim = int(hidden_size * mlp_ratio) approx_gelu = lambda: nn.GELU(approximate="tanh") self.mlp = Mlp( in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=0, ) def forward(self, x): x = x + self.attn(self.norm1(x)) x = x + self.mlp(self.norm2(x)) return x class CrossAttnBlock(nn.Module): def __init__( self, hidden_size, context_dim, num_heads=1, mlp_ratio=4.0, **block_kwargs ): super().__init__() self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.norm_context = nn.LayerNorm(hidden_size) self.cross_attn = Attention( hidden_size, context_dim=context_dim, num_heads=num_heads, qkv_bias=True, **block_kwargs ) self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) mlp_hidden_dim = int(hidden_size * mlp_ratio) approx_gelu = lambda: nn.GELU(approximate="tanh") self.mlp = Mlp( in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=0, ) def forward(self, x, context, mask=None): if mask is not None: if mask.shape[1] == x.shape[1]: mask = mask[:, None, :, None].expand( -1, self.cross_attn.heads, -1, context.shape[1] ) else: mask = mask[:, None, None].expand( -1, self.cross_attn.heads, x.shape[1], -1 ) fill_neg_value = - 1e6 attn_bias = (~mask) * fill_neg_value else: attn_bias = None x = x + self.cross_attn( self.norm1(x), context=self.norm_context(context), attn_bias=attn_bias ) x = x + self.mlp(self.norm2(x)) return x