Aligning language models with human preferences
In the last four posts we built the pieces of a language model from the ground up: tokenizers, a causal transformer, adapters, and a held-out evaluation loop that tells us whether any of it works. What we have never done is teach the model to prefer one answer over another. That is the job of alignment, and it is the through-line of this post. Alignment is the process of making a model's outputs match human preferences, and it is a tug-of-war between what a model can say and what people actually want to hear. The two trained models below, the reward model and DPO, have to beat a cheap confound before we believe them. We will build the whole stack on a laptop CPU, from a reward model that reaches 0.567 held-out pairwise accuracy to a DPO run whose implicit reward margin barely moves, and the gaps between those numbers are the story.
We work with the Anthropic HH-RLHF dataset, roughly 170,000 human preference pairs where each row holds a chosen and a rejected assistant turn. We slice 4,000 pairs with seed 42 and cache them as parquet, which keeps the entire run under half an hour on CPU. The notebook trains a reward model and a DPO policy on a few hundred pairs each, and the point is not to produce a great model. The point is to see the machinery move and to read the numbers honestly.
What better looks like
Before any model, we look at the data. The slice has two text columns, no numeric fields, no missing values, and no empty strings after stripping. The label is simply which response a human preferred, so the first question is whether a dumb heuristic already predicts it. We compute the length difference between chosen and rejected and find that the chosen response is longer in only 0.421 of pairs. That is the confound we have to beat, and it is a strange one: the obvious guess, longer is better, is wrong more often than it is right on this slice.
Figure 1 plots the chosen minus rejected character count for every pair, centered on zero. Most pairs sit near zero length difference, so length is a weak preference signal.

The histogram sits nearly symmetric around zero, which tells us length carries almost no preference signal here. A model that only counts characters would score near the base rate, and anything above that is real signal. We also check duplicates and find none in the pair columns, though seven human prompts are reused across pairs, so we drop duplicates to keep the train and eval split honestly disjoint.
The token counts have a long right tail, with a median of 123 tokens and a p90 (the 90th percentile) of 324 on the chosen transcripts. That is why we cut training sequences at 96 tokens and left-truncate so the assistant turn survives. The word frequency curve is roughly Zipf-like (a few words appear very often, while most appear rarely) with a heavy head, and the tokenizer reports zero unknown tokens across 7,789 subword ids, so the risk is fragmentation, not missing words.
Figure 2 plots the token count per chosen transcript with the 96-token training cut marked. Most chosen transcripts sit under the 96-token cut, with a long right tail.

The cut at 96 tokens keeps most pairs usable while making every CPU step cheap. That single budget decision shapes everything that follows.
The alignment stack
The 96-token budget forces the first alignment choice: which tokens get supervised. Instruction tuning teaches format, and the way we get there is to mask the prompt and train on the response only, so the model learns to answer rather than to continue. Reward models score a single response with a scalar, trained on pairs with the Bradley-Terry loss, where the probability that the preferred response $y_w$ beats the rejected one $y_l$ is $\sigma(r(y_w) - r(y_l))$. RLHF optimizes the policy against that reward with a KL leash to a frozen reference. PPO is the classic optimizer for that loop, and DPO is the shortcut that fits the same objective directly on the pairs. We will take each of those in turn.
The tokenizer step that makes instruction tuning work is the label mask. We split each transcript at the last Assistant: turn, keep the tail so the response survives truncation, and set the prompt tokens to -100 so the cross-entropy loss ignores them.
def tokenize_example(text, max_len=MAX_LEN):
prompt, response = split_turn(text)
prefix = '### Instruction:\n' + prompt.strip() + '\n\n### Response:\n'
ids_prefix = tokenizer(prefix, add_special_tokens=False)['input_ids']
ids_resp = tokenizer(response.strip() + tokenizer.eos_token, add_special_tokens=False)['input_ids']
ids = (ids_prefix + ids_resp)[-max_len:] # keep the tail so the response survives truncation
n_prefix = max(len(ids) - len(ids_resp), 0)
labels = [-100] * n_prefix + ids[n_prefix:] # -100 is ignored by the cross entropy loss
return ids, labels
On the first example the whole 96-token window ends up supervised, because the response fills the tail after truncation. That is fine for a short conversational turn, but it is the first place a production pipeline would differ: it would keep the prompt visible and supervise only the reply.
The reward model is a DistilGPT-2 sequence classifier with a LoRA adapter on the attention projections and a fresh scalar head. The adapter trains 148,224 of 82,061,568 parameters, 0.181 percent of the model. Before training it scores 0.467 pairwise accuracy on the held-out set, near the 0.500 chance line, while the length heuristic sits at 0.35. Pairwise accuracy is the fraction of held-out pairs where the preferred response scores higher than the rejected one. 0.500 is chance. After 80 paired steps of the Bradley-Terry loss, in 2.2 seconds, the loss drops from 0.8065 to 0.7353 and held-out accuracy reaches 0.567.