From Raw Text to Aligned Assistant: Building and Testing an LLM
Machine LearningModel answerLast updated
Walk through how a foundation model becomes a safe, helpful assistant: pretraining, SFT versus preference optimization, reward modeling pitfalls, and evaluation including reward hacking detection.
Question
You are on a team that will build a new large language model, starting from a blank slate and ending with a deployed chat assistant. Describe the technical path and justify why each stage is needed.
Cover these four areas:
- Pretraining. What loss is optimized, and how do you weigh the quality of the training data against its sheer volume?
- Alignment after pretraining. Compare supervised fine-tuning (SFT) on demonstrations with reinforcement learning from human feedback (RLHF). Suppose an SFT model already scores well on accuracy-style metrics. Why might you still need a preference-based stage?
- Preference learning. Whether you pick PPO with a separate reward model or DPO with a direct preference loss, what are the main difficulties in getting the reward signal or preference objective to work well?
- Evaluation. Propose an evaluation setup that covers both factual reliability and safety. Explain how you would notice that the policy is exploiting the reward signal (reward hacking).
A strong answer links the objectives of each stage, names concrete failure modes, and states trade-offs rather than only listing terminology.
Hints
Hint 1
Start from the objectives: next-token cross-entropy, then token-level imitation, then sequence-level preference optimization with a KL anchor to a reference model.
Hint 2
For the SFT versus RLHF question, think about exposure bias, the lack of negative examples in demonstrations, and the fact that judging two answers is easier than writing a perfect one.
Hint 3
For reward modeling and hacking, think about spurious features such as length and flattery, distribution shift as the policy moves, and what happens to a true quality measure as KL from the reference grows.
Hint 4
For evaluation, report paired metrics (harmful compliance with over-refusal, accuracy with abstention) and compare the proxy reward to an independent gold signal.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
Each stage fixes a limitation of the previous one. Pretraining gives broad capability, SFT gives the right format and behavior, preference optimization shapes what people actually favor, and evaluation checks that the optimization did not quietly break something.
1. Pretraining
Objective. Autoregressive maximum likelihood, i.e. cross-entropy on the next token:
$$\mathcal{L}(\theta) = -\sum_t \log p_\theta(x_t \mid x_{<t})$$
Minimizing it is equivalent to minimizing the KL divergence from the data distribution to the model. Track it as perplexity, exp(loss). Syntax, facts and some reasoning emerge because predicting text well requires compressing the world that produced it.
Quality versus quantity.
- Scaling-law results (Chinchilla) suggest about 20 tokens per parameter for compute-optimal training. Production models often train well beyond that, since a smaller, longer-trained model is cheaper to serve.
- Quality multiplies the value of quantity. Deduplication, language ID, boilerplate removal, classifier-based quality filters and deliberate domain mixing (code, math, multilingual) often let a smaller clean corpus match a larger noisy one.
- Repeating data helps only a few epochs (roughly up to 4), so the real constraint is unique high-quality tokens.
- Decontaminate against benchmarks (n-gram overlap), otherwise evaluation numbers are inflated.
2. SFT versus RLHF
| SFT | RLHF | |
|---|---|---|
| Signal | Demonstrations | Pairwise comparisons |
| Loss | Token-level cross-entropy | Sequence-level reward with KL penalty |
| Teaches | Format, instruction following, tone | What people prefer, including appropriate refusals |
| Data source | Human-written text (teacher forcing) | The model's own samples (on-policy) |
Why a preference stage is still needed:
- Token match is not answer quality. SFT cannot express that one complete answer is better than another plausible one.
- Exposure bias. SFT conditions on gold prefixes; at inference the model conditions on its own output and errors compound. On-policy training sees the real distribution.
- Comparing is easier than writing. Raters can rank answers they could not author, so the model can exceed demonstrator quality.
- Negative signal. Demonstrations only say what to do. Rejected responses say what to avoid, which matters for harmfulness and hallucination.
- Calibrated uncertainty. Imitating confident human answers teaches confident tone even when the model lacks knowledge. Preferences can reward "I don't know."
Alignment tax. Raters tend to prefer fluent, confident, long answers, so optimization can trade truthfulness or benchmark skill for approval. Mitigations: KL penalty to the reference, mixing in pretraining gradients, and a factuality-specific reward component.
3. Reward modeling and preference objectives
PPO path. Train a scalar reward model with a Bradley-Terry loss:
$$\mathcal{L}_{RM} = -\log\sigma\big(r(x,y_w) - r(x,y_l)\big)$$
then maximize $\mathbb{E}[r] - \beta,\mathrm{KL}(\pi|\pi_{ref})$.
DPO path. Use the closed-form optimum of that same objective and train directly on pairs:
$$\mathcal{L}{DPO} = -\log\sigma\Big(\beta\log\tfrac{\pi(y_w|x)}{\pi{ref}(y_w|x)} - \beta\log\tfrac{\pi(y_l|x)}{\pi_{ref}(y_l|x)}\Big)$$
Main challenges.
- Noisy, plural preferences. Annotator agreement is often 60-75%, while Bradley-Terry assumes one consistent preference.
- Spurious features. Reward models latch onto length, markdown, hedging, flattery and agreeing with the user. Check the correlation between reward and length.
- Distribution shift. The reward model was fit on earlier samples; as the policy moves, it is queried off-distribution. Remedies: iterative data collection, reward-model ensembles, uncertainty penalties.
- Over-optimization (Goodhart). True quality typically rises, then falls as KL from the reference increases. Tune β and stop early.
- Scale and credit assignment. Rewards are shift-invariant, so normalize them; a single sequence-level reward gives high-variance per-token credit.
- DPO specifics. It is offline (no exploration) and sensitive to the gap between the preference data and the reference policy. It can reduce the likelihood of both chosen and rejected responses, overfits when labels are near-deterministic, and still inherits length bias. Options: IPO, length-normalized DPO, iterative or online DPO.
4. Evaluation design
Use held-out, decontaminated, versioned sets, and compare each checkpoint against the base and SFT models.
- Capability regression: knowledge (MMLU-style), math (GSM8K/MATH), code (HumanEval), multilingual, long-context retrieval.
- Factual grounding:
- Closed-book QA with calibration (ECE, accuracy against abstention rate).
- For retrieval-augmented use, faithfulness: decompose answers into claims and verify each against the context (NLI or FActScore-style), plus citation precision and recall.
- Probes for imitative falsehoods (TruthfulQA-style).
- Safety: attack success rate under red-teaming and jailbreaks, paired with over-refusal rate on benign edgy prompts; toxicity, bias across slices, PII leakage.
- Helpfulness: pairwise win rate against a baseline, from humans and calibrated LLM judges, with position swapping and length control. Periodically re-validate the judge against humans.
Detecting reward hacking
- Proxy-gold divergence (the definitive signal). Reward-model score keeps climbing while an independent gold measure (fresh human ratings, a stronger or held-out judge, a second reward model) flattens or drops.
- KL trajectory. Reward rising together with fast KL growth is a warning.
- Feature drift. Monitor response length, list and markdown density, hedge phrases, refusal rate and sycophancy markers.
- Qualitative audits. Read the highest-reward samples regularly; exploits are often visible by eye.
- Adversarial probes. Test prompts where the true answer is "I don't know" or where the user is wrong.
Responses: early stopping at the gold-metric peak, larger β, ensembles or uncertainty penalties, length-controlled rewards, refreshing preference data with the current policy's outputs.
Common mistakes
- Treating RLHF as just "more SFT" and missing the on-policy and negative-signal points.
- Reporting safety as a single refusal rate, which rewards over-refusal.
- Evaluating the policy only with the reward model it was optimized against.
- Ignoring benchmark contamination.
- Describing DPO as free of reward-hacking-like issues; it can still exploit length and dataset artifacts.