Instruction Tuning and RLHF
Instruction tuning and preference tuning are the training stages that turn a pretrained base model, which only continues text, into an assistant that answers questions, follows instructions and declines harmful requests. Together they are often called post-training. RLHF (reinforcement learning from human feedback) is the best-known preference tuning method, and DPO (direct preference optimization) is a simpler method that is now widely used.
The Stages After Pretraining
| Stage | Description |
|---|---|
| Supervised fine-tuning (SFT) | It is used to teach the assistant format: training continues on example conversations of prompts and good answers |
| Preference data | For one prompt, two answers, and a label saying which one people (or a strong model) preferred |
| RLHF | It is used to train a reward model on the preferences, then improve the assistant with reinforcement learning to earn higher rewards |
| DPO | It is used to learn from the preference pairs directly, with no separate reward model |
| Safety training | Examples and preferences that teach the model to refuse harmful requests and admit uncertainty |
SmolLM2-135M-Instruct, used in this lesson, was made from the base model with SFT on public and curated conversation datasets, then DPO on the UltraFeedback preference dataset, according to its model card.
Example: Base Model vs Instruct Model
The programs in this chapter need pip install torch transformers. They use SmolLM2-135M, a small open language model from Hugging Face (Apache 2.0 license, about 270 MB), which runs on an ordinary laptop. The first run downloads it; the download and loading messages are left out of the output shown. This lesson also uses SmolLM2-135M-Instruct, the same size after post-training.
from transformers import AutoModelForCausalLM, AutoTokenizer
question = "Give me three tips for studying for a math exam."
# The instruct model expects a chat template: special tokens mark who is speaking
chat = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct")
prompt = chat.apply_chat_template([{"role": "user", "content": question}], tokenize=False, add_generation_prompt=True)
print("What the instruct model really reads:")
print(prompt)
for name in ["HuggingFaceTB/SmolLM2-135M", "HuggingFaceTB/SmolLM2-135M-Instruct"]:
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name)
text = prompt if name.endswith("Instruct") else question # the base model just continues text
ids = tokenizer(text, return_tensors="pt").input_ids
out = model.generate(ids, max_new_tokens=70, do_sample=False, pad_token_id=tokenizer.eos_token_id)
reply = tokenizer.decode(out[0, ids.shape[1]:], skip_special_tokens=True).strip()
print(f"=== {name.split('/')[1]} ===")
print(reply, "\n")What the instruct model really reads:
<|im_start|>system
You are a helpful AI assistant named SmolLM, trained by Hugging Face<|im_end|>
<|im_start|>user
Give me three tips for studying for a math exam.<|im_end|>
<|im_start|>assistant
=== SmolLM2-135M ===
The first tip is to study for a math exam in a quiet place. If you are studying in a noisy environment, you will be distracted and will not be able to concentrate on the exam.
The second tip is to study for a math exam in a quiet place. If you are studying in a noisy environment, you will be
=== SmolLM2-135M-Instruct ===
Here are three tips for studying for a math exam:
1. **Study Regularly:** The more you study, the better you'll perform. Try to study for at least 30 minutes a day, 5 days a week. This will help you build a strong foundation in math concepts.
2. **Use a Study Schedule:** TryExplanation:
- The chat template wraps each message in special tokens:
<|im_start|>and the speaker's role (system,userorassistant), then the text, then<|im_end|>. It ends with<|im_start|>assistant, which tells the model it's its turn. The instruct model was trained on conversations in exactly this format, and the template adds a default system message. - The base model continues the text like a web page: "The first tip is..." Then its second tip repeats the first. It has knowledge, but nothing taught it to give a clear, varied answer and stop.
- The instruct model answers like an assistant: "Here are three tips", a numbered list, bold headings. It has the same number of parameters; only post-training changed.
- Both replies stop at 70 new tokens (
max_new_tokens=70), which is why they end mid-sentence.
Example: Measuring Preferences
DPO trains on preference pairs: a prompt, a preferred answer and a rejected one. It pushes up the probability of the preferred answer and pushes down the rejected one, measured against the original model so the new model doesn't drift too far. This program measures how far the instruct model has moved on three new pairs.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
# Preference data: for each prompt, an answer people preferred and one they rejected
pairs = [
("Can I share my password with a classmate?",
"It's best not to. Keep your password private, and if you think someone knows it, change it.",
"Sure, sharing passwords with friends is fine."),
("What is 12 times 12?",
"12 times 12 is 144.",
"12 times 12 is 124."),
("Write one sentence inviting parents to the science fair.",
"Please join us at the science fair on Friday at 10 in the school library!",
"Science fair. Friday."),
]
tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct")
models = {name: AutoModelForCausalLM.from_pretrained(f"HuggingFaceTB/SmolLM2-135M{name}").eval()
for name in ["", "-Instruct"]}
def answer_logprob(model, question, answer):
"""Total log probability the model gives to the answer's tokens, after the question."""
prompt = tokenizer.apply_chat_template([{"role": "user", "content": question}], tokenize=False,
add_generation_prompt=True)
start = len(tokenizer(prompt).input_ids)
ids = tokenizer(prompt + answer, return_tensors="pt").input_ids
with torch.no_grad():
logp = model(ids).logits[0, :-1].float().log_softmax(dim=-1)
targets = ids[0, 1:]
return logp[range(len(targets)), targets][start - 1:].sum().item()
for question, chosen, rejected in pairs:
print(question)
gains = {}
for label, answer in [("preferred", chosen), ("rejected", rejected)]:
base = answer_logprob(models[""], question, answer)
tuned = answer_logprob(models["-Instruct"], question, answer)
gains[label] = tuned - base
print(f" {label:9} base {base:7.2f} instruct {tuned:7.2f} change {tuned - base:+6.2f}")
print(f" preference margin (DPO's measure): {gains['preferred'] - gains['rejected']:+.2f}\n")Can I share my password with a classmate?
preferred base -56.86 instruct -51.48 change +5.38
rejected base -28.69 instruct -26.92 change +1.77
preference margin (DPO's measure): +3.61
What is 12 times 12?
preferred base -12.86 instruct -3.24 change +9.63
rejected base -15.35 instruct -8.58 change +6.76
preference margin (DPO's measure): +2.86
Write one sentence inviting parents to the science fair.
preferred base -48.07 instruct -38.75 change +9.33
rejected base -28.66 instruct -25.79 change +2.87
preference margin (DPO's measure): +6.45Explanation:
answer_logprobadds up the log probabilities of the answer's tokens, given the question in the chat template. Closer to 0 means more likely. Longer answers always have lower totals, which is why the numbers are compared as changes, not directly.- "change" is how much more likely the instruct model finds an answer than the base model did. Post-training raised every answer a little, because they are all in assistant format.
- The preference margin is the change for the preferred answer minus the change for the rejected one, the quantity DPO pushes up. It is positive for all three pairs: +3.61 for the safe password answer, +2.86 for the correct product (144, not 124) and +6.45 for the polite invitation.
- These pairs were written for this lesson and were not in its training data, so the positive margins show the tuning generalized. They don't show the model is always right: a small model still makes mistakes.
RLHF and DPO Compared
| RLHF | DPO | |
|---|---|---|
| What it learns from | Preference pairs, through a separate reward model | Preference pairs, directly |
| Training steps | Train a reward model, then reinforcement learning (often PPO) | One supervised-style training stage |
| Strengths | Flexible; the reward model can score new answers during training | Simpler, cheaper and more stable |
| Used for | Early ChatGPT and many frontier models | Many open models, including SmolLM2-Instruct |
Newer methods also use AI feedback instead of only human ratings, guided by written principles, and reinforcement learning on checkable tasks such as math and code, where the answer can be verified automatically.
Common Mistakes
Prompting an instruct model without its chat template. The model was trained on the template; plain text gives worse answers. Use apply_chat_template.
Expecting a base model to follow instructions. It continues text; give it the start of the text you want instead of a question.
Thinking alignment is finished. Post-training reduces harmful and unhelpful answers but doesn't eliminate them.
Comparing total log probabilities of answers of different lengths. Longer answers always score lower; compare changes or per-token averages.
Interview Corner
What are the stages of training a chat assistant?
Pretraining on next-token prediction, supervised fine-tuning on example conversations, then preference tuning with RLHF or DPO. Safety training is usually part of the last two stages.
What is the difference between RLHF and DPO?
RLHF trains a reward model on human preferences and then optimizes the policy with reinforcement learning; DPO optimizes directly on the preference pairs with a simple loss, with no reward model. Both keep the model close to a reference model so it doesn't drift.
Practice
Exercise: your own preference pair. Add a pair to the second program, such as a question about homework with a helpful answer and an answer that just gives the result with no explanation. Is the margin positive? Try a pair where you are unsure which answer is better.
Check your understanding:
- What did the base model do with the study-tips question, and why?
- What do the
<|im_start|>and<|im_end|>tokens do? - Why are the answers compared by their change from the base model rather than their totals?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Format a chat | tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) |
| A message | {"role": "user", "content": "..."} |
| Generate greedily | model.generate(ids, max_new_tokens=70, do_sample=False) |
| Only the new text | tokenizer.decode(out[0, ids.shape[1]:], skip_special_tokens=True) |
| Log probability of tokens | logits[0, :-1].log_softmax(-1)[range(n), ids[0, 1:]] |
Was this tutorial helpful?