Attention Mechanism
Attention is all you need — যাদুর শুরু।
Seq2Seq এ সব meaning একটা context vector এ চেপে ঢোকানো হতো — long sentence এ model হাঁসফাঁস করত। ২০১৪-১৫ সালে Bahdanau & Luong একটা game-changing idea দিলেন — decoder কে প্রতিটা step এ encoder এর সব hidden state দেখতে দাও, আর শেখাও কোনটায় কতটা 'attention' দিতে হবে। এটাই Attention Mechanism — পরে এর ওপর গোটা Transformer architecture দাঁড়াবে।
Attention এমন একটা mechanism যা output এর প্রতিটা step এ input এর প্রতিটা position এর সাথে একটা weight calculate করে — কোন input position এই মুহূর্তে কতটা relevant। সূত্র: Attention(Q, K, V) = softmax(QKᵀ / √d_k) · V। Query (এখন কী খুঁজছি), Key (প্রতিটা input এর address), Value (আসল content) — তিনটার interaction।
ভাবুন আপনি 'The cat sat on the mat because it was tired' — এ 'it' কে refer করছে? 'cat' এ! মানুষ এটা automatically বুঝে। Attention model কে শেখায় — 'it' word process করার সময় 'cat' এ বেশি focus দাও, 'mat' এ কম। প্রতিটা word অন্য সব word এর সাথে similarity score বের করে, softmax দিয়ে normalize, তারপর weighted sum।
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
def scaled_dot_product_attention(Q, K, V, mask=None):
d_k = Q.size(-1)
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, float("-inf"))
weights = F.softmax(scores, dim=-1)
output = torch.matmul(weights, V)
return output, weights
class SelfAttention(nn.Module):
def __init__(self, embed_dim):
super().__init__()
self.q = nn.Linear(embed_dim, embed_dim)
self.k = nn.Linear(embed_dim, embed_dim)
self.v = nn.Linear(embed_dim, embed_dim)
def forward(self, x):
Q, K, V = self.q(x), self.k(x), self.v(x)
out, attn = scaled_dot_product_attention(Q, K, V)
return out, attn
x = torch.randn(2, 5, 32)
attn_layer = SelfAttention(embed_dim=32)
out, weights = attn_layer(x)
print("Output:", out.shape)
print("Attention weights:", weights.shape)scaled_dot_product_attention হলো attention এর core formula। Q · Kᵀ দিয়ে similarity matrix, √d_k দিয়ে scale (large dim এ gradient stable রাখতে), softmax দিয়ে weight distribution, তারপর V এর সাথে multiply করে context। SelfAttention class এ same input থেকেই Q, K, V — তাই 'self'।
একটা small self-attention layer train/run করুন কয়েকটা sentence এ, প্রতিটা word এর জন্য অন্য word গুলোর attention weight heatmap দেখান। কোন word কোন word এ 'attend' করছে — visually বোঝান।