Level 5 — MasterySequence Models

Sequence Models

90 minutes60 marksprintable — key stays hidden on paper

Time limit: 90 minutes Total marks: 60 Instructions: Answer all THREE questions. Show all derivations. Notation: σ\sigma is the logistic sigmoid, \odot is elementwise (Hadamard) product, \|\cdot\| is the spectral norm unless stated.


Question 1 — Vanishing gradients: proof + numerics (20 marks)

Consider a vanilla RNN with hidden update ht=tanh(Wht1+Uxt+b),at=Wht1+Uxt+b.h_t = \tanh(W h_{t-1} + U x_t + b),\qquad a_t = W h_{t-1} + U x_t + b.

(a) Derive the Jacobian htht1\dfrac{\partial h_t}{\partial h_{t-1}} and show that the gradient of a loss LL at time TT w.r.t. an early state hkh_k factorises as a product of Jacobians. Write the product explicitly. (4)

(b) Let Dt=diag(1tanh2(at))D_t=\operatorname{diag}(1-\tanh^2(a_t)). Prove the bound hThkt=k+1TDtW.\left\|\frac{\partial h_T}{\partial h_k}\right\| \le \prod_{t=k+1}^{T}\|D_t\|\,\|W\|. Hence give a sufficient condition on W\|W\| that guarantees the gradient contracts geometrically to zero, and a necessary condition (via largest singular value) for it to not vanish. (6)

(c) Take the scalar case ht=tanh(wht1)h_t=\tanh(w\,h_{t-1}) with w=0.5w=0.5, and suppose at every step tanh(at)=0.8\tanh'(a_t)=0.8. Compute the multiplicative gradient factor t=k+1T\prod_{t=k+1}^{T} for a span of Tk=10T-k=10 steps. Give the value and state whether this vanishes. (4)

(d) LSTMs mitigate this via the cell-state path ct=ftct1+itc~tc_t = f_t\odot c_{t-1} + i_t\odot \tilde c_t. Show ct/ct1=diag(ft)\partial c_t/\partial c_{t-1}=\operatorname{diag}(f_t) (ignoring the indirect dependence through gates), and explain in two sentences why a forget gate near 11 preserves gradient flow where the tanh path does not. (6)


Question 2 — Attention mechanism: build and analyse (22 marks)

An encoder produces annotations h1,,hSRdh_1,\dots,h_S\in\mathbb{R}^d. A decoder state is sRds\in\mathbb{R}^d.

(a) Bahdanau (additive) attention scores: ej=vtanh(Was+Uahj)e_j = v^\top\tanh(W_a s + U_a h_j). Luong (dot) attention: ej=shje_j = s^\top h_j. State one computational and one representational difference between them, and explain why Bahdanau uses the previous decoder state st1s_{t-1} while Luong uses the current sts_t. (6)

(b) Attention weights are αj=softmax(e)j\alpha_j = \operatorname{softmax}(e)_j and context c=jαjhjc=\sum_j \alpha_j h_j. Derive αiej\dfrac{\partial \alpha_i}{\partial e_j} (the softmax Jacobian) and give it in closed form. (4)

(c) Numerical: with S=3S=3 scores e=(2,1,0)e=(2,\,1,\,0), compute the attention weights α\alpha (to 3 decimals) and the context as a convex combination coefficient vector. Verify jαj=1\sum_j\alpha_j=1. (6)

(d) Show that if all scores are equal, attention reduces to a uniform average c=1Sjhjc=\frac1S\sum_j h_j, and argue why this is the desired "no information" prior. Then show that as the gap emaxe2nde_{\max}-e_{\text{2nd}}\to\infty, attention converges to a hard argmax\arg\max (hard attention). (6)


Question 3 — Seq2seq decoding: beam search build + complexity (18 marks)

A seq2seq model outputs, at each step, a distribution over a vocabulary VV. We decode with beam search, beam width kk, using length-normalised log-probability score.

(a) Give the beam-search update rule: from kk live hypotheses, how many candidate extensions are generated, and how are the top-kk selected? Why do we sum log-probabilities rather than multiply probabilities? (4)

(b) Worked example. Vocabulary {A,B}\{A,B\}, beam width k=2k=2, start empty. Step-1 token probs: P(A)=0.6,  P(B)=0.4P(A)=0.6,\;P(B)=0.4. Step-2 conditional probs:

prefix P(A)P(A\mid\cdot) P(B)P(B\mid\cdot)
A 0.7 0.3
B 0.5 0.5

Enumerate all length-2 sequences with their probabilities, and identify the two beams kept after step 2 (highest joint probability). State the single most probable sequence. (8)

(c) State the time complexity of beam search over LL steps as a function of kk, V|V|, LL. Contrast with exhaustive search complexity and with greedy (k=1k=1). Give one reason length-normalisation is applied before final ranking. (6)

Answer keyMark scheme & solutions

Question 1

(a) [4] Since ht=tanh(at)h_t=\tanh(a_t) with at=Wht1+Uxt+ba_t=Wh_{t-1}+Ux_t+b, by chain rule htht1=diag(tanh(at))W=DtW,Dt=diag(1tanh2(at)).\frac{\partial h_t}{\partial h_{t-1}} = \operatorname{diag}(\tanh'(a_t))\,W = D_t W,\quad D_t=\operatorname{diag}(1-\tanh^2(a_t)). (2) Loss gradient telescopes: Lhk=LhTt=k+1Ththt1=LhTt=k+1TDtW.\frac{\partial L}{\partial h_k}=\frac{\partial L}{\partial h_T}\prod_{t=k+1}^{T}\frac{\partial h_t}{\partial h_{t-1}}=\frac{\partial L}{\partial h_T}\prod_{t=k+1}^{T}D_tW. (2)

(b) [6] Submultiplicativity of the spectral norm: ABAB\|AB\|\le\|A\|\|B\|. Applying to the product: t=k+1TDtWt=k+1TDtW.\Big\|\prod_{t=k+1}^{T}D_tW\Big\|\le\prod_{t=k+1}^{T}\|D_t\|\,\|W\|. (3) Since tanh(0,1]\tanh'\in(0,1], Dt1\|D_t\|\le1. Hence if W<1\|W\|<1 the bound is WTk0\le\|W\|^{T-k}\to0: sufficient condition W<1\|W\|<1 gives geometric contraction (vanishing). (2) Necessary (non-vanishing) condition: the largest singular value σmax(W)1\sigma_{\max}(W)\ge1 (and the DtD_t not too small), otherwise the product norm is bounded above by WTk<1\|W\|^{T-k}<1 decaying to 00. (1)

(c) [4] Scalar factor per step =tanh(at)w=0.8×0.5=0.4=\tanh'(a_t)\cdot w = 0.8\times0.5 = 0.4. (2) Over 10 steps: 0.410=1.048576×1041.05×1040.4^{10}=1.048576\times10^{-4}\approx1.05\times10^{-4}. (1) This is 1\ll1, so the gradient vanishes. (1)

(d) [6] ct=ftct1+itc~tc_t=f_t\odot c_{t-1}+i_t\odot\tilde c_t. Treating ft,it,c~tf_t,i_t,\tilde c_t as constants w.r.t. ct1c_{t-1} (ignoring gate dependence), ctct1=diag(ft).\frac{\partial c_t}{\partial c_{t-1}}=\operatorname{diag}(f_t). (3) The product over time is tdiag(ft)\prod_t\operatorname{diag}(f_t); if ft1f_t\approx1 the product stays near 11, so gradients neither vanish nor explode — a constant error carousel. The tanh path instead multiplies by DtWD_tW with Dt1\|D_t\|\le1 and W\|W\| typically <1<1, giving geometric decay. (3)


Question 2

(a) [6]

  • Computational: Bahdanau requires a small MLP (v,Wa,Uav,W_a,U_a, a tanh) per (query,key) pair — more parameters/FLOPs; Luong dot-product has no extra parameters and is cheaper/parallelisable. (2)
  • Representational: additive scoring can align keys/queries of different subspaces and is more expressive for small dims; dot-product assumes query and key live in the same space and scale. (2)
  • Bahdanau computes attention using st1s_{t-1} because the context is fed into the RNN cell to produce sts_t (attention precedes the recurrence). Luong computes attention with sts_t because it applies attention after the RNN update, then combines context with sts_t. (2)

(b) [4] Softmax αi=eei/meem\alpha_i=e^{e_i}/\sum_m e^{e_m}. αiej=αi(δijαj),\frac{\partial\alpha_i}{\partial e_j}=\alpha_i(\delta_{ij}-\alpha_j), i.e. diag(α)αα\operatorname{diag}(\alpha)-\alpha\alpha^\top. Derivation: for i=ji=j, quotient rule gives αiαi2\alpha_i-\alpha_i^2; for iji\ne j, αiαj-\alpha_i\alpha_j. (4)

(c) [6] Exponentials: e2=7.389,  e1=2.718,  e0=1e^2=7.389,\;e^1=2.718,\;e^0=1. Sum =11.107=11.107. (2) α1=7.389/11.107=0.665\alpha_1=7.389/11.107=0.665, α2=2.718/11.107=0.245\alpha_2=2.718/11.107=0.245, α3=1/11.107=0.090\alpha_3=1/11.107=0.090. (3) Sum =0.665+0.245+0.090=1.000=0.665+0.245+0.090=1.000. Context c=0.665h1+0.245h2+0.090h3c=0.665\,h_1+0.245\,h_2+0.090\,h_3. (1)

(d) [6] If ej=ee_j=e for all jj: αj=ee/(See)=1/S\alpha_j=e^{e}/(S e^{e})=1/S, so c=1Shjc=\frac1S\sum h_j, uniform average. (3) This is the maximum-entropy / least-committal distribution — with no evidence favouring any position, equal weight avoids bias. (1) Let e(1)e_{(1)} be the max with gap Δ=e(1)e(2)\Delta=e_{(1)}-e_{(2)}\to\infty. Then α(1)=1/(1+j(1)e(e(1)ej))1/(1+0)=1\alpha_{(1)}=1/(1+\sum_{j\ne(1)}e^{-(e_{(1)}-e_j)})\to1/(1+0)=1, all others 0\to0: attention selects a single position — hard attention / argmax\arg\max. (2)


Question 3

(a) [4] From kk live hypotheses each is extended by every token in VV, giving kVk\cdot|V| candidates. Score each by (length-normalised) cumulative log-prob; keep the top kk overall as the new beam. (2) We sum log-probabilities because the joint probability is a product tP(yt)\prod_t P(y_t\mid\cdot); multiplying many probabilities (0,1)\in(0,1) underflows numerically and log turns it into a numerically stable sum. (2)

(b) [8] Joint probabilities:

  • AA=0.6×0.7=0.42AA = 0.6\times0.7 = 0.42
  • AB=0.6×0.3=0.18AB = 0.6\times0.3 = 0.18
  • BA=0.4×0.5=0.20BA = 0.4\times0.5 = 0.20
  • BB=0.4×0.5=0.20BB = 0.4\times0.5 = 0.20 (4)

Sorted: AA(0.42)>BA(0.20)=BB(0.20)>AB(0.18)AA(0.42) > BA(0.20)=BB(0.20) > AB(0.18). Beams kept after step 2 (top 2): {AA=0.42,  BA=0.20}\{AA=0.42,\; BA=0.20\} (ties broken to BABA; BB=0.20BB=0.20 equally valid). (3) Most probable sequence: AAAA with 0.420.42. (1)

(c) [6] Per step we score kVk|V| candidates and re-select top-kk (cost O(kVlogk)O(k|V|\log k) or O(kV)O(k|V|)); over LL steps total O(LkV)O(L\,k\,|V|) (plus decoder forward passes). (2) Exhaustive search is O(VL)O(|V|^L) — exponential; greedy is the k=1k=1 special case, cheapest but no back-up hypotheses. (2) Length-normalisation (dividing log-prob by length, or lengthα^\alpha) is applied before final ranking because raw joint log-prob is a sum of negative terms that grows in magnitude with length, biasing beam search toward shorter sequences; normalising makes hypotheses of different lengths comparable. (2)

[
  {"claim":"Q1c gradient factor 0.4^10 approx 1.048576e-4",
   "code":"val=(Rational(8,10)*Rational(5,10))**10; result=abs(float(val)-1.048576e-4)<1e-9"},
  {"claim":"Q2c softmax weights of (2,1,0) sum to 1 and alpha1 approx 0.665",
   "code":"import math; e=[math.exp(2),math.exp(1),math.exp(0)]; s=sum(e); a=[x/s for x in e]; result=(abs(sum(a)-1)<1e-9) and (abs(a[0]-0.665)<1e-3)"},
  {"claim":"Q3b joint probabilities AA=0.42 max, AB=0.18",
   "code":"AA=Rational(6,10)*Rational(7,10); AB=Rational(6,10)*Rational(3,10); BA=Rational(4,10)*Rational(5,10); result=(AA==Rational(42,100)) and (AB==Rational(18,100)) and (AA>BA) and (AA>AB)"},
  {"claim":"Q2b softmax Jacobian diagonal entry equals alpha_i(1-alpha_i)",
   "code":"a1=symbols('a1'); result=simplify(a1*(1-a1)-(a1-a1**2))==0"}
]