Serial block class. Note: In this implementation, each serial block only contains a conv-attention and a FFN (MLP) module.
| 194 | |
| 195 | |
| 196 | class SerialBlock(nn.Module): |
| 197 | """ Serial block class. |
| 198 | Note: In this implementation, each serial block only contains a conv-attention and a FFN (MLP) module. """ |
| 199 | def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0., |
| 200 | drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, shared_cpe=None, shared_crpe=None): |
| 201 | super().__init__() |
| 202 | |
| 203 | # Conv-Attention. |
| 204 | self.cpe = shared_cpe |
| 205 | |
| 206 | self.norm1 = norm_layer(dim) |
| 207 | self.factoratt_crpe = FactorAtt_ConvRelPosEnc( |
| 208 | dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop, shared_crpe=shared_crpe) |
| 209 | self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() |
| 210 | |
| 211 | # MLP. |
| 212 | self.norm2 = norm_layer(dim) |
| 213 | mlp_hidden_dim = int(dim * mlp_ratio) |
| 214 | self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) |
| 215 | |
| 216 | def forward(self, x, size: Tuple[int, int]): |
| 217 | # Conv-Attention. |
| 218 | x = self.cpe(x, size) |
| 219 | cur = self.norm1(x) |
| 220 | cur = self.factoratt_crpe(cur, size) |
| 221 | x = x + self.drop_path(cur) |
| 222 | |
| 223 | # MLP. |
| 224 | cur = self.norm2(x) |
| 225 | cur = self.mlp(cur) |
| 226 | x = x + self.drop_path(cur) |
| 227 | |
| 228 | return x |
| 229 | |
| 230 | |
| 231 | class ParallelBlock(nn.Module): |