Encoder vs decoder vs encoder-decoder
Overview
The three fundamental transformer architecture patterns solve different sequence-to-sequence problems by using self-attention mechanisms in different configurations. Understanding when to use each is crucial for choosing the right model for your task.

The key difference is in attention masking and information flow patterns.
1. Encoder-Only Architecture
How It Works (From First Principles)
Step 1: Bidirectional Context Building
For input sequence :
WHY bidirectional? The attention mask is all1s:
This means token can see token regardless of position. Token3 sees tokens 1, 2, 4, 5, etc.
WHY does this matter? The word "bank" in "river bank" vs "bank account" gets different representations because it sees ALL surrounding words simultaneously.
Step 2: Deep Contextual Representations
After encoder layers, each token embedding contains information from the ENTIRE sequence:
WHY multiple layers? Each layer refines understanding:
- Layer 1: "bank" sees "river" nearby
- Layer 2: "bank" sees "water" and "shore" contextually
- Layer 3: "bank" representation now encodes "river-bank-not-financial-bank"
Derivation:
- Start with raw similarity: (dot product measures relevance)
- Scale by to prevent saturation: (keeps gradients healthy)
- Softmax over ALL positions: (normalizes to probability distribution)
Output representation:
Input tokens: [CLS] This movie was not bad at all ! [SEP]
WHY [CLS]? Special token whose final representation aggregates sentence meaning.
Layer 1 attention for "not":
- Attends to: "bad" (0.4), "at" (0.1), "all" (0.2 "was" (0.15), "!" (0.15)
- Why? "not" modifies "bad", needs local context
Layer 6 attention for "not":
- Now [CLS] attends to: "not" (0.3), "bad" (0.25), "!" (0.2)
- Why this matters? [CLS] learned "not bad" = positive sentiment through bidirectional flow
Final classification:
Best for: Classification, named entity recognition, question answering (when answer is IN the input)
2. Decoder-Only Architecture
How It Works (From First Principles)
Step 1: Causal Masking
The attention mask is now lower-triangular:
WHY? During generation, position hasn't been generated yet when computing position .
Implementation:
where if else .
WHY ? After softmax, , completely blocking future tokens.
Step 2: Autoregressive Generation
Generate token-by-token:
where only depends on .
Full sequence probability:
WHY product? Chain rule of probability:
Generation process:
| Step | Input | Attention | Output Token | Why? |
|------|-------|-----------|--------------|
| 1 | [The capital of France is] | Each token sees only left | "Paris" | Pattern: "[capital of X is Y]" learned from training |
| 2 | [The capital of France is Paris] | "Paris" only sees prompt | "," | Punctuation pattern after city names |
| 3 | [.., Paris,] | "," sees all previous | "which" | Common continuation "Paris, which..." |
Token 3 attention for "which":
- Attends to: "is" (0.1), "Paris" (0.4), "," (0.3), "France" (0.15)
- Cannot see future (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, any autoregressive task
3. Encoder-Decoder Architecture
How It Works (From First Principles)
Step 1: Encoder (Bidirectional)
Processes source sequence with full bidirectional attention:
Each sees all source tokens.
Step 2: Decoder Self-Attention (Causal)
Processes target sequence with causal masking:
Step 3: Cross-Attention (The Key Innovation)
Decoder attends to ALL encoder outputs:
Derivation of cross-attention:
- Query from decoder: (what decoder is "asking about")
- Keys from encoder: (what encoder "knows")
- Values from encoder: (encoder's information to retrieve)
WHY cross-attention? Decoder position can "look at" any encoder position, but still can't see its own future.
Decoder layer (simplified):
- Causal self-attention:
- Cross-attention:
- Feed-forward:
Generation:
Encoding phase:
Input: [The, cat, sleeps]
Encoder output: [h_The, h_cat, h_sleps]
Each contains bidirectional context.
Decoding step 1: Generate "Le"
- Decoder input:
[START] - Self-attention: Only sees
[START](nothing to left) - Cross-attention: Queries encoder
- Attention weights: {The: 0.6, cat: 0.3, sleeps: 0.1}
- Why? "Le" (article) relates most to "The"
- Output: "Le"
Decoding step 2: Generate "chat"
- Decoder input:
[START, Le] - Self-attention: "chat" attends to "Le" (0.4) and START (0.6)
- Cross-attention:
- Attention weights: {The: 0.1, cat: 0.8, sleeps: 0.1}
- Why? "chat" is translation of "cat"
- Output: "chat"
Decoding step 3: Generate "dort"
- Decoder input:
[START, Le, chat] - Self-attention: "dort" sees "Le" (0.2), "chat" (0.5), START (0.3)
- Cross-attention:
- Attention weights: {The: 0.05, cat: 0.15, sleeps: 0.8}
- Why? "dort" translates "sleps"
- Output: "dort"
Why encoder-decoder wins here?
- Encoder builds full understanding of English sentence
- Decoder generates French word-by-word
- Cross-attention aligns source and target (attention as soft alignment)
Best for: Translation, summarization, question answering (generating answers), any seq2seq with different input/output
Architecture Comparison Table
| Aspect | Encoder-Only | Decoder-Only | Encoder-Decoder | |--------|--------------|-----------------| | Attention Type | Bidirectional | Causal (unidirectional) | Both + cross-attention | | Token Visibility | All tokens | Only previous tokens | Encoder: all; Decoder: previous + encoder | | Training Objective | Masked LM (MLM) | Next token prediction | Seq2seq loss | | Generation | ❌ No | ✅ Yes (autoregressive) | ✅ Yes (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 |
The fix: Encoders are MORE powerful at understanding because they see both directions. For tasks requiring deep comprehension (semantic search, classification with subtle cues), encoders win.
Example: BERT classifies sentiment better than GPT-style models of same size because "not bad" requires seeing BOTH words simultaneously during encoding.
The fix: Cross-attention is asymetric:
- Query from decoder (decoder asking questions)
- Key/Value from encoder (encoder providing answers)
Regular attention is symmetric (Q, K, V all from same sequence). Cross-attention creates information flow: encoder → decoder.
Example: When generating "dort", the decoder QUERIES the encoder for "which English word am I translating?" The encoder's "sleps" representation RESPONDS through high attention weight.
The fix: Encoder-decoder has 2× parameters and is overkill when you don't need both directions.
Rules:
- Same input/output modality + generation → Decoder-only (GPT)
- Understanding without generation → Encoder-only (BERT)
- Different input/output or summarization → Encoder-decoder (T5)
Mathematical Connections
Unified View: All three are special cases of the general transformer equation:
where is the neighborhood that token can attend to:
- Encoder: (all tokens)
- Decoder: (causal)
- Encoder-Decoder: (self) (cross)
Recall Explain to a 12-year-old
Imagine you're working on a group project with three different helpers:
Helper 1 (Encoder-only): The "Super Reader"
- Reads the WHOLE book before answering your question
- Sees the ending before understanding the beginning
- Best at: "What's this story about?" (understanding tasks)
- Can't write new stories, just understands existing ones
Helper 2 (Decoder-only): The "Story Writer"
- Writes stories word by word, never peeking ahead
- Only remembers what they've already written
- Best at: "Continue this story..." (generation tasks)
- Writes new content but doesn't do deep reading
Helper 3 (Encoder-Decoder): The "Translator"
- First, reads the WHOLE French sentence (encoder)
- Then, writes English word-by-word (decoder)
- While writing each English word, looks back at the French (cross-attention)
- Best at: "Change this into something else" (transformation tasks)
The key difference? Where they can look while working!
Or: "Bidirectional Brain, Causal Creator, Cross-attention Converter"
Connections
- Self-Attention Mechanism - Foundation for all three architectures
- Positional Encoding - How all variants handle sequence order
- Multi-Head Attention - Used in encoder, decoder, and cross-attention
- Masked Language Modeling - Training objective for encoder-only
- Causal Language Modeling - Training objective for decoder-only
- Sequenceto-Sequence Models - Problem class solved by encoder-decoder
- Attention Masking - Different masks define each architecture
- BERT - Canonical encoder-only model
- GPT - Canonical decoder-only model
- T5 - Canonical encoder-decoder model
- Cross-Attention - Unique component of encoder-decoder
- Autoregressive Generation - How decoders and encoder-decoders generate
#flashcards/ai-ml
What is the key attention difference between encoder-only and decoder-only architectures? :: Encoder-only uses bidirectional attention (each token sees all tokens), while decoder-only uses causal attention (each token only sees previous tokens). This is enforced through attention masking.
Why can't decoder-only models use bidirectional attention?
Derive the causal attention mask mathematically :: Mask_{ij} = 1 if j ≤ i, else 0. Implemented as: Attention(Q,K,V) = softmax(QK^T/√d_k + M)V, where M_{ij} = 0 if j≤i, else -∞. The -∞ becomes 0 after softmax, blocking future tokens.
What is cross-attention and which architecture uses it?
Why do encoder-decoder models use cross-attention instead of just concatenating encoder and decoder?
When should you choose encoder-only vs decoder-only vs encoder-decoder?
How does an encoder-only model like BERT handle the word "bank" differently in "river bank" vs "bank account"?
Derive the probability of a sequence in decoder-only architecture
What are the three components of a decoder layer in encoder-decoder architecture and their order?
Why does cross-attention use encoder outputs for both Key and Value but decoder output for Query?
Compare parameter counts: if an encoder-only model has N parameters, how many does an encoder-decoder model of same depth/width have?
What training objective does BERT (encoder-only) use and why?
Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Dekho, transformers ke teen main prakar hain aur ye samajhna bahut zaroori hai kiab kaun sa use karna hai.
Encoder-only (jaise BERT)ek kitab padhne wale ki tarah hai jo pehle pori kitaab padh leta hai, phir tumhare sawaal ka jawab deta hai. Ye "bidirectional" hai matlab har shabd sabhi dosre shabdon ko dekh sakta hai - pichle bhi aur age ke bhi. Jaise "bank" shabd ko samajhne ke liye ye "river" aur "account" dono dekh sakta hai same time pe. Iska matlab ye classification aur understanding tasks ke liye best hai jahan generation ki zaroorat nahi.
Decoder-only (jaise GPT) ek kahani likhne wale ki tarah hai jo ek shabd likh raha hai bina age dekhe. Ye "causal" hai matlab har shabd sirf pichle shabdon ko dekh sakta hai, future ko nahi. Ye