| 266 | |
| 267 | |
| 268 | class FeedForwardNetwork(nn.Module): |
| 269 | def __init__( |
| 270 | self, |
| 271 | embed_dim, |
| 272 | ffn_dim, |
| 273 | activation_fn=F.gelu, |
| 274 | dropout=0.0, |
| 275 | activation_dropout=0.0, |
| 276 | layernorm_eps=1e-6, |
| 277 | subln=False, |
| 278 | subconv=False |
| 279 | ): |
| 280 | super().__init__() |
| 281 | self.embed_dim = embed_dim |
| 282 | # self.out_dim = out_dim |
| 283 | self.activation_fn = activation_fn |
| 284 | self.activation_dropout_module = torch.nn.Dropout(activation_dropout) |
| 285 | self.dropout_module = torch.nn.Dropout(dropout) |
| 286 | self.fc1 = nn.Linear(self.embed_dim, ffn_dim) |
| 287 | self.fc2 = nn.Linear(ffn_dim, self.embed_dim) |
| 288 | self.ffn_layernorm = nn.LayerNorm(ffn_dim, eps=layernorm_eps) if subln else None |
| 289 | self.dwconv = DWConv2d(ffn_dim, 3, 1, 1) if subconv else None |
| 290 | |
| 291 | def reset_parameters(self): |
| 292 | self.fc1.reset_parameters() |
| 293 | self.fc2.reset_parameters() |
| 294 | if self.ffn_layernorm is not None: |
| 295 | self.ffn_layernorm.reset_parameters() |
| 296 | |
| 297 | def forward(self, x: torch.Tensor): |
| 298 | ''' |
| 299 | x: (b h w c) |
| 300 | ''' |
| 301 | x = self.fc1(x) |
| 302 | x = self.activation_fn(x) |
| 303 | x = self.activation_dropout_module(x) |
| 304 | if self.dwconv is not None: |
| 305 | residual = x |
| 306 | x = self.dwconv(x) |
| 307 | x = x + residual |
| 308 | if self.ffn_layernorm is not None: |
| 309 | x = self.ffn_layernorm(x) |
| 310 | x = self.fc2(x) |
| 311 | x = self.dropout_module(x) |
| 312 | return x |
| 313 | |
| 314 | |
| 315 | class FeedForward(nn.Module): |