| 25 | |
| 26 | |
| 27 | class Block(nn.Module): |
| 28 | def __init__( |
| 29 | self, |
| 30 | dim: int, |
| 31 | num_heads: int, |
| 32 | mlp_ratio: float = 4.0, |
| 33 | qkv_bias: bool = True, |
| 34 | proj_bias: bool = True, |
| 35 | ffn_bias: bool = True, |
| 36 | drop: float = 0.0, |
| 37 | attn_drop: float = 0.0, |
| 38 | init_values=None, |
| 39 | drop_path: float = 0.0, |
| 40 | act_layer: Callable[..., nn.Module] = nn.GELU, |
| 41 | norm_layer: Callable[..., nn.Module] = nn.LayerNorm, |
| 42 | attn_class: Callable[..., nn.Module] = Attention, |
| 43 | ffn_layer: Callable[..., nn.Module] = Mlp, |
| 44 | qk_norm: bool = False, |
| 45 | fused_attn: bool = True, # use F.scaled_dot_product_attention or not |
| 46 | rope=None, |
| 47 | ) -> None: |
| 48 | super().__init__() |
| 49 | |
| 50 | self.norm1 = norm_layer(dim) |
| 51 | |
| 52 | self.attn = attn_class( |
| 53 | dim, |
| 54 | num_heads=num_heads, |
| 55 | qkv_bias=qkv_bias, |
| 56 | proj_bias=proj_bias, |
| 57 | attn_drop=attn_drop, |
| 58 | proj_drop=drop, |
| 59 | qk_norm=qk_norm, |
| 60 | fused_attn=fused_attn, |
| 61 | rope=rope, |
| 62 | ) |
| 63 | |
| 64 | self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() |
| 65 | self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() |
| 66 | |
| 67 | self.norm2 = norm_layer(dim) |
| 68 | mlp_hidden_dim = int(dim * mlp_ratio) |
| 69 | self.mlp = ffn_layer( |
| 70 | in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop, bias=ffn_bias |
| 71 | ) |
| 72 | self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() |
| 73 | self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() |
| 74 | |
| 75 | self.sample_drop_ratio = drop_path |
| 76 | |
| 77 | def forward(self, x: Tensor, pos=None, enable_ulysses_cp=False, |
| 78 | num_patches=None, num_special=None, num_frames=None, enable_3d_rope=False) -> Tensor: |
| 79 | def attn_residual_func(x: Tensor, pos=None) -> Tensor: |
| 80 | return self.ls1(self.attn(self.norm1(x), pos=pos, enable_ulysses_cp=enable_ulysses_cp, |
| 81 | num_patches=num_patches, num_special=num_special, num_frames=num_frames, |
| 82 | enable_3d_rope=enable_3d_rope)) |
| 83 | |
| 84 | def ffn_residual_func(x: Tensor) -> Tensor: |