Attention & Transformers

GATE Relevance: Medium

Prerequisites

  • RNNs — Sequence modelling basics
  • LSTM & GRU — Encoder–decoder framework

🎯 Learning Objectives

  • Understand why attention was introduced (information bottleneck)
  • Compute scaled dot-product attention: softmax(QKT/√dk)V
  • Explain multi-head attention and its benefit
  • Describe the transformer encoder–decoder architecture
  • Know positional encoding and layer normalisation
  • Distinguish BERT (encoder-only) and GPT (decoder-only)

1. The Information Bottleneck

In a vanilla encoder–decoder RNN, the encoder compresses the entire input sequence into a single fixed-size context vector c = hT. For long sequences, this bottleneck loses information.

Attention (Bahdanau et al., 2014) allows the decoder to look at all encoder hidden states and dynamically focus on the most relevant ones at each decoding step.

2. Scaled Dot-Product Attention

Attention Formula (Vaswani et al., 2017)

Attention(Q, K, V) = softmax(QKT / √dk) · V

Where:
  Q ∈ ℝn×dk  — Query matrix (n queries)
  K ∈ ℝm×dk  — Key matrix (m key-value pairs)
  V ∈ ℝm×dv  — Value matrix
  dk            — key dimension (scaling factor)
  Output ∈ ℝn×dv

Why Scale by √dk?

For large dk, the dot products QKT grow large in magnitude, pushing softmax into regions with extremely small gradients. Dividing by √dk keeps the variance of the dot products at roughly 1.

Numerical Example (dk = 2)

Q = [1, 0]   (1 query)
K = [[1, 0],  ← key 1
     [0, 1],  ← key 2
     [1, 1]]  ← key 3
V = [[10],
     [20],
     [30]]

Scores = QKT = [1·1+0·0, 1·0+0·1, 1·1+0·1] = [1, 0, 1]
Scaled = [1/√2, 0/√2, 1/√2] = [0.707, 0, 0.707]
Weights = softmax([0.707, 0, 0.707]) ≈ [0.387, 0.226, 0.387]
Output = 0.387×10 + 0.226×20 + 0.387×30 = 3.87 + 4.52 + 11.61 = 20.0

3. Self-Attention

When Q, K, and V all come from the same sequence, we call this self-attention. Each position attends to all other positions in the sequence.

Q = XWQ,  K = XWK,  V = XWV

Where X ∈ ℝn×dmodel is the input sequence.

Key advantage over RNNs: Self-attention computes relationships between any two positions in O(1) path length, compared to O(n) for RNNs. This eliminates the sequential bottleneck.

4. Multi-Head Attention

Multi-Head Attention

MultiHead(Q, K, V) = Concat(head1, …, headh) · WO

where headi = Attention(QWiQ, KWiK, VWiV)

Projection matrices:
  WiQ ∈ ℝdmodel × dk
  WiK ∈ ℝdmodel × dk
  WiV ∈ ℝdmodel × dv
  WO ∈ ℝhdv × dmodel

Typical: dk = dv = dmodel / h

Why multiple heads? Each head can attend to different types of relationships (e.g., syntactic vs semantic). With h = 8 heads and dmodel = 512, each head uses dk = 64.

5. Positional Encoding

Since self-attention has no inherent notion of position (it’s permutation-equivariant), position information is added explicitly:

Sinusoidal Positional Encoding

PE(pos, 2i)   = sin(pos / 100002i/dmodel)
PE(pos, 2i+1) = cos(pos / 100002i/dmodel)

Input to transformer = token embedding + PE

This encoding allows the model to attend to relative positions because PE(pos+k) can be expressed as a linear function of PE(pos).

6. Transformer Architecture

The Transformer (“Attention Is All You Need”, Vaswani et al., 2017) eliminates recurrence entirely.

Encoder Block (repeated N×)

1. Multi-Head Self-Attention
2. Add & Layer Norm (residual connection)
3. Feed-Forward Network: FFN(x) = max(0, xW1+b1)W2+b2
4. Add & Layer Norm

Decoder Block (repeated N×)

1. Masked Multi-Head Self-Attention (causal mask)
2. Add & Layer Norm
3. Multi-Head Cross-Attention (Q from decoder, K,V from encoder)
4. Add & Layer Norm
5. Feed-Forward Network
6. Add & Layer Norm

Transformer-Base Configuration

N = 6 layers, dmodel = 512, h = 8 heads, dff = 2048, dropout = 0.1. Total ∼65M parameters.

7. BERT & GPT

FeatureBERTGPT
ArchitectureEncoder-onlyDecoder-only
AttentionBidirectionalCausal (left-to-right)
Pre-trainingMasked Language Model + NSPAutoregressive LM
Best ForUnderstanding (classification, NER)Generation (text, code)
ParametersBERT-base: 110MGPT-2: 1.5B; GPT-3: 175B

Summary

  • Attention: softmax(QKT/√dk)V — weighted sum of values based on query-key similarity.
  • Multi-head attention: h parallel attention heads, concatenated and projected.
  • Positional encoding uses sinusoids to inject position information.
  • Transformer = stacked encoder/decoder blocks with self-attention + FFN + residual + LayerNorm.
  • BERT = encoder-only (bidirectional). GPT = decoder-only (causal).
  • For GATE: know the attention formula, scaling factor reason, and transformer block structure.