Download module/transformers/rope/transformer_block.py from Pulsar-Dynamic-Technologies/Adria: direct link, hf CLI and curl.
- Browser
- Download file 1.94 kB
-
https://huggingface.co/Pulsar-Dynamic-Technologies/Adria/resolve/main/module/transformers/rope/transformer_block.py
- Command line
-
hf download hf://Pulsar-Dynamic-Technologies/Adria/module/transformers/rope/transformer_block.py
-
curl -L -o transformer_block.py https://huggingface.co/Pulsar-Dynamic-Technologies/Adria/resolve/main/module/transformers/rope/transformer_block.py
1.94 kB
| import torch | |
| import torch.nn as nn | |
| from module.transformers.rope.multi_head_attention import RoPEVanillaMultiHeadAttention | |
| """ | |
| A standard 'vanilla' transformer block with pre-norm, multi-head attention, and an FFN. | |
| Uses RoPE Multi-Head Attention blocks. | |
| """ | |
| class RoPEVanillaTransformerBlock(nn.Module): | |
| def __init__( | |
| self, | |
| d_model: int = 512, | |
| head_amount: int = 8, | |
| n_ctx: int = 2048, | |
| rope_base: float = 10000.0, | |
| d_ffn: int = 2048, | |
| ffn_func: type[nn.Module] = nn.GELU | |
| ): | |
| """ | |
| d_model (int): The dimension of the model (embedding dimension size). | |
| head_amount (int): The number of attention heads. | |
| d_ffn (int): The dimension of the FFN used in the transformer block () | |
| """ | |
| super().__init__() | |
| # Norm -> Attention -> Norm -> FFN 1 -> FFN Func -> FFN 2 -> Out | |
| self.norm1 = nn.LayerNorm(d_model) | |
| self.attention = RoPEVanillaMultiHeadAttention(d_model, head_amount, n_ctx, rope_base) | |
| self.norm2 = nn.LayerNorm(d_model) | |
| self.ffn = nn.Sequential( | |
| nn.Linear(d_model, d_ffn), | |
| ffn_func(), | |
| nn.Linear(d_ffn, d_model) | |
| ) | |
| def forward(self, x: torch.Tensor, kv_cache: tuple[torch.Tensor, torch.Tensor] = None) -> tuple[ | |
| torch.Tensor, tuple[torch.Tensor, torch.Tensor]]: | |
| """ | |
| A forward pass with residual connections. | |
| Norm -> Attention (+ Residual) -> Norm -> FFN 1 -> FFN Func -> FFN 2 (+ Residual) -> Out | |
| x (torch.Tensor): Input tensor | |
| kv_cache (tuple[torch.Tensor, torch.Tensor]): The kv cache. | |
| Should not be passed in as anything but the returned kv cache from a previous forward call. | |
| """ | |
| attention_out, new_kv = self.attention(self.norm1(x), kv_cache) | |
| x = x + attention_out | |
| x = x + self.ffn(self.norm2(x)) | |
| return x, new_kv | |