Sequence Models
Chapter: 3.5 Sequence Models Level: 3 — Production (from-scratch derivations, code-from-memory, explain-out-loud) Time limit: 45 minutes Total marks: 60
Instructions: Show all derivations. Where code is asked, pseudocode/NumPy-style from memory is acceptable if logic is correct. Use notation for math.
Question 1 — RNN forward + BPTT gradient (12 marks)
Consider a vanilla RNN with hidden update
(a) Write the forward recurrence and state the shapes of given input dim , hidden dim , output dim . (3)
(b) For scalar loss , derive using backpropagation through time. Include the recursive expression for . (6)
(c) Show that the Jacobian . (3)
Question 2 — Vanishing gradients derivation (10 marks)
(a) Starting from , give a bound on its norm in terms of the largest singular value of and bound. (4)
(b) State the precise condition on (with ) that guarantees vanishing gradients, and explain why. (3)
(c) Name two architectural fixes and one training-time fix, each in one sentence. (3)
Question 3 — LSTM vs GRU from memory (12 marks)
(a) Write ALL LSTM gate equations (forget, input, candidate, cell update, output, hidden). (6)
(b) Write ALL GRU equations (update, reset, candidate, hidden). (4)
(c) Explain in one sentence each: why the LSTM additive cell path mitigates vanishing gradients, and how GRU differs in parameter count/structure. (2)
Question 4 — Attention mechanism (12 marks)
(a) Given encoder states and decoder state , write the general attention pipeline: score → weights → context vector. (4)
(b) Give the Bahdanau (additive) score and the Luong (multiplicative/dot) score formulas, and state one architectural difference between how they use the decoder state. (5)
(c) Compute attention weights: scores . Give the softmax weights (to 3 dp) and the resulting context if . (3)
Question 5 — Seq2seq, teacher forcing, beam search (10 marks)
(a) Draw/describe the encoder–decoder architecture and explain teacher forcing vs free-running decoding, plus one risk of teacher forcing. (4)
(b) Beam search with beam width . At step 1 vocab log-probs are . From : next ; from : next . List surviving beams after step 2 with cumulative log-probs, ranked. (6)
Question 6 — Word embeddings + variable-length (4 marks)
(a) State the training objective difference between Word2Vec skip-gram and GloVe. (2)
(b) Explain padding + masking for variable-length batches in one sentence, and why masking matters for the loss. (2)
Answer keyMark scheme & solutions
Question 1 (12)
(a) Forward: , , with . (1) Shapes: , , . (2, 1 each pair-set)
(b) Let . Since affects (via ) and : (3) With , . Then (3) — summed over all timesteps because is shared.
(c) , ; ; chain gives . (3)
Question 2 (10)
(a) where , . So bound . (4)
(b) Vanishing if (more precisely with , so suffices): the product exponentially as grows, so gradients from distant timesteps vanish. (3)
(c) Fixes: LSTM/GRU gating (additive cell path); residual/skip connections; and training-time: gradient clipping (also helps exploding), or good init (orthogonal ). (3)
Question 3 (12)
(a) (6, 1 each)
(b) (4, 1 each)
(c) LSTM: gives a near-identity additive path so gradient avoids repeated multiplicative shrink. GRU: fewer gates (2 vs 3), no separate cell state → fewer parameters. (2)
Question 4 (12)
(a) (4) Score ; weights ; context .
(b) (5) Bahdanau (additive): . Luong (dot): (or general). Difference: Bahdanau uses previous state to compute attention before generating ; Luong uses the current state after the RNN step. (2 formulas, 2 formulas, 1 diff)
(c) (3) softmax of : denom ; weights . Context .
Question 5 (10)
(a) (4) Encoder RNN compresses input into context (final hidden state); decoder RNN generates output conditioned on context, feeding previous token as input. Teacher forcing: feed ground-truth previous token during training; free-running: feed model's own prediction. Risk: exposure bias — train/inference mismatch degrades inference.
(b) (6) Step-2 cumulative log-probs:
- A→X:
- A→Y:
- B→X:
- B→Y:
Keep top : A→X (), B→X (). (4 computation, 2 selection/ranking)
Question 6 (4)
(a) (2) Skip-gram: predict context words from center word (local, softmax/negative sampling). GloVe: factorize/fit log co-occurrence counts globally, minimizing weighted least-squares on .
(b) (2) Pad shorter sequences to max length with a pad token; a boolean mask zeros out padded positions so padding doesn't contribute to loss/attention — otherwise the model would learn from meaningless pad tokens.
[
{"claim":"Softmax of [2,1,0] weights approx [0.665,0.245,0.090]","code":"e=[exp(2),exp(1),exp(0)];s=sum(e);w=[float(x/s) for x in e];result=all(abs(a-b)<1e-2 for a,b in zip(w,[0.665,0.245,0.090]))"},
{"claim":"Attention context = [0.755,0.335]","code":"e=[exp(2),exp(1),exp(0)];s=sum(e);w=[x/s for x in e];h=[[1,0],[0,1],[1,1]];c=[sum(w[j]*h[j][d] for j in range(3)) for d in range(2)];result=all(abs(float(a)-b)<1e-2 for a,b in zip(c,[0.755,0.335]))"},
{"claim":"Beam step-2 survivors are A-X(-0.9) and B-X(-1.3)","code":"cands={'AX':-0.5-0.4,'AY':-0.5-1.2,'BX':-1.0-0.3,'BY':-1.0-0.7};top=sorted(cands,key=lambda k:-cands[k])[:2];result=set(top)=={'AX','BX'} and abs(cands['AX']+0.9)<1e-9 and abs(cands['BX']+1.3)<1e-9"},
{"claim":"Vanishing gradient product gamma=0.9 over 20 steps is tiny","code":"result=(Rational(9,10)**20) < Rational(1,10)"}
]