Alignment, Prompting & RAG
Level 3 (Production): Derivations, Code-from-Memory & Explain-Out-Loud
Time limit: 45 minutes Total marks: 60
Answer all questions. Show all derivation steps. Code may be pseudo-Python but must be runnable-quality.
Q1. Derive the DPO objective from the RLHF/Bradley-Terry setup. (12 marks)
Starting from the KL-regularized RLHF objective
(a) Show that the optimal policy has the closed form . (4) (b) Invert this to express the reward in terms of , and . (2) (c) Substitute into the Bradley-Terry preference model and show the partition function cancels. (3) (d) Write the final DPO loss over a dataset of triples. (3)
Q2. PPO clipped surrogate — explain out loud + compute. (10 marks)
(a) Write the PPO clipped surrogate objective with probability ratio and advantage , and explain in 2–3 sentences why the clip prevents destructive updates. (5) (b) Given , , : compute the per-token surrogate value . (2) (c) Repeat for , , . State in one line whether the gradient contributes for each case. (3)
Q3. Reward model loss — from memory. (8 marks)
(a) Write the pairwise ranking loss used to train a reward model from human preference pairs . (3) (b) A batch has three pairs with reward-margins equal to , , and . Compute the mean loss (use natural log). (3) (c) Explain why reward models are typically initialized from the SFT model and use a scalar head. (2)
Q4. Self-consistency vs single-sample CoT — derive the win. (10 marks)
Suppose a model produces the correct final answer on any single chain-of-thought sample with probability , and wrong answers are spread so no single wrong answer beats the correct one under majority vote.
(a) For independent samples, write the probability that the majority vote is correct (majority = at least 3 correct). (4) (b) Compute this probability numerically. (3) (c) Explain the assumption that most fails, in practice, that can make self-consistency underperform this idealized number. (3)
Q5. Build a minimal RAG pipeline from memory. (12 marks)
Write clean pseudo-Python for a RAG query function that: (a) embeds the query, (b) does cosine-similarity retrieval of top- chunks from a vector store, (c) reranks with a hybrid score , (d) builds a grounded prompt, (e) calls the LLM. (8) Then in 4 bullet points explain two chunking strategy trade-offs and two hallucination-mitigation techniques your pipeline enables. (4)
Q6. Cosine similarity & normalization. (8 marks)
Given query embedding and two chunk embeddings , . (a) Compute cosine similarity of with each and state which is retrieved as top-1. (5) (b) If embeddings are L2-normalized at index time, explain why inner-product search then equals cosine search, and why this speeds up ANN retrieval. (3)
Answer keyMark scheme & solutions
Q1 — DPO Derivation (12)
(a) (4) Rewrite objective per-prompt as minimizing This equals with . (2 marks) KL is minimized (=0) when , giving (2 marks)
(b) (2) Take logs and rearrange:
(c) (3) In BT, only the difference matters: The term is identical in both and cancels (1 mark for identifying cancellation; 2 for correct difference).
(d) (3) Replacing with the trainable :
Q2 — PPO Clip (10)
(a) (5) , where . (3) Why: the clip caps how far the new policy can move from the old one in a single update; taking the min makes the bound pessimistic so the objective never rewards moving outside the trust region — preventing large, destabilizing policy jumps. (2)
(b) (2) ; clipped ratio , ; .
(c) (3) ; clipped ratio , ; . (2) Case (b): clip is active, ratio was above with positive ⇒ gradient zero (no further push). Case (c): the (unclipped, larger magnitude) is selected ⇒ gradient nonzero, pushing probability down. (1)
Q3 — Reward Model (8)
(a) (3)
(b) (3) Loss per pair :
- :
- :
- :
Mean .
(c) (2) Init from SFT: shares language understanding, so preference signal only needs to fit a ranking head — cheaper and more stable. Scalar head: BT model needs a single real-valued score per response to compute margins.
Q4 — Self-Consistency (10)
(a) (4) Majority correct , .
(b) (3)
- :
- :
- :
Sum (≈0.593), higher than single-sample . ✓
(c) (3) The assumption of independence of samples fails: chains sampled from the same model are correlated (shared biases/failure modes), and wrong answers can cluster on a single plausible-but-wrong value that beats the correct answer under majority vote — collapsing the gain or reversing it.
Q5 — RAG Pipeline (12)
(a) (8) Reference solution:
def rag_query(query, store, llm, embed, bm25, k=20, alpha=0.6):
q_vec = embed(query) # (a) embed
# (b) dense retrieval by cosine
cand = store.search(q_vec, top_k=k, metric="cosine")
# (c) hybrid rerank
for c in cand:
s_dense = cosine(q_vec, c.vec)
s_bm25 = bm25.score(query, c.text)
c.score = alpha*s_dense + (1-alpha)*normalize(s_bm25)
top = sorted(cand, key=lambda c: c.score, reverse=True)[:5]
# (d) grounded prompt
ctx = "\n\n".join(f"[{i}] {c.text}" for i, c in enumerate(top))
prompt = (f"Answer ONLY from context. Cite [i]. "
f"If not present, say 'not in context'.\n\n"
f"Context:\n{ctx}\n\nQ: {query}\nA:")
return llm(prompt) # (e) call LLMMarks: embed(1), retrieval(2), hybrid rerank(2), grounded/cited prompt(2), LLM call(1).
(b) (4) — 1 mark each:
- Chunk size trade-off: large chunks preserve context but dilute embeddings & waste context window; small chunks are precise but fragment meaning across boundaries.
- Overlap trade-off: sliding-window overlap avoids splitting an answer across chunks but inflates index size and causes duplicate retrievals.
- Hallucination mitigation: grounding instruction + "say 'not in context'" abstention reduces fabrication.
- Hallucination mitigation: inline citation
[i]forces attribution, enabling faithfulness checks / self-verification.
Q6 — Cosine (8)
(a) (5) , .
- : dot , , cos .
- : dot , , cos .
Top-1 retrieved: . (dot each 1, norms 1, values 2, decision 1)
(b) (3) After L2 normalization , so ·(const) — inner product equals cosine up to the fixed which is monotone-invariant for ranking. ANN indexes (IVF/HNSW) use raw inner-product/L2 distance kernels that are cheaper than dividing by norms per comparison, so pre-normalizing lets the fast IP search return exact cosine order.
[
{"claim":"Q2b clipped surrogate = 2.4","code":"rt=Rational(14,10);At=2;eps=Rational(2,10);val=Min(rt*At, Max(1-eps,Min(rt,1+eps))*At);result=(val==Rational(24,10))"},
{"claim":"Q2c clipped surrogate = -2.4","code":"rt=Rational(5,10);At=-3;eps=Rational(2,10);val=Min(rt*At, Max(1-eps,Min(rt,1+eps))*At);result=(val==Rational(-24,10))"},
{"claim":"Q3b mean reward-model loss approx 0.7111","code":"import sympy as sp;f=lambda m:-sp.log(1/(1+sp.exp(-m)));mean=(f(2)+f(0)+f(-1))/3;result=abs(float(mean)-0.7111)<1e-3"},
{"claim":"Q4b self-consistency prob approx 0.5931","code":"p=Rational(55,100);from sympy import binomial;s=sum(binomial(5,k)*p**k*(1-p)**(5-k) for k in range(3,6));result=abs(float(s)-0.5931)<1e-3"},
{"claim":"Q6a cosine c2 > c1 so c2 top1","code":"import sympy as sp;q=sp.Matrix([1,2,2]);c1=sp.Matrix([2,0,1]);c2=sp.Matrix([0,3,4]);cos1=q.dot(c1)/(q.norm()*c1.norm());cos2=q.dot(c2)/(q.norm()*c2.norm());result=(cos2>cos1)"}
]