technology
Transformer
Attention Mechanism
Deep Learning
NLP
Ask anything about this article
Hi! I've read this article.
What would you like to know?
@farhan
Both encoder and decoder stack N such layers (commonly N=6).
pythonimport math, torch
def scaled_dot_product_attention(Q, K, V, mask=None):
d_k = Q.size(-1)
# Compute raw scores
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
# Softmax to obtain attention weights
attn = torch.softmax(scores, dim=-1)
# Weighted sum of values
return torch.matmul(attn, V)
sqrt(d_k) prevents the softmax from entering regions with extremely small gradients.d_model into h heads, each with dimension d_k = d_v = d_model / h. This allows the model to attend to information from different representation subspaces.pythonclass MultiHeadAttention(torch.nn.Module):
def __init__(self, d_model, num_heads):
super().__init__()
assert d_model % num_heads == 0
self.d_k = d_model // num_heads
self.num_heads = num_heads
self.W_q = torch.nn.Linear(d_model, d_model)
self.W_k = torch.nn.Linear(d_model, d_model)
self.W_v = torch.nn.Linear(d_model, d_model)
self.W_o = torch.nn.Linear(d_model, d_model)
def forward(self, query, key, value, mask=None):
batch_size = query.size(0)
# Linear projections
Q = self.W_q(query).view(batch_size, -1, self.num_heads, self.d_k).transpose(1,2)
K = self.W_k(key).view(batch_size, -1, self.num_heads, self.d_k).transpose(1,2)
V = self.W_v(value).view(batch_size, -1, self.num_heads, self.d_k).transpose(1,2)
# Apply scaled dot‑product attention on each head
attn_output = scaled_dot_product_attention(Q, K, V, mask)
# Concatenate heads
concat = attn_output.transpose(1,2).contiguous().view(batch_size, -1, self.num_heads * self.d_k)
return self.W_o(concat)
PE_{(pos, 2i)} = sin(pos / 10000^{2i/d_model})
PE_{(pos, 2i+1)} = cos(pos / 10000^{2i/d_model})
FFN(x) = max(0, xW_1 + b_1)W_2 + b_2
d_model = 512 and inner layer size d_ff = 2048.lr = d_model^{-0.5} * min(step^{-0.5}, step * warmup_steps^{-1.5})