Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection" This Block has a slightly different structure compared to a regular prenorm Transformer block. The standard block is: LN -> MHA/MLP -> Add. [Ref: https://arxiv.org/abs/2002.0
(
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False
)
| 336 | |
| 337 | class Block(nn.Module): |
| 338 | def __init__( |
| 339 | self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False |
| 340 | ): |
| 341 | """ |
| 342 | Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection" |
| 343 | |
| 344 | This Block has a slightly different structure compared to a regular |
| 345 | prenorm Transformer block. |
| 346 | The standard block is: LN -> MHA/MLP -> Add. |
| 347 | [Ref: https://arxiv.org/abs/2002.04745] |
| 348 | Here we have: Add -> LN -> Mixer, returning both |
| 349 | the hidden_states (output of the mixer) and the residual. |
| 350 | This is purely for performance reasons, as we can fuse add and LayerNorm. |
| 351 | The residual needs to be provided (except for the very first block). |
| 352 | """ |
| 353 | super().__init__() |
| 354 | self.residual_in_fp32 = residual_in_fp32 |
| 355 | self.fused_add_norm = fused_add_norm |
| 356 | self.mixer = mixer_cls(dim) |
| 357 | self.norm = norm_cls(dim) |
| 358 | if self.fused_add_norm: |
| 359 | assert RMSNorm is not None, "RMSNorm import fails" |
| 360 | assert isinstance( |
| 361 | self.norm, (nn.LayerNorm, RMSNorm) |
| 362 | ), "Only LayerNorm and RMSNorm are supported for fused_add_norm" |
| 363 | |
| 364 | def forward( |
| 365 | self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None |