| 38 | |
| 39 | |
| 40 | class Block(nn.Module): |
| 41 | def __init__( |
| 42 | self, |
| 43 | dim: int, |
| 44 | num_heads: int, |
| 45 | mlp_ratio: float = 4.0, |
| 46 | qkv_bias: bool = False, |
| 47 | proj_bias: bool = True, |
| 48 | ffn_bias: bool = True, |
| 49 | drop: float = 0.0, |
| 50 | attn_drop: float = 0.0, |
| 51 | init_values=None, |
| 52 | drop_path: float = 0.0, |
| 53 | act_layer: Callable[..., nn.Module] = nn.GELU, |
| 54 | norm_layer: Callable[..., nn.Module] = nn.LayerNorm, |
| 55 | attn_class: Callable[..., nn.Module] = Attention, |
| 56 | ffn_layer: Callable[..., nn.Module] = Mlp, |
| 57 | ) -> None: |
| 58 | super().__init__() |
| 59 | # print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}") |
| 60 | self.norm1 = norm_layer(dim) |
| 61 | self.attn = attn_class( |
| 62 | dim, |
| 63 | num_heads=num_heads, |
| 64 | qkv_bias=qkv_bias, |
| 65 | proj_bias=proj_bias, |
| 66 | attn_drop=attn_drop, |
| 67 | proj_drop=drop, |
| 68 | ) |
| 69 | self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() |
| 70 | self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() |
| 71 | |
| 72 | self.norm2 = norm_layer(dim) |
| 73 | mlp_hidden_dim = int(dim * mlp_ratio) |
| 74 | self.mlp = ffn_layer( |
| 75 | in_features=dim, |
| 76 | hidden_features=mlp_hidden_dim, |
| 77 | act_layer=act_layer, |
| 78 | drop=drop, |
| 79 | bias=ffn_bias, |
| 80 | ) |
| 81 | self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() |
| 82 | self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() |
| 83 | |
| 84 | self.sample_drop_ratio = drop_path |
| 85 | |
| 86 | def forward(self, x: Tensor) -> Tensor: |
| 87 | def attn_residual_func(x: Tensor) -> Tensor: |
| 88 | return self.ls1(self.attn(self.norm1(x))) |
| 89 | |
| 90 | def ffn_residual_func(x: Tensor) -> Tensor: |
| 91 | return self.ls2(self.mlp(self.norm2(x))) |
| 92 | |
| 93 | if self.training and self.sample_drop_ratio > 0.1: |
| 94 | # the overhead is compensated only for a drop path rate larger than 0.1 |
| 95 | x = drop_add_residual_stochastic_depth( |
| 96 | x, |
| 97 | residual_func=attn_residual_func, |