# Sequence Labeling (HMM Viterbi) & Transformers (Self-Attention, BERT vs GPT)
Exam: GATE Data Science & Artificial Intelligence (DA) (GATE DA)
Subject: Natural Language Processing (NLP) & LLMs
Canonical URL: https://gateandnet.com/exams/gate-da/natural-language-processing/hmm-viterbi-self-attention-and-transformers

> HMM generative tagging & O(T * S^2) Viterbi DP decoding, Scaled Dot-Product & Multi-Head Self-Attention parameter counts, Causal Masking, Positional Encodings, and BERT vs GPT vs T5.

## 1. Sequence Labeling: HMM + Viterbi vs Linear-Chain CRF

In Part-of-Speech (POS) tagging or Named Entity Recognition (NER), given words $O = (o_1, \dots, o_T)$, find the best tag sequence $\hat{Y} = (y_1, \dots, y_T)$:
- **Hidden Markov Model (Generative):** Maximizes $P(O, Y) = \prod_{t=1}^T \underbrace{P(y_t \mid y_{t-1})}_{\text{Transition } a_{ij}} \underbrace{P(o_t \mid y_t)}_{\text{Emission } b_j(o_t)}$ in $\mathcal{O}(T \cdot |S|^2)$ time using **Viterbi** (max-product) or computes marginal likelihood $P(O)$ using the **Forward Algorithm** (sum-product).
- **Linear-Chain CRF (Discriminative):** Directly models conditional $P(Y \mid O)$ with arbitrary overlapping orthographic features (capitalization, suffixes, surrounding words) without independence assumptions on $O$, avoiding the *label bias problem* of MEMMs.

## 2. Inside the Transformer Architecture (Vaswani et al.)

Given input token representations $X \in \mathbb{R}^{n \times d_{\text{model}}}$:
1. **Query, Key, Value Projections:** $Q = XW^Q,\; K = XW^K,\; V = XW^V$ with $d_k = d_v = d_{\text{model}} / h$.
2. **Why divide by $\sqrt{d_k}$?** If components of $q, k$ are independent with mean $0$ and variance $1$, then $q \cdot k = \sum_{i=1}^{d_k} q_i k_i$ has mean $0$ and **variance $d_k$** (std dev $\sqrt{d_k}$). Dividing by $\sqrt{d_k}$ restores unit variance so $\operatorname{softmax}$ doesn't saturate into near-zero gradient regions!
3. **Permutation Equivariance $\implies$ Positional Encoding Required:** Self-attention without positional info treats input as an unordered **bag/set**! Sinusoidal, learned, or **RoPE (Rotary Position Embeddings)** inject token order.
4. **Parameter Count of 1 Standard Transformer Encoder Block** (ignoring biases & LayerNorm $2d$):
   - Multi-Head Attention ($W^Q, W^K, W^V, W^O$): $4 \, d_{\text{model}}^2$
   - Position-wise FFN ($d_{\text{model}} \to 4d_{\text{model}} \to d_{\text{model}}$): $2 \times (d_{\text{model}} \times 4d_{\text{model}}) = 8 \, d_{\text{model}}^2$
   - **Total per layer** $\approx \mathbf{12 \, d_{\text{model}}^2}$!

## 3. Pretrained LLM Families: Encoder vs Decoder vs Encoder-Decoder

| Architecture | Canonical Models | Attention Mask | Pretraining Objective | Best Suited Tasks |
| :--- | :--- | :--- | :--- | :--- |
| **Encoder-Only** | **BERT, RoBERTa, DeBERTa** | Bidirectional ($n \times n$ full) | Masked Language Modeling (MLM 15%) | Classification, NER, Extractive QA, Embeddings |
| **Decoder-Only** | **GPT-4, Llama, Gemini, Claude** | **Causal Upper-Triangular** ($-\infty$ for $j > i$) | Autoregressive Next-Token Prediction | Open-ended Generation, Reasoning, Code, Chat |
| **Encoder-Decoder** | **T5, BART, Original Transformer** | Full Encoder + Causal Decoder + Cross-Attention | Span Corruption / Denoising | Translation, Seq2Seq Summarization |

## Solved Practice Questions & PYQs

### [GATE DA Transformer NAT | NAT]
A Multi-Head Self-Attention layer has model dimension $d_{\text{model}} = 512$ and $h = 8$ attention heads with $d_k = d_v = d_{\text{model}} / h$. What is the per-head key dimension **$d_k$**?
**Correct Answer:** 64
**Solution:** Each head projects into dimension $d_k = d_{\text{model}} / h = 512 / 8 = \mathbf{64}$ (and divides dot products by $\sqrt{64} = 8$).

### [GATE DA Transformers | MCQ]
For an input sequence of length $n$ and model hidden dimension $d$ (where $n > d$), what is the time complexity of computing **global Scaled Dot-Product Self-Attention** for one Transformer layer?
**Correct Answer:** B
**Solution:** Computing the $n \times n$ pairwise score matrix $Q K^T$ ($Q, K \in \mathbb{R}^{n \times d}$) and multiplying attention weights ($n \times n$) by $V$ ($n \times d$) both take **$\mathcal{O}(n^2 \cdot d)$** operations (quadratic in sequence length $n$!).

### [GATE DA NLP | MCQ]
An HMM Part-of-Speech tagger has $|S| = 12$ distinct POS tags and processes a sentence of $T = 20$ tokens. What is the asymptotic order of operations required by the **Viterbi algorithm** vs **naive exhaustive tag enumeration**?
**Correct Answer:** A
**Solution:** At each of $T$ positions, Viterbi computes maxima over $|S|$ previous states for each of $|S|$ current states: $\mathcal{O}(T \cdot |S|^2)$ ($20 \times 144 = 2,880$ steps) vs brute-force $|S|^T = 12^{20}$ sequences!

### [GATE DA LLMs | MCQ]
How does **GPT (Decoder-Only)** prevent token position $i$ from attending to future tokens $j > i$ during parallelized training?
**Correct Answer:** A
**Solution:** Setting pre-softmax attention logits to **$-\infty$** for $j > i$ ensures $\exp(-\infty) = 0$ after Softmax! (Trap: setting logits to $0$ before Softmax would give $\exp(0) = 1 > 0$, leaking future tokens!)

### [GATE DA 2027 Expected MSQ | MSQ]
Which of the following statements about **Transformer Self-Attention** and **Modern LLMs** are **TRUE**?
**Correct Answer:** A,B,D
**Solution:** - **A, B, D (True)!**
- **C (False — Classic Exam Trap!):** $8$ heads of $(512 \times 64)$ have exact same total parameters $8 \times 512 \times 64 = 512^2$ as a single $(512 \times 512)$ head!
