Transformer Architecture
Level 4 (Application: novel/unseen problems) Time: 60 minutes Total Marks: 60
Instructions: Show all reasoning. Use for math. Calculators permitted; no external references.
Question 1 — Scaled Dot-Product Attention on Concrete Vectors (12 marks)
A single attention head processes 3 tokens with . The projected matrices are:
(a) Compute the raw score matrix and then divide by . (4) (b) Explain why we divide by and what would degrade numerically if were 512 and we omitted it. (3) (c) For token 1 (first row), compute the softmax attention weights over the 3 keys (using the scaled scores) and the resulting output vector. Keep 3 decimals. (5)
Question 2 — Designing a Causal Language Model Head (14 marks)
You are asked to adapt an encoder-style block into a decoder-only autoregressive model over a length- sequence.
(a) Write down the additive mask matrix (entries or ) that must be added to the pre-softmax scores for , and state the rule for entry . (4) (b) A colleague suggests applying the mask after the softmax by zeroing forbidden weights. Prove this is incorrect by showing the row would no longer be a valid probability distribution, and give the correct fix if one insisted on post-softmax masking. (4) (c) Explain precisely why, at inference time, a KV-cache makes causal decoding cheaper, and give the per-new-token attention cost with and without the cache in Big-O terms (sequence so far length ). (6)
Question 3 — Positional Encoding Under Sequence Extrapolation (12 marks)
(a) For sinusoidal encodings with model dimension , base , write the encoding vector as a function of (give the 4 component formulas). (4) (b) A model trained on length 512 is asked to process length 4096. Contrast how sinusoidal absolute encodings vs RoPE behave with respect to relative position and extrapolation, and justify why RoPE's rotation formulation preserves relative offsets. (5) (c) Show that in RoPE, the dot product between a query at position and a key at position depends only on for a single 2D rotary sub-block. (3)
Question 4 — Complexity Trade-off Analysis (12 marks)
A transformer layer has sequence length , model dim , FFN hidden dim , and heads.
(a) Derive the asymptotic cost (FLOPs, Big-O) of: (i) the self-attention score+weighting, (ii) the QKV+output projections, (iii) the FFN sublayer. (6) (b) For , , identify which term dominates and by roughly what ratio (order-of-magnitude, ignoring constants). (3) (c) State the key idea by which FlashAttention reduces memory (not asymptotic FLOP) cost, and explain why it never materialises the full matrix. (3)
Question 5 — Multi-Head vs Single-Head Reasoning (10 marks)
A model has . Compare configuration A: 1 head with , vs configuration B: 8 heads with .
(a) Show both configurations have (approximately) the same number of parameters in the QKV projections. (4) (b) Give a concrete functional advantage of B over A that A structurally cannot replicate, and justify it. (3) (c) After concatenating 8 head outputs of dim 64, what is the role and shape of , and why is it needed even though concatenation already gives dimension 512? (3)
Answer keyMark scheme & solutions
Question 1 (12)
(a) : compute row·row dot products. Rows of : ; same as keys.
Divide by : Marks: correct matrix (2), correct scaling (2).
(b) Dot products of -dim vectors with unit-variance components have variance ; scaling by normalises variance to . Without it at , scores grow ~, pushing softmax into saturated regions → near one-hot outputs and vanishing gradients (softmax derivative ), harming training. (variance reasoning 2, gradient consequence 1).
(c) Token 1 scaled scores: . Exponentials: ; sum . Weights: . Output . Marks: exponentials/softmax (3), output vector (2).
Question 2 (14)
(a) Rule: if (key at or before query), if . (rule 2, matrix 2).
(b) Softmax normalises over all positions first: . Zeroing entries afterward leaves (mass leaked to now-zeroed future terms), so the row is not a distribution and outputs are mis-scaled. Correct post-softmax fix: zero forbidden weights then renormalise by dividing by the surviving sum — equivalent to additive masking. (prove leakage 2, renormalise fix 2).
(c) Without cache: at step you recompute for all tokens → attention costs per generated token (or for the single new query against keys but recomputing all keys is projections; recompute of full attention is ). With KV-cache: keys/values of past tokens are stored, so only the new token's are computed and it attends to cached keys → per new token. Over a full sequence: cached vs recomputing. (cache concept 2, without-cache cost 2, with-cache cost 2).
Question 3 (12)
(a) , indices ; frequencies .
- (since )
- (each pair/frequency 2 each).
(b) Sinusoidal absolute encodings are added to embeddings; at length 4096 the model sees values (and low-frequency phases) never encountered during training → poor extrapolation, though sinusoids are defined for all . RoPE instead rotates Q/K by an angle proportional to position; attention scores depend on relative angle , so a shift in absolute position leaves relative structure invariant, giving smoother length extrapolation. RoPE encodes relative position implicitly in the dot product rather than as an additive absolute signal. (sinusoidal limitation 2, RoPE relative property 2, justification 1).
(c) For a 2D sub-block, RoPE applies rotation to and to : Since , the result depends only on . (rotation composition 2, conclusion 1).
Question 4 (12)
(a) (i) Scores : from → ; weighting also . Total attention core . (ii) QKV projections: 3 matmuls by → ; output projection . (iii) FFN: by , then back → . (each part 2).
(b) Attention term vs projection/FFN term . Ratio attention/FFN . So attention (the term) dominates by roughly at this configuration. (identify crossover 1, ratio 2).
(c) FlashAttention tiles Q,K,V into blocks kept in fast SRAM and computes softmax online (running max + running sum, streaming), so the score matrix is never written to HBM. This reduces memory from to (plus recomputation in backward), while FLOPs stay . (online softmax/tiling 2, no full matrix 1).
Question 5 (10)
(a) QKV projection params: for config A, three matrices . For config B, each head has for Q,K,V; 8 heads → . Equal. (A count 2, B count and equality 2).
(b) B can attend to different representation subspaces simultaneously — e.g. one head tracks syntactic dependency while another tracks positional/coreference — producing distinct attention distributions per head. A single head yields exactly one attention distribution per query, so it cannot mix multiple relational patterns in one layer. (advantage 2, justification 1).
(c) has shape (). Concatenation just stacks head outputs in fixed slots; mixes/recombines information across heads and projects back into the model space, letting the layer learn how head outputs interact rather than treating them as independent fixed partitions. (shape 1, role/mixing 2).
[
{"claim":"Q1a scaled score matrix correct", "code":"Q=Matrix([[1,0],[0,1],[1,1]]); K=Q; S=Q*K.T/sqrt(2); result = S.equals(Matrix([[1,0,1],[0,1,1],[1,1,2]])/sqrt(2))"},
{"claim":"Q1c token1 output vector approx (2.406,2.000)", "code":"import math; s=[0.707,0,0.707]; e=[math.exp(x) for x in s]; Z=sum(e); w=[x/Z for x in e]; V=[[2,0],[0,2],[4,4]]; out=[sum(w[i]*V[i][j] for i in range(3)) for j in range(2)]; result = abs(out[0]-2.406)<0.01 and abs(out[1]-2.000)<0.01"},
{"claim":"Q4b attention/FFN ratio n/d equals 8", "code":"n=8192; d=1024; result = (n*n*d)/(n*d*d)==8"},
{"claim":"Q5a QKV param counts equal for A and B", "code":"A=3*512**2; B=8*3*(512*64); result = A==B"}
]