Transformer module that applies multi-head attention and feed-forward layers. Args: dim (int): The dimension of the input and output tensors. heads (int): The number of attention heads. depth (int): The number of transformer layers. ff_mult (int, optional):
| 37 | |
| 38 | |
| 39 | class Transformer(nn.Module): |
| 40 | """ |
| 41 | Transformer module that applies multi-head attention and feed-forward layers. |
| 42 | |
| 43 | Args: |
| 44 | dim (int): The dimension of the input and output tensors. |
| 45 | heads (int): The number of attention heads. |
| 46 | depth (int): The number of transformer layers. |
| 47 | ff_mult (int, optional): The multiplier for the hidden dimension in the feed-forward layers. |
| 48 | Defaults to 2. |
| 49 | *args: Variable length argument list. |
| 50 | **kwargs: Arbitrary keyword arguments. |
| 51 | |
| 52 | Attributes: |
| 53 | layers (nn.ModuleList): List of multi-head attention layers. |
| 54 | ffn_layers (nn.ModuleList): List of feed-forward layers. |
| 55 | |
| 56 | """ |
| 57 | |
| 58 | def __init__( |
| 59 | self, dim: int, heads: int, depth: int, ff_mult: int = 2, *args, **kwargs |
| 60 | ): |
| 61 | super().__init__() |
| 62 | self.layers = nn.ModuleList([]) |
| 63 | self.ffn_layers = nn.ModuleList([]) |
| 64 | |
| 65 | for _ in range(depth): |
| 66 | self.layers.append(BitMGQA(dim, heads, *args, **kwargs)) |
| 67 | |
| 68 | self.ffn_layers.append( |
| 69 | BitFeedForward( |
| 70 | dim, |
| 71 | dim, |
| 72 | ff_mult, |
| 73 | swish=True, |
| 74 | post_act_ln=True, |
| 75 | dropout=0.1, |
| 76 | ), |
| 77 | ) |
| 78 | |
| 79 | # Norm |
| 80 | self.norm = nn.LayerNorm(dim) |
| 81 | |
| 82 | def forward(self, x: Tensor, *args, **kwargs) -> Tensor: |
| 83 | skip = x |
| 84 | for attn, ffn in zip(self.layers, self.ffn_layers): |
| 85 | x, _ = attn(x, x, x, is_causal=True, *args, **kwargs) |
| 86 | x = self.norm(x + skip) |
| 87 | x = ffn(x) + x |
| 88 | return x |
| 89 | |
| 90 | |
| 91 | # [MAIN MODEL] BitNetTransformer |
no outgoing calls