import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple # Multi-Head Attention Mechanism class MultiHeadAttention(nn.Module): def __init__(self, d_model: int, num_heads: int, dropout: float = 0.1): super().__init__() assert d_model % num_heads == 0 self.d_model = d_model self.num_heads = num_heads self.head_dim = d_model // num_heads self.q_proj = nn.Linear(d_model, d_model) self.k_proj = nn.Linear(d_model, d_model) self.v_proj = nn.Linear(d_model, d_model) self.o_proj = nn.Linear(d_model, d_model) self.dropout = nn.Dropout(dropout) def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor: batch_size, seq_len, d_model = x.shape # Project and reshape for multi-head attention q = self.q_proj(x).reshape(batch_size, seq_len, self.num_heads, self.head_dim) k = self.k_proj(x).reshape(batch_size, seq_len, self.num_heads, self.head_dim) v = self.v_proj(x).reshape(batch_size, seq_len, self.num_heads, self.head_dim) # Transpose for attention computation q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2) # Compute attention scores scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim) if mask is not None: scores = scores.masked_fill(mask == 0, float('-inf')) attn_weights = F.softmax(scores, dim=-1) attn_weights = self.dropout(attn_weights) # Apply attention to values out = torch.matmul(attn_weights, v).transpose(1, 2).reshape(batch_size, seq_len, d_model) return self.o_proj(out)