import math
from types import SimpleNamespace
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(0)
def scaled_dot_product_attention(query, key, value):
dim_k = query.size(-1)
scores = torch.bmm(query, key.transpose(1, 2)) / math.sqrt(dim_k)
weights = F.softmax(scores, dim=-1)
return torch.bmm(weights, value)
class AttentionHead(nn.Module):
def __init__(self, embed_dim, head_dim):
super().__init__()
self.q = nn.Linear(embed_dim, head_dim)
self.k = nn.Linear(embed_dim, head_dim)
self.v = nn.Linear(embed_dim, head_dim)
def forward(self, hidden_state):
return scaled_dot_product_attention(
self.q(hidden_state), self.k(hidden_state), self.v(hidden_state)
)
class MultiHeadAttention(nn.Module):
def __init__(self, config):
super().__init__()
embed_dim = config.hidden_size
num_heads = config.num_attention_heads
if num_heads <= 0 or embed_dim % num_heads != 0:
raise ValueError("hidden_size must be divisible by positive num_heads")
head_dim = embed_dim // num_heads
self.heads = nn.ModuleList(
[AttentionHead(embed_dim, head_dim) for _ in range(num_heads)]
)
self.output_linear = nn.Linear(embed_dim, embed_dim)
def forward(self, hidden_state):
x = torch.cat([h(hidden_state) for h in self.heads], dim=-1)
x = self.output_linear(x)
return x
config = SimpleNamespace(hidden_size=768, num_attention_heads=12)
mha = MultiHeadAttention(config)
x = torch.randn(2, 10, config.hidden_size) # batch of 2 sequences of 10 tokens
print("input:", tuple(x.shape), " output:", tuple(mha(x).shape))