COMP5046 — Natural Language Processing

Lecture 6: Models — Transformer

Attention · Q/K/V · position & masks · encoder block · decoder cross-attention.

How to use: know each score formula’s role · close the page and answer Recall lines.

Beyond RNN

Why move beyond RNN encoders?

RecallWhat two RNN limits does attention mitigate?

Scores

Forms of attention

RecallWhy divide by \(\sqrt{d_k}\)?

All-to-all

Self-attention

RecallSelf-attention output \(\mathbf{o}_i\) as weighted sum — weights from what?

Learned

Query, key, value projections

Input X W_Q W_K W_V Q K V QKᵀ / √dₖ softmax α × V Output
Scaled dot-product attention: Q, K, V projected from input; scores = QKᵀ/√dₖ → softmax → weighted V.

RecallWhat do multiple heads buy you vs one head?

Order

Position and causal masking

Causal Attention Mask (4×4) t=1 t=2 t=3 t=4 t=1 t=2 t=3 t=4 −∞ −∞ −∞ −∞ −∞ −∞
Causal mask: position i can attend to j ≤ i (blue ✓) but not future j > i (red −∞). After softmax, future weights become 0.

RecallWhy causal mask in decoder training?

Stack

Transformer encoder layer

\(\mathbf{x}\)
Self-Attn
+ Residual
LayerNorm
FFN
+ Residual
LayerNorm
\(\mathbf{h}\)

RecallResidual + LN: one purpose each.

Seq2seq

Decoder and cross-attention

Encoder (×N) Self-Attn + Res + LN FFN + Res + LN K, V Decoder (×N) Masked Self-Attn + Res + LN Cross-Attn Q from decoder FFN + Res + LN Output
Full Transformer: encoder produces K,V; decoder uses masked self-attention + cross-attention (Q from decoder, K/V from encoder) + FFN. Stacked N times.

RecallWhere do Q vs K,V come from in cross-attention?

Impact

Landmark models & scaling

RecallBERT vs GPT: encoder-only or decoder-only? What do scaling laws predict?

Lab

Workshop 7 & materials

Quick practice

Why scale dot products by \(\sqrt{d_k}\)?
Dot products grow with \(d_k\), saturating softmax and shrinking gradients; scaling restores stable variance
It makes the model faster
Without scaling, attention weights are always uniform
The scale factor is a learned parameter
Why does the decoder use a causal mask?
To reduce computation by ignoring some positions
To handle variable-length sequences
To prevent attending to future tokens, preserving the autoregressive property
To mask padding tokens only

Chapter quizzes

Retrieval practice for this lecture.

Open Quiz Hub Chapter flashcards