PyTorch
Adria / module /transformers /vanilla /transformer_block.py
Nebulon33's picture
Upload 84 files
bd992b7 verified
Raw History Blame Contribute Delete
1.8 kB
import torch
import torch.nn as nn
from module.transformers.vanilla.multi_head_attention import VanillaMultiHeadAttention
"""
A standard 'vanilla' transformer block with pre-norm, multi-head attention, and an FFN.
"""
class VanillaTransformerBlock(nn.Module):
def __init__(
self,
d_model: int = 512,
head_amount: int = 8,
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 = VanillaMultiHeadAttention(d_model, head_amount)
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