Transformer architecture
এই পাঠে যা শিখবেন
- Transformer architecture — encoder ও decoder side-by-side
- প্রতিটি block-এর উপাদান — attention, FFN, residual, LayerNorm
- Masked attention কেন decoder-এ দরকার
- Cross-attention — encoder থেকে decoder-এ information flow
- PyTorch nn.Transformer ও scratch implementation
- Training loss, hyperparameter, BLEU score
১ · কেন Transformer এসেছিল
২০১৭-র আগে — Seq2Seq translation-এ RNN/LSTM dominant। কিন্তু RNN-এর দু'টি বড় সমস্যা:
- Sequential bottleneck: token $t$ process করতে হলে $t-1$ আগে শেষ হতে হবে। GPU parallelism utilize হয় না।
- Long-range degradation: দীর্ঘ বাক্যে শুরু-শেষ token-এর মধ্যে gradient signal weak — vanishing gradient।
Vaswani et al.-এর "Attention Is All You Need" (২০১৭) — RNN পুরোপুরি বাদ। শুধু self-attentionSelf-Attentionএকটি sequence-এ প্রতিটি token অন্য সব token-এর সাথে compatibility মাপে — Q, K, V projection দিয়ে। L31-এ বিস্তারিত। ও feed-forward দিয়ে complete model। English→German translation-এ BLEU ২৮.৪ — তখনকার state-of-the-art ছাড়িয়ে।
১) Multi-head self-attention — sequence-এর internal relationship।
২) Position-wise FFN — non-linear transformation per token।
৩) Residual + LayerNorm — gradient flow ও stable training।
Encoder-decoder-এ এগুলো বিভিন্নভাবে combine।
২ · Encoder block — পদে পদে
প্রতিটি encoder layer-এ চারটি step:
- Multi-head self-attention on input $X$ → output $A$।
- Add & Norm: $X' = \text{LayerNorm}(X + A)$ — residual connection ও normalization।
- Feed-Forward Network: $F = \text{FFN}(X') = \text{ReLU}(X' W_1 + b_1) W_2 + b_2$। Two linear layer; hidden dim সাধারণত $4 \cdot d_{model}$।
- Add & Norm: output $= \text{LayerNorm}(X' + F)$।
এই block $N$ বার stack — original paper-এ $N = 6$। BERT-base-এ $N = 12$।
৩ · Decoder block — তিন sub-layer
Decoder layer encoder-এর মতো — কিন্তু একটি অতিরিক্ত sub-layer:
- Masked multi-head self-attention — শুধু পূর্ববর্তী token দেখা যায় (future leak রোধ)।
- Add & Norm।
- Cross-attention — Q decoder থেকে, K, V encoder output থেকে। এখানেই source-target alignment।
- Add & Norm।
- FFN।
- Add & Norm।
৪ · Masked attention — কেন দরকার
Training-এ পুরো target sentence একসাথে পাওয়া যায়। কিন্তু decoder-কে শেখাতে হবে — token $t$ predict করার সময় শুধু $t-1, t-2, \ldots$ দেখো; $t+1$ দেখলে cheating।
সমাধান — attention score matrix-এ upper triangle $-\infty$ বসানো (softmax-এ ০ হয়ে যায়):
$$\text{mask}_{ij} = \begin{cases} 0 & \text{if } j \leq i \\ -\infty & \text{if } j > i \end{cases}$$
এই masking-এর কারণে training-এ teacher forcing parallel — প্রতিটি position-এ সঠিক context।
৫ · Add & Norm — কেন এত গুরুত্বপূর্ণ
Residual connection (He et al., ResNet ২০১৫) — gradient সরাসরি back-propagate। Without residual, ৬-layer Transformer train করা impossible — gradient vanish।
LayerNormLayer Normalizationপ্রতিটি token-এর feature dimension-এ mean=0, std=1 normalize। BatchNorm-এর মতো নয় — batch-এর ওপর depend করে না, তাই variable-length sequence ও inference-এ সমস্যা নেই। — feature dim-এ normalize। Activation-এর scale stable, training fast।
Modern Transformer (GPT-2 onwards) — "Pre-LN": LayerNorm আগে, attention/FFN পরে। আরও stable training।
৬ · PyTorch — scratch encoder layer
import torch
import torch.nn as nn
class TransformerEncoderLayer(nn.Module):
def __init__(self, d_model=512, n_heads=8, d_ff=2048, dropout=0.1):
super().__init__()
self.self_attn = nn.MultiheadAttention(
d_model, n_heads, dropout=dropout, batch_first=True)
self.ffn = nn.Sequential(
nn.Linear(d_model, d_ff),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(d_ff, d_model),
)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.drop = nn.Dropout(dropout)
def forward(self, x, src_mask=None):
# Self-attention sub-layer
a, _ = self.self_attn(x, x, x, attn_mask=src_mask)
x = self.norm1(x + self.drop(a))
# FFN sub-layer
f = self.ffn(x)
x = self.norm2(x + self.drop(f))
return x
layer = TransformerEncoderLayer()
x = torch.randn(2, 20, 512) # (B, T, d)
print(layer(x).shape) # torch.Size([2, 20, 512])
৭ · PyTorch built-in — nn.Transformer
import torch
import torch.nn as nn
model = nn.Transformer(
d_model=512, nhead=8,
num_encoder_layers=6,
num_decoder_layers=6,
dim_feedforward=2048,
dropout=0.1,
batch_first=True
)
src = torch.randn(2, 20, 512) # source (B, S, d)
tgt = torch.randn(2, 15, 512) # target (B, T, d)
# Causal mask for decoder self-attention
T = tgt.size(1)
tgt_mask = nn.Transformer.generate_square_subsequent_mask(T)
out = model(src, tgt, tgt_mask=tgt_mask)
print(out.shape) # (2, 15, 512)
print(f"Params: {sum(p.numel() for p in model.parameters())/1e6:.1f}M")
৮ · Hyperparameter — original paper
- Base: $d_{model}=512$, $h=8$, $d_{ff}=2048$, $N=6$ — ৬৫M params।
- Big: $d_{model}=1024$, $h=16$, $d_{ff}=4096$, $N=6$ — ২১৩M params।
- Optimizer: Adam ($\beta_1=0.9$, $\beta_2=0.98$, $\epsilon=10^{-9}$)।
- LR schedule: warmup ৪,০০০ steps, তারপর $\frac{1}{\sqrt{step}}$ decay।
- Label smoothing: ০.১ — over-confident prediction প্রতিরোধ।
- Training: ৮ × P100 GPU, ১২ ঘণ্টা base model।
৯ · Encoder-only, Decoder-only, Encoder-Decoder
- Encoder-only (BERT, RoBERTa): bidirectional context — classification, NER, QA।
- Decoder-only (GPT, LLaMA): causal mask — text generation, completion।
- Encoder-Decoder (T5, BART, original): source→target — translation, summarization।
আজকের সব major LLM Transformer-এর কোনো না কোনো variant। GPT-3, ChatGPT, Claude, Gemini — সবই decoder-only Transformer।
ভাবনার প্রশ্ন
প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।
প্র ০১ "Attention Is All You Need" — শিরোনামটি provocative। RNN/CNN-এর সব advantage ছাড়াও Transformer কেন কাজ করে? কোন inductive bias হারায়, কোনটি পায়?
Vaswani et al.-র ২০১৭ পেপার — DL-এর landmark। Title এতটাই bold যে অনেকেই প্রথমে hyperbole ভেবেছিল। কিন্তু পরের ৭ বছরে প্রায় সব major model এই foundation-এর উপর।
RNN-এর হারানো inductive bias:
- Sequential ordering bias: RNN built-in ধরে নেয় — token order matters, recent past important। Transformer position-agnostic — তাই positional encoding inject করতে হয়।
- Recency bias: RNN প্রাকৃতিকভাবে recent token-কে বেশি weight। Attention-এ সব position equal — bias শিখে data থেকে।
- Compact memory state: RNN-এর hidden state $h_t$ সব past compress করে। Transformer পুরো history-তে raw access।
CNN-এর হারানো inductive bias:
- Locality: CNN-এ kernel small window। Transformer-এ instant global view।
- Translation invariance: CNN feature map shift-invariant। Transformer position-aware (PE), shift-equivariant নয়।
- Parameter sharing: CNN একই kernel সর্বত্র। Transformer attention pattern data-dependent।
Transformer যা পায়:
- Full parallelism: training-এ পুরো sequence একসাথে। GPU-friendly।
- $O(1)$ path length: যেকোনো দু'টি position সরাসরি interact। Long-range trivially।
- Data-dependent connectivity: attention weight প্রতিটি input-এ আলাদা — flexible।
- Scalability: parameter বাড়ানো → linear capacity। RNN-এ marginal return।
The real reason it works — scale:
- Transformer-এর inductive bias দুর্বল — তাই বেশি data দরকার।
- ২০১৭-র আগে এই scale impractical।
- ২০১৮+ web-scale data + GPU cluster — Transformer flourish।
- Sutton-এর "Bitter Lesson" — strong inductive bias eventually scale-এর কাছে হারে।
Empirical winner:
- Translation: Transformer immediately better।
- Language modeling: GPT series — exponential scaling।
- Vision: ViT (২০২০) — সব প্রত্যাশা ছাড়িয়ে।
- Speech: Conformer (Transformer + CNN) hybrid।
Failure modes:
- Small data — Transformer অনেক CNN/RNN-এর কাছে হারে।
- $O(T^2)$ memory — দীর্ঘ sequence-এ infeasible।
- Inference cost — autoregressive generation costly।
Modern hybrids:
- Mamba (২০২৪) — RNN-like, Transformer-competitive।
- RetNet — recurrent + parallel।
- Mixture-of-Experts — sparse activation।
মূল উপলব্ধি: Transformer-এর genius — minimal inductive bias + maximum parameter sharing efficiency + perfect parallelism। এই ত্রিভুজ বড় data এবং বড় compute-এর সাথে magic। "Attention Is All You Need" আজও প্রায় সত্য — কিন্তু "almost"।
প্র ০২ Cross-attention vs self-attention — exact difference কী, কেন translation-এ cross-attention critical?
Self vs cross attention — Transformer-এর দু'টি ভিন্ন information flow। বুঝলে decoder-এর কাজ পরিষ্কার।
Self-attention (Q, K, V সব এক sequence থেকে):
- Encoder-এ — input sequence-এর internal relationship।
- Decoder-এর প্রথম sub-layer — generated output-এর internal relationship (masked)।
- Same length input-output।
Cross-attention (Q decoder থেকে, K, V encoder থেকে):
- Decoder প্রতিটি step-এ — "encoder output-এর কোন অংশ এখন প্রাসঙ্গিক?"।
- Source-target alignment learn করে।
- Different length OK — Q (target len) × K (source len)।
Translation-এ critical কেন:
- "I love Bangladesh" → "আমি বাংলাদেশকে ভালোবাসি" — order ভিন্ন (SOV vs SVO)।
- "আমি" generate করতে — encoder-এর "I"-এ attention।
- "বাংলাদেশকে" generate করতে — "Bangladesh" + accusative marker।
- "ভালোবাসি" generate করতে — "love" + person-tense agreement।
Attention visualization:
- Cross-attention weight plot — diagonal-ish but reordered।
- Old IBM word alignment models এর neural counterpart।
- Bahdanau et al. (২০১৪) attention — এই idea-র ancestor।
Mechanism details:
- Encoder run prior — output cache।
- Decoder প্রতিটি step-এ — same encoder output-এ cross-attend।
- Q $\in \mathbb{R}^{T_{tgt} \times d}$, K, V $\in \mathbb{R}^{T_{src} \times d}$।
- Attention matrix $T_{tgt} \times T_{src}$।
Without cross-attention (just self-attention):
- Decoder source content access করতে পারবে না।
- Translation impossible।
- Pure decoder model (GPT) — concatenated input-output, single self-attention।
Decoder-only alternative:
- GPT/LLaMA — encoder নেই।
- Source-target concatenated single sequence।
- Self-attention সব handle করে।
- Modern LLM trend এদিকেই।
Bangla NMT-এ:
- BanglaT5 — encoder-decoder, cross-attention essential।
- Specific head — verb-end (Bangla SOV) ↔ verb-mid (English SVO) alignment।
- Postposition tracking — "তে", "র" markers।
মূল উপলব্ধি: Self-attention = same sequence internal। Cross-attention = source-target bridge। Translation-এ cross-attention is the alignment mechanism। Modern decoder-only models এই pattern self-attention দিয়েই achieve করে — শুধু concatenation।
প্র ০৩ Original Transformer-এর FFN dimension $d_{ff}=2048$ — $d_{model}$-এর ৪ গুণ। এই ratio কেন? FFN-এর role কী?
FFN — Transformer-এর কম-আলোচিত কিন্তু critical component। Model parameter-এর প্রায় ২/৩ এখানে।
FFN structure:
$$\text{FFN}(x) = \max(0, x W_1 + b_1) W_2 + b_2$$
- $W_1 \in \mathbb{R}^{d_{model} \times d_{ff}}$ — expand।
- $W_2 \in \mathbb{R}^{d_{ff} \times d_{model}}$ — project back।
- Per-token applied (position-wise) — token-এর মধ্যে কোনো interaction নেই।
$4 \times$ ratio কেন:
- Empirically tuned — paper-এ ৬৪ থেকে ১০২৪ × ratio test।
- $2 \times$ — under-capacity।
- $8 \times$ — diminishing return, parameter waste।
- $4 \times$ — sweet spot — তখন থেকে standard।
FFN-এর role — interpretability research:
- Geva et al. (২০২০) — "FFN are key-value memories"।
- $W_1$ — pattern detection (key)। $W_2$ — corresponding fact retrieval (value)।
- Specific neuron specific factual memory store করে।
- "Eiffel Tower → Paris" type association।
Without FFN — what fails:
- Pure attention — linear transformation of values।
- FFN — non-linearity inject।
- Without — limited expressivity।
- Universal approximation FFN-এর কাছে।
Compute distribution:
- Attention: $O(T^2 d + T d^2)$।
- FFN: $O(T d \cdot d_{ff}) = O(T d^2)$ since $d_{ff} = 4d$।
- Long sequence — attention dominates।
- Short sequence — FFN dominates।
Modern variants:
- GLU/SwiGLU (LLaMA) — gated activation, better।
- Mixture-of-Experts — multiple FFN, sparse routing।
- Switch Transformer — single expert per token, scale to trillions।
Activation choice evolution:
- Original ReLU।
- GPT-2 — GELU।
- LLaMA — SwiGLU।
- Performance-driven empirical choice।
মূল উপলব্ধি: FFN — per-token transformation, knowledge storage, non-linearity। ৪x ratio empirical। Modern interpretability — FFN factual memory। Attention global mixing, FFN local enrichment — Transformer-এর dual mechanism।
প্র ০৪ Bangladesh-এর একটি team Bangla→English MT system বানাচ্ছে। Encoder-decoder vs decoder-only — কোনটা বাছবেন? Trade-offs?
Bangladesh practical decision — Bangla-English NMT design। Architecture choice critical।
Encoder-Decoder (BART, T5, mBART):
Pros:
- Translation-এর জন্য designed — strong inductive bias।
- Encoder full bidirectional context।
- Cross-attention explicit alignment।
- Smaller model competitive (mBART-50 ৬১১M)।
- Training data efficient।
Cons:
- Two-stage compute — slower inference।
- Source-target separated — less flexible।
- Specialized architecture — task-specific।
Decoder-only (GPT, LLaMA):
Pros:
- Universal — translation, generation, classification একই model।
- Scaling ভালো — large model better।
- Few-shot prompting — no fine-tuning।
- Modern ecosystem (LLaMA 3, Gemma) — strong base।
Cons:
- Larger required (typically 7B+) for quality।
- Compute expensive।
- Bangla-specific data scarce — ad-hoc support।
- Latency higher per request।
Bangla-English specific considerations:
- SOV → SVO order change — explicit alignment helps।
- Honorific complexity — context-dependent।
- Code-mixing ("Banglish") common — flexible model needed।
- Domain (news, social, formal) variability।
Recommendation by scenario:
Production translation service (e.g. গভর্নমেন্ট portal):
- mBART-50 fine-tune — proven quality।
- OPUS/BUET parallel data ব্যবহার।
- Low latency, predictable cost।
Conversational AI / general assistant:
- LLaMA 3 / Gemma fine-tune।
- Translation as prompt task।
- Multi-task flexibility।
Research / state-of-art:
- NLLB-200 (Meta) — 200 language MT।
- Bangla included।
- Encoder-decoder, optimized।
Data requirements:
- Encoder-decoder: ~১M parallel sentence good start।
- Decoder-only: more — instruction tuning data critical।
- BUET, SIPC, OPUS — primary Bangla parallel sources।
Hardware budget:
- mBART fine-tune: single A100, ১-২ দিন।
- LLaMA-7B fine-tune: 4×A100, 1 week।
- From scratch: ১০x more — generally infeasible Bangladesh-এ।
Evaluation:
- BLEU on FLORES-200 Bangla devtest।
- Human evaluation crucial — automatic misleading।
- Domain-specific test set — news, conversation।
Deployment:
- Quantization INT8 — 4x size reduction।
- ONNX/TensorRT — inference optimized।
- Distillation — smaller deployment model।
- API service vs self-host trade-off।
Bangladesh practical pick:
- Start with mBART-50 fine-tune — fastest path to quality।
- Monitor — if generic chatbot needs, consider LLaMA।
- Hybrid possible — translation specific + LLM fallback।
মূল উপলব্ধি: Encoder-decoder translation-specific, efficient। Decoder-only general, scalable। Bangladesh — mBART fine-tune practical first step। LLM era pull toward decoder-only, but encoder-decoder still competitive translation-এ। Architecture choice = data + budget + use-case।
অনুশীলন
-
Parameter count: Vanilla base Transformer — $d=512$, $h=8$, $d_{ff}=2048$, $N=6$ encoder + ৬ decoder। প্রতি encoder layer-এ params estimate (attention + FFN + LayerNorm)।
- Attention: $4 \times d^2 = 4 \times 512^2 \approx 1.05$M।
- FFN: $2 \times d \times d_{ff} = 2 \times 512 \times 2048 \approx 2.1$M।
- LayerNorm: negligible (~2K)।
- Per encoder layer ~৩.১৫M; ৬ layer ≈ ১৯M।
- Decoder layer slightly more (cross-attn) — ~৪.২M; ৬ layer ≈ ২৫M।
- Embedding + output projection — vocab × d (vocab~৩৭K) ≈ ৩৮M।
- Total ~৬৫M — paper-এর সাথে মিলে।
-
Mask construction: Decoder causal mask (length 5) PyTorch-এ লিখুন।
import torch T = 5 mask = torch.triu(torch.ones(T, T), diagonal=1).bool() print(mask) # True = mask out (future) # nn.Transformer.generate_square_subsequent_mask(T) # returns float mask with -inf and 0 -
চিন্তা: Transformer-এ "Add & Norm" বাদ দিলে কী হবে — দু'টি সম্ভাব্য failure mode বলুন।
- Residual বাদ: deep model-এ vanishing gradient — layer ৬+ train অসম্ভব। Identity path-এর অভাবে initial layer learning signal পায় না।
- LayerNorm বাদ: activation explode/vanish — variable scale-এ FFN/softmax unstable। Training diverge দ্রুত।
আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ
- পাঠ ৩৪ · Positional encoding পরবর্তী পাঠ Transformer order-agnostic — position-এর তথ্য কীভাবে যোগ?
- পাঠ ৩২ · Multi-head attention আগের পাঠ Transformer-এর মূল building block।
- NLP & LLM Track গভীরে যান BERT, GPT, prompt engineering — Transformer-এর application।
- সব AI Courses দেখুন ABCL TECH Python, ML, DL, NLP, CV, GenAI, RL, MLOps — সব AI কোর্স একসাথে।