Multi-Head Attention
Múltiples heads paralelos y representaciones diversas
Multi-head attention aplica múltiples heads de atención en paralelo, cada uno con proyecciones lineales diferentes de Q, K, V. Con h heads, cada head tiene dimensión d_k = d_model / h. Cada head aprende a atender a diferentes tipos de relaciones semánticas simultáneamente (e.g., head 1 atiende a dependencias sintácticas, head 2 a semánticas, head 3 a coreferencia). Los outputs de todos los heads se concatenan y se proyectan linealmente nuevamente.
La ventaja clave: h heads permiten que el modelo capture múltiples tipos de dependencias sin aumentar dramáticamente el cálculo. Con h=8 heads y d_k=64, d_model=512, el cálculo es similar a un single head de 512 dimensiones, pero con más capacidad representacional (8 diferentes patrones de atención).
En práctica, se observa que diferentes heads aprenden roles distintos: algunos heads atienden localmente (tokens cercanos), otros globalmente (tokens lejanos), otros a estructura sintáctica, etc. Esto es una propiedad emergente del entrenamiento, no explícitamente diseñada.
import torch
import torch.nn as nn
import math
class MultiHeadAttention(nn.Module):
def __init__(self, d_model=512, num_heads=8):
super().__init__()
assert d_model % num_heads == 0, 'd_model must be divisible by num_heads'
self.d_model = d_model
self.num_heads = num_heads
self.d_k = d_model // num_heads
self.W_q = nn.Linear(d_model, d_model)
self.W_k = nn.Linear(d_model, d_model)
self.W_v = nn.Linear(d_model, d_model)
self.W_o = nn.Linear(d_model, d_model)
def forward(self, Q, K, V, mask=None):
batch_size = Q.shape[0]
# Linear projections and split into heads
Q = self.W_q(Q).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
K = self.W_k(K).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
V = self.W_v(V).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
# Now shape: (batch_size, num_heads, seq_len, d_k)
# Scaled dot-product attention
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, float('-inf'))
attn_weights = torch.softmax(scores, dim=-1)
attn_output = torch.matmul(attn_weights, V)
# Concatenate heads
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.view(batch_size, -1, self.d_model)
# Output projection
output = self.W_o(attn_output)
return output
# Example
mha = MultiHeadAttention(d_model=512, num_heads=8)
x = torch.randn(4, 20, 512) # batch=4, seq=20, d_model=512
output = mha(x, x, x) # Self-attention
print(output.shape) # (4, 20, 512)Debugging lab
Detecta y corrige el error en el código.
- 01
d_model = 512, num_heads = 7 # 512 % 7 != 0 d_k = d_model // num_heads # What is the problem?
- 02
# Multi-head attention dimensions d_model = 512, num_heads = 8, seq_len = 20 Q shape after projection: (batch, seq_len, d_model) = (4, 20, 512) Q shape after split into heads: (batch, num_heads, seq_len, d_k) = (4, 8, 20, ?) # d_k = ?