Level 5 — MasteryPretraining & Fine-Tuning LLMs

Pretraining & Fine-Tuning LLMs

90 minutes60 marksprintable — key stays hidden on paper

Time limit: 90 minutes Total marks: 60 Instructions: Answer all three questions. Show all derivations. Coding answers may be written in PyTorch-style pseudocode but must be dimensionally correct.


Question 1 — LoRA / QLoRA: memory, math, and correctness (22 marks)

A dense linear layer of a frozen LLM has weight W0Rd×kW_0 \in \mathbb{R}^{d \times k} with d=4096d = 4096, k=4096k = 4096. You apply LoRA replacing the update ΔW\Delta W with ΔW=αrBA\Delta W = \frac{\alpha}{r} B A, where ARr×kA \in \mathbb{R}^{r \times k}, BRd×rB \in \mathbb{R}^{d \times r}, rank r=16r = 16, scaling constant α=32\alpha = 32.

(a) Derive the forward pass h=W0x+ΔWxh = W_0 x + \Delta W\, x and state the initialization of AA and BB that guarantees ΔW=0\Delta W = 0 at step 0. Explain why this initialization matters for training stability. (4 marks)

(b) Compute the number of trainable parameters introduced by LoRA on this one layer, and express it as a percentage of the full-fine-tuning trainable count for the same layer. (4 marks)

(c) The model has L=32L = 32 layers, and LoRA is applied to the query and value projections only (2 matrices per layer, all 4096×40964096\times4096). Compute total trainable LoRA parameters. (3 marks)

(d) QLoRA stores W0W_0 in NF4 (4-bit) while keeping LoRA adapters in bf16 (16-bit). For the entire 7B-parameter frozen backbone, compute the memory (in GB, 1 GB=1091\text{ GB}=10^9 bytes) to store frozen weights in (i) fp16 and (ii) NF4, ignoring quantization constants. State the compression ratio. (4 marks)

(e) Prove that for any target update matrix MRd×kM \in \mathbb{R}^{d\times k}, the LoRA parameterization αrBA\frac{\alpha}{r}BA can represent MM exactly if and only if rank(M)r\operatorname{rank}(M) \le r. (4 marks)

(f) State one reason why QLoRA uses double quantization and what it quantizes. (3 marks)


Question 2 — Pretraining objectives & the text-to-text unification (20 marks)

(a) Write the training loss for (i) GPT-style causal language modeling and (ii) BERT-style masked language modeling, using explicit conditioning notation over a sequence x1:Tx_{1:T}. Clearly indicate which tokens contribute to the loss in each case. (6 marks)

(b) T5 uses a span-corruption objective. Given the input sentence "the cat sat on the mat", show a corrupted input/target pair using sentinel tokens <X>, <Y>, assuming the model corrupts the spans {"cat"} and {"on the"}. (4 marks)

(c) A BERT model uses 15% masking: of masked positions, 80% → [MASK], 10% → random token, 10% → unchanged. Explain mathematically/informally why the 10% "unchanged" and 10% "random" fractions exist — i.e., what train/inference mismatch they mitigate. (4 marks)

(d) Consider a corpus of N=1012N = 10^{12} tokens and a model with P=7×109P = 7 \times 10^9 parameters. Using the Chinchilla-style compute heuristic C6PNC \approx 6 P N (FLOPs), compute the training compute CC. Then, given the compute-optimal Chinchilla ratio of 20\approx 20 tokens per parameter, state whether this model is over- or under-trained relative to compute-optimality, with justification. (6 marks)


Question 3 — Fine-tuning strategy, forgetting, and distillation (18 marks)

(a) Distinguish feature extraction from full fine-tuning in terms of which parameters receive gradients, and give one scenario where feature extraction is preferable. (4 marks)

(b) Knowledge distillation trains a student on the soft targets of a teacher. With teacher logits ztz^t and student logits zsz^s, temperature τ\tau, the distillation loss is the KL divergence between softened distributions. Write the combined loss L=λLKD+(1λ)LCE\mathcal{L} = \lambda \mathcal{L}_{KD} + (1-\lambda)\mathcal{L}_{CE}, define each term, and explain why gradients from the soft-target term are commonly scaled by τ2\tau^2. (6 marks)

(c) Define catastrophic forgetting formally as a change in performance on task A after training on task B. Describe how (i) LoRA and (ii) a small replay/rehearsal set each mitigate it, and why. (5 marks)

(d) For INT8 symmetric quantization of a weight tensor with per-tensor absolute maximum wmax=0.5|w|_{\max} = 0.5, compute the scale factor ss (mapping to the range [127,127][-127, 127]), then quantize and dequantize the value w=0.31w = 0.31. Report the dequantization error. (3 marks)

Answer keyMark scheme & solutions

Question 1

(a) (4 marks) Forward: h=W0x+αrB(Ax)h = W_0 x + \frac{\alpha}{r} B (A x). Compute AxAx first (rr-dim), then B()B(\cdot) — cheaper than forming BABA. (2) Initialization: AN(0,σ2)A \sim \mathcal{N}(0,\sigma^2) (or small random), B=0B = 0. Then BA=0ΔW=0BA = 0 \Rightarrow \Delta W = 0 at step 0. (1) Why: the model starts exactly as the pretrained model, so early training doesn't inject random noise into a well-tuned function; gradients flow gradually. If both were random, initial output would be corrupted. (1)

(b) (4 marks) LoRA params =rk+dr=16(4096)+4096(16)=65536+65536=131072= r\cdot k + d\cdot r = 16(4096) + 4096(16) = 65536 + 65536 = 131072. (2) Full FT params for layer =dk=40962=16,777,216= d\cdot k = 4096^2 = 16{,}777{,}216. (1) Percentage =131072/16777216=0.78125%= 131072/16777216 = 0.78125\%. (1)

(c) (3 marks) Per layer: 2 matrices → 2×131072=2621442 \times 131072 = 262144. (1) Total: 32×262144=8,388,6088.3932 \times 262144 = 8{,}388{,}608 \approx 8.39M trainable params. (2)

(d) (4 marks) (i) fp16: 7×109×27\times10^9 \times 2 bytes =1.4×1010= 1.4\times10^{10} B =14= 14 GB. (1.5) (ii) NF4: 7×109×0.57\times10^9 \times 0.5 bytes =3.5×109= 3.5\times10^{9} B =3.5= 3.5 GB. (1.5) Compression ratio =14/3.5=4×= 14/3.5 = 4\times. (1)

(e) (4 marks) (\Leftarrow) If rank(M)r\operatorname{rank}(M)\le r, by SVD M=UΣVM = U\Sigma V^\top with r\le r nonzero singular values. Set B=rαU:,:rΣ:r,:rB = \frac{r}{\alpha} U_{:, :r}\Sigma_{:r,:r} and A=V:,:rA = V_{:,:r}^\top; then αrBA=UΣV=M\frac{\alpha}{r}BA = U\Sigma V^\top = M. (2) (\Rightarrow) rank(BA)min(rank(B),rank(A))r\operatorname{rank}(BA)\le \min(\operatorname{rank}(B),\operatorname{rank}(A)) \le r since AA has rr rows and BB has rr columns. Scaling by α/r\alpha/r doesn't change rank. So if αrBA=M\frac{\alpha}{r}BA = M then rank(M)r\operatorname{rank}(M)\le r. (2)

(f) (3 marks) Double quantization quantizes the quantization constants (the per-block scale/absmax factors) themselves — a second-level quantization of the metadata. It saves additional memory (~0.4 bits/param) at negligible accuracy cost.


Question 2

(a) (6 marks) (i) Causal LM: LCLM=t=1Tlogpθ(xtx<t)\mathcal{L}_{CLM} = -\sum_{t=1}^{T}\log p_\theta(x_t \mid x_{<t}). Every token contributes; strictly left-context. (3) (ii) Masked LM: let M\mathcal{M} be masked positions. LMLM=tMlogpθ(xtxM)\mathcal{L}_{MLM} = -\sum_{t\in\mathcal{M}}\log p_\theta(x_t \mid x_{\setminus \mathcal{M}}). Only masked tokens contribute; bidirectional context. (3)

(b) (4 marks) Input: the <X> sat <Y> the mat Target: <X> cat <Y> on the <Z> (Sentinels replace corrupted spans in the input; the target lists sentinel+original-span, terminated by final sentinel <Z>.) (4; 2 input, 2 target)

(c) (4 marks) At inference there is no [MASK] token, but if 100% of masked positions were [MASK] during training the model would only learn representations conditioned on seeing [MASK], creating a pretrain/finetune mismatch. (2) Keeping 10% unchanged forces the model to build good representations for real tokens too; 10% random tokens force it not to blindly trust the observed token, encouraging robust context use. (2)

(d) (6 marks) C=6PN=6×7×109×1012=4.2×1022C = 6PN = 6 \times 7\times10^9 \times 10^{12} = 4.2\times10^{22} FLOPs. (3) Compute-optimal tokens 20P=20×7×109=1.4×1011\approx 20P = 20\times7\times10^9 = 1.4\times10^{11}. (1) Actual tokens N=10121.4×1011N = 10^{12} \gg 1.4\times10^{11} (ratio N/P=142.920N/P = 142.9 \gg 20). (1) Therefore the model is over-trained relative to Chinchilla compute-optimality (trained on far more tokens than compute-optimal — common for inference-efficient deployment). (1)


Question 3

(a) (4 marks) Feature extraction: backbone frozen (no gradients to pretrained weights); only a new head is trained. Full fine-tuning: all parameters receive gradients and update. (2) Preferable when: very small target dataset (avoids overfitting), limited compute, or when preserving the general representation / avoiding forgetting is important. (2)

(b) (6 marks) LKD=τ2KL ⁣(softmax(zt/τ)softmax(zs/τ))\mathcal{L}_{KD} = \tau^2 \, \mathrm{KL}\!\left(\mathrm{softmax}(z^t/\tau) \,\|\, \mathrm{softmax}(z^s/\tau)\right), LCE=iyilogsoftmax(zs)i\mathcal{L}_{CE} = -\sum_i y_i\log\mathrm{softmax}(z^s)_i, combined L=λLKD+(1λ)LCE\mathcal{L}=\lambda\mathcal{L}_{KD}+(1-\lambda)\mathcal{L}_{CE}. (3) Definitions: zt,zsz^t,z^s teacher/student logits, τ\tau temperature softening the distributions, yy hard labels. (1) τ2\tau^2 scaling: the gradient of the softened KL term is proportional to 1/τ21/\tau^2 (softmax with z/τz/\tau shrinks logit gradients by τ\tau; the KL derivative brings another 1/τ1/\tau). Multiplying by τ2\tau^2 keeps the KD gradient magnitude comparable to the hard-label CE gradient so their relative weighting stays λ\approx\lambda across temperatures. (2)

(c) (5 marks) Formal: forgetting =PerfA(θinit)PerfA(θafter B)= \mathrm{Perf}_A(\theta_{\text{init}}) - \mathrm{Perf}_A(\theta_{\text{after B}}); positive means degradation on A after training on B. (1) (i) LoRA: freezes original weights W0W_0; task B only edits low-rank adapters. Base capability on A stored in W0W_0 is untouched, so removing/swapping adapters recovers A. (2) (ii) Replay: interleave a small set of task-A examples during B training; gradients keep A's loss low, constraining the update to a region good for both tasks. (2)

(d) (3 marks) Scale s=wmax/127=0.5/127=0.0039370s = |w|_{\max}/127 = 0.5/127 = 0.0039370\ldots (1) Quantize: q=round(0.31/s)=round(0.31/0.0039370)=round(78.74)=79q = \mathrm{round}(0.31/s) = \mathrm{round}(0.31/0.0039370) = \mathrm{round}(78.74) = 79. (1) Dequantize: w^=79×s=79×0.0039370=0.311024\hat w = 79 \times s = 79 \times 0.0039370 = 0.311024; error =0.3110240.31=0.001024= |0.311024 - 0.31| = 0.001024. (1)

[
  {"claim":"LoRA per-layer params r*k+d*r = 131072", "code":"r,d,k=16,4096,4096\nresult=(r*k+d*r==131072)"},
  {"claim":"LoRA fraction of full FT is 0.78125%", "code":"r,d,k=16,4096,4096\nresult=(Rational(r*k+d*r, d*k)*100==Rational(78125,100000))"},
  {"claim":"Total QV LoRA params over 32 layers = 8388608", "code":"r,d,k=16,4096,4096\nper=2*(r*k+d*r)\nresult=(32*per==8388608)"},
  {"claim":"NF4 compression vs fp16 is 4x and C=4.2e22 FLOPs", "code":"fp16=7e9*2\nnf4=7e9*0.5\nC=6*7e9*1e12\nresult=(abs(fp16/nf4-4)<1e-9 and abs(C-4.2e22)<1e15)"},
  {"claim":"INT8 dequant of 0.31 gives error ~0.001024", "code":"s=Rational(1,2)/127\nq=round(float(Rational(31,100)/s))\ndeq=q*s\nerr=abs(float(deq)-0.31)\nresult=(q==79 and abs(err-0.001024)<1e-5)"}
]