রোডম্যাপ
PHASE 5 · অধ্যায় 22

অ্যাটেনশন মেকানিজম

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।

বাস্তব ব্যবহার

  • Machine translation — কোন source word এখন target word generate এ helpful।
  • Image captioning — image এর কোন part এখন describe হচ্ছে।
  • Question answering — passage এর কোন part answer ধারণ করে।
  • Document summarization — কোন sentence summary তে include।
  • Transformer, BERT, GPT — সবার core building block।

ধাপে ধাপে বিশ্লেষণ

1
Step 1 — Q, K, V project
Input কে তিনটা linear projection দিয়ে Query, Key, Value বানান।
2
Step 2 — Score = Q · Kᵀ
Query আর প্রতিটা Key এর dot product — similarity।
3
Step 3 — Scale + softmax
√d_k দিয়ে scale, softmax দিয়ে probability distribution।
4
Step 4 — Weighted sum
Attention weights × Values = context vector।
5
Step 5 — Multi-head
একাধিক attention parallel চালান, concat — different relation শেখে।

Python কোড

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'।

সাধারণ ভুল

  • Scale না করা (√d_k) — dimension বড় হলে softmax saturate।
  • Padding token এ attention দেওয়া — mask দরকার।
  • Self-attention এ causal mask না দেওয়া (decoder এ) — future token দেখে ফেলবে।
  • Single-head attention এ আটকে থাকা — multi-head দিয়ে richer representation।

অনুশীলন

  1. Multi-head attention নিজে implement করুন (split → attention → concat)।
  2. Attention weight heatmap plot করুন matplotlib দিয়ে।
  3. Causal mask বানান triangular matrix দিয়ে।
  4. Bahdanau (additive) attention implement করে scaled-dot এর সাথে compare।

ছোট প্রজেক্ট

Attention Visualizer

একটা small self-attention layer train/run করুন কয়েকটা sentence এ, প্রতিটা word এর জন্য অন্য word গুলোর attention weight heatmap দেখান। কোন word কোন word এ 'attend' করছে — visually বোঝান।

সারাংশ

  • Attention = relevant input এ dynamic weight।
  • Query · Key → score, softmax → weight, × Value → context।
  • Self-attention: same sequence এর মধ্যে relation।
  • Multi-head: parallel attention, different pattern শেখে।
  • Transformer, BERT, GPT — সবার heart।