4.1.10 · HinglishTransformer Architecture

Encoder vs decoder vs encoder-decoder

2,800 words13 min readRead in English

4.1.10 · AI-ML › Transformer Architecture

Overview

Teen fundamental transformer architecture patterns alag-alag sequence-to-sequence problems solve karte hain — self-attention mechanisms ko alag configurations mein use karke. Yeh samajhna ki kab kaun sa use karna hai, aapke task ke liye sahi model chunne ke liye bahut zaroori hai.

Figure — Encoder vs decoder vs encoder-decoder

Sabse badi difference attention masking aur information flow patterns mein hai.

1. Encoder-Only Architecture

Yeh Kaam Kaise Karta Hai (First Principles Se)

Step 1: Bidirectional Context Building

Input sequence ke liye:

Bidirectional KYO? Attention mask saari 1s hai:

Matlab token , token ko dekh sakta hai chahe position koi bhi ho. Token3 tokens 1, 2, 4, 5, etc. sab dekh sakta hai.

Yeh kyun important hai? "river bank" vs "bank account" mein word "bank" ko alag representations milte hain kyunki yeh SAARE surrounding words ko ek saath dekhta hai.

Step 2: Deep Contextual Representations

encoder layers ke baad, har token embedding mein POORE sequence ki information hoti hai:

Multiple layers KYO? Har layer understanding ko refine karti hai:

  • Layer 1: "bank" paas mein "river" dekhta hai
  • Layer 2: "bank" contextually "water" aur "shore" dekhta hai
  • Layer 3: "bank" ki representation ab "river-bank-not-financial-bank" encode karti hai

Derivation:

  1. Raw similarity se shuru karo: (dot product relevance measure karta hai)
  2. se scale karo saturation rokne ke liye: (gradients healthy rakhta hai)
  3. SAARI positions par Softmax: (probability distribution mein normalize karta hai)

Output representation:

Input tokens: [CLS] This movie was not bad at all ! [SEP]

[CLS] KYO? Special token jiska final representation sentence ka meaning aggregate karta hai.

"not" ke liye Layer 1 attention:

  • Attend karta hai: "bad" (0.4), "at" (0.1), "all" (0.2), "was" (0.15), "!" (0.15)
  • Kyun? "not" "bad" ko modify karta hai, local context chahiye

"not" ke liye Layer 6 attention:

  • Ab [CLS] attend karta hai: "not" (0.3), "bad" (0.25), "!" (0.2)
  • Yeh kyun matter karta hai? [CLS] ne seekha ki "not bad" = positive sentiment, bidirectional flow ke through

Final classification:

Best for: Classification, named entity recognition, question answering (jab answer input mein hi ho)

2. Decoder-Only Architecture

Yeh Kaam Kaise Karta Hai (First Principles Se)

Step 1: Causal Masking

Attention mask ab lower-triangular hai:

KYO? Generation ke dauran, position compute karte waqt position abhi generate nahi hua hota.

Implementation:

jahan agar else .

KYO? Softmax ke baad, , future tokens ko completely block kar deta hai.

Step 2: Autoregressive Generation

Token-by-token generate karo:

jahan sirf par depend karta hai.

Full sequence probability:

Product KYO? Probability ka chain rule:

Generation process:

Step Input Attention Output Token Kyun?
1 [The capital of France is] Har token sirf left dekhta hai "Paris" Pattern: "[capital of X is Y]" training mein seekha
2 [The capital of France is Paris] "Paris" sirf prompt dekhta hai "," City names ke baad punctuation pattern
3 [.., Paris,] "," saab previous dekhta hai "which" Common continuation "Paris, which..."

"which" ke liye Token 3 attention:

  • Attend karta hai: "is" (0.1), "Paris" (0.4), "," (0.3), "France" (0.15)
  • Future nahi dekh sakta (no look-ahead)

Generation loop:

for t in range(max_length):
    h = decoder(tokens[:t+1])  # Only uses tokens up to t
    logits = output_head(h[t])  # Only last position
    next_token = sample(logits)
    tokens.append(next_token)

Best for: Text generation, code completion, chatbots, koi bhi autoregressive task

3. Encoder-Decoder Architecture

Yeh Kaam Kaise Karta Hai (First Principles Se)

Step 1: Encoder (Bidirectional)

Source sequence ko full bidirectional attention se process karta hai:

Har saare source tokens dekhta hai.

Step 2: Decoder Self-Attention (Causal)

Target sequence ko causal masking se process karta hai:

Step 3: Cross-Attention (The Key Innovation)

Decoder SAARE encoder outputs ko attend karta hai:

Cross-attention ki derivation:

  1. Decoder se Query: (decoder kya "pooch raha hai")
  2. Encoder se Keys: (encoder kya "jaanta hai")
  3. Encoder se Values: (encoder ki information jo retrieve karni hai)

Cross-attention KYO? Decoder position kisi bhi encoder position ko "dekh" sakta hai, lekin apna future nahi dekh sakta.

Decoder layer (simplified):

  1. Causal self-attention:
  2. Cross-attention:
  3. Feed-forward:

Generation:

Encoding phase:

Input: [The, cat, sleeps]
Encoder output: [h_The, h_cat, h_sleps]

Har mein bidirectional context hai.

Decoding step 1: "Le" generate karo

  • Decoder input: [START]
  • Self-attention: Sirf [START] dekhta hai (left mein kuch nahi)
  • Cross-attention: Encoder se query karta hai
    • Attention weights: {The: 0.6, cat: 0.3, sleeps: 0.1}
    • Kyun? "Le" (article) sabse zyada "The" se relate karta hai
  • Output: "Le"

Decoding step 2: "chat" generate karo

  • Decoder input: [START, Le]
  • Self-attention: "chat" "Le" (0.4) aur START (0.6) ko attend karta hai
  • Cross-attention:
    • Attention weights: {The: 0.1, cat: 0.8, sleeps: 0.1}
    • Kyun? "chat" "cat" ka translation hai
  • Output: "chat"

Decoding step 3: "dort" generate karo

  • Decoder input: [START, Le, chat]
  • Self-attention: "dort" "Le" (0.2), "chat" (0.5), START (0.3) dekhta hai
  • Cross-attention:
    • Attention weights: {The: 0.05, cat: 0.15, sleeps: 0.8}
    • Kyun? "dort" "sleeps" ka translation hai
  • Output: "dort"

Encoder-decoder yahan kyun jeet ta hai?

  1. Encoder English sentence ki poori understanding build karta hai
  2. Decoder French word-by-word generate karta hai
  3. Cross-attention source aur target ko align karta hai (attention as soft alignment)

Best for: Translation, summarization, question answering (answers generate karna), koi bhi seq2seq jahan input/output alag ho

Architecture Comparison Table

Aspect Encoder-Only Decoder-Only Encoder-Decoder
Attention Type Bidirectional Causal (unidirectional) Dono + cross-attention
Token Visibility Saare tokens Sirf pehle ke tokens Encoder: sab; Decoder: pehle ke + encoder
Training Objective Masked LM (MLM) Next token prediction Seq2seq loss
Generation ❌ Nahi ✅ Haan (autoregressive) ✅ Haan (autoregressive)
Understanding ✅ Excellent Good ✅ Excellent (encoder side)
Best For Classification, NER, embedding Text generation, chat Translation, summarization
Examples BERT, RoBERTa GPT, LaMa, Claude T5, BART, mT5

Fix: Encoders samajhne mein ZYADA powerful hote hain kyunki woh dono directions dekhte hain. Jahan deep comprehension chahiye (semantic search, subtle cues wali classification), encoders jeette hain.

Example: BERT sentiment same size ke GPT-style models se better classify karta hai kyunki "not bad" ke liye encoding ke dauran DONO words simultaneously dekhna padta hai.

Fix: Cross-attention asymmetric hai:

  • Query decoder se aata hai (decoder sawaal pooch raha hai)
  • Key/Value encoder se aata hai (encoder jawab de raha hai)

Regular attention symmetric hota hai (Q, K, V sab same sequence se). Cross-attention information flow create karta hai: encoder → decoder.

Example: "dort" generate karte waqt, decoder encoder se QUERY karta hai ki "main kaunsa English word translate kar raha hoon?" Encoder ki "sleeps" representation high attention weight ke through RESPOND karti hai.

Fix: Encoder-decoder mein 2× parameters hote hain aur yeh overkill hai jab dono directions ki zaroorat nahi.

Rules:

  • Same input/output modality + generation → Decoder-only (GPT)
  • Generation ke bina understanding → Encoder-only (BERT)
  • Alag input/output ya summarization → Encoder-decoder (T5)

Mathematical Connections

Unified View: Teeno general transformer equation ke special cases hain:

jahan woh neighborhood hai jise token attend kar sakta hai:

  • Encoder: (saare tokens)
  • Decoder: (causal)
  • Encoder-Decoder: (self) (cross)
Recall Ek 12-saal ke bachche ko samjhao

Socho tum ek group project par kaam kar rahe ho aur teen alag helpers hain:

Helper 1 (Encoder-only): "Super Reader"

  • Tumhara sawaal answer karne se pehle POORI kitaab padhta hai
  • Shuruaat samajhne se pehle ending bhi dekh leta hai
  • Best at: "Yeh kahaani kis baare mein hai?" (understanding tasks)
  • Nayi kahaaniyaan nahi likh sakta, sirf existing samajhta hai

Helper 2 (Decoder-only): "Story Writer"

  • Kahaaniyaan word by word likhta hai, kabhi aage nahi dekhta
  • Sirf jo likh chuka hai wahi yaad rehta hai
  • Best at: "Yeh kahaani aage badhao..." (generation tasks)
  • Naya content likhta hai lekin gehri reading nahi karta

Helper 3 (Encoder-Decoder): "Translator"

  • Pehle POORA French sentence padhta hai (encoder)
  • Phir English word-by-word likhta hai (decoder)
  • Har English word likhte waqt French ko wapas dekhta hai (cross-attention)
  • Best at: "Ise kuch aur mein badlo" (transformation tasks)

Sabse badi difference? Kaam karte waqt yeh kahan dekh sakte hain!

Ya: "Bidirectional Brain, Causal Creator, Cross-attention Converter"

Connections

  • Self-Attention Mechanism - Teeno architectures ki foundation
  • Positional Encoding - Saare variants sequence order kaise handle karte hain
  • Multi-Head Attention - Encoder, decoder, aur cross-attention mein use hota hai
  • Masked Language Modeling - Encoder-only ka training objective
  • Causal Language Modeling - Decoder-only ka training objective
  • Sequenceto-Sequence Models - Encoder-decoder ka problem class
  • Attention Masking - Alag masks har architecture define karte hain
  • BERT - Canonical encoder-only model
  • GPT - Canonical decoder-only model
  • T5 - Canonical encoder-decoder model
  • Cross-Attention - Encoder-decoder ka unique component
  • Autoregressive Generation - Decoders aur encoder-decoders kaise generate karte hain

#flashcards/ai-ml

Encoder-only aur decoder-only architectures mein key attention difference kya hai? :: Encoder-only bidirectional attention use karta hai (har token saare tokens dekhta hai), jabki decoder-only causal attention use karta hai (har token sirf pehle ke tokens dekhta hai). Yeh attention masking se enforce hota hai.

Decoder-only models bidirectional attention kyun use nahi kar sakte?
Autoregressive generation ke dauran, future tokens abhi exist nahi karte. Agar position 3 training mein position 4 ko attend kar pata, toh model "cheat" karta jawab dekhke. Causal masking generation constraint enforce karta hai.

Causal attention mask mathematically derive karo :: Mask_{ij} = 1 agar j ≤ i, else 0. Implement aise: Attention(Q,K,V) = softmax(QK^T/√d_k + M)V, jahan M_{ij} = 0 agar j≤i, else -∞. Softmax ke baad -∞ 0 ban jaata hai, future tokens block ho jaate hain.

Cross-attention kya hai aur kaun si architecture use karti hai?
Cross-attention decoder ko saare encoder outputs attend karne deta hai. Query decoder se aata hai (kya pooch raha hai), Key/Value encoder se (kya jaanta hai). Sirf encoder-decoder architectures jaise T5 aur BART mein use hota hai.
Encoder-decoder models encoder aur decoder ko concatenate karne ki jagah cross-attention kyun use karte hain?
Cross-attention dynamic aur selective hai — har decoder position relevant encoder positions par focus kar sakti hai. Concatenation static hoti. Example: French word "dort" generate karte waqt, cross-attention English "sleeps" par focus karta hai (0.8 weight) aur "The" ignore karta hai (0.05 weight).
Encoder-only vs decoder-only vs encoder-decoder kab chunna chahiye?
Encoder-only: classification, NER, deep understanding bina generation ke (BERT). Decoder-only: text generation, completion, chat (GPT). Encoder-decoder: translation, summarization, ek sequence ko doosre mein transform karna (T5).
BERT jaisa encoder-only model "river bank" vs "bank account" mein "bank" ko alag kaise handle karta hai?
Bidirectional attention se, "bank" ek saath saare surrounding words dekhta hai. "river bank" mein yeh "river", "water" attend karta hai. "bank account" mein yeh "account", "money" attend karta hai. Alag attention patterns same word ke liye alag contextual embeddings create karte hain.
Decoder-only architecture mein sequence ki probability derive karo
P(x₁,...,xₙ) = ∏ᵢ₌₁ⁿ P(xᵢ | x₍<i₎). Yeh probability ke chain rule se aata hai. Causal masking ki wajah se har token sirf pehle ke tokens deke predict hota hai. Training maximize karta hai log ∑ log P(xᵢ | x₍<i₎).
Encoder-decoder architecture mein decoder layer ke teen components kya hain aur unka order?
(1) Decoder inputs par causal self-attention, (2) Cross-attention jahan Query=decoder, Key/Value=encoder, (3) Feed-forward network. Pehle self-attention decoder ko internal context build karne deta hai, phir cross-attention relevant encoder information retrieve karta hai.
Cross-attention Query ke liye decoder output lekin Key aur Value ke liye encoder outputs kyun use karta hai?
Query represent karta hai "decoder kya dhundh raha hai", Keys represent karta hai "encoder kya jaanta hai", Values represent karta hai "retrieve karni wali information". Decoder sawaal poochta hai (Q), encoder jawab deta hai (K/V). Yeh asymmetry directed information flow create karta hai: encoder → decoder.
Parameters compare karo: agar ek encoder-only model mein N parameters hain, toh same depth/width ke encoder-decoder model mein kitne honge?
Approximately 2N parameters. Encoder-decoder mein alag encoder stack + decoder stack + cross-attention layers hote hain. Isliye encoder-only (BERT) ya decoder-only (GPT) zyada parameter-efficient hote hain jab dono encoding aur generation ki zaroorat nahi.
BERT (encoder-only) kaun sa training objective use karta hai aur kyun?
Masked Language Modeling (MLM): randomly 15% tokens mask karo aur unhe predict karo. Yeh bidirectional context se train hota hai. Next-token prediction use NAHI kar sakte kyunki uske liye causal masking chahiye hogi, jo bidirectional encoding ka purpose hi khatam kar deti.

Concept Map

configures

governed by

pattern

pattern

pattern

all 1s enables

used by

example

task

example

example

stacks

refine

Transformer Patterns

Self-Attention

Attention Masking

Encoder-Only

Decoder-Only

Encoder-Decoder

Bidirectional Context

BERT Understanding

Sentiment Classification

GPT Generation

T5 Translation

Deep Layers L

Contextual Representations