DPO with TRL
Train on preferences.
TRL has a DPO trainer that looks almost exactly like the SFT trainer. Let's use it to make our assistant's replies warmer.
- A DPOTrainer
- Almost like SFTTrainer
- Warmer replies
prefs.py
First, prefs dot p y turns each row into the format DPO expects. A prompt, with the system and user messages. A chosen answer. And a rejected answer. Each answer is a list with one assistant message.
from datasets import load_dataset
SYSTEM = "Write a short reply to the customer."
def to_pair(row):
prompt = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": row["message"]}]
return {"prompt": prompt,
"chosen": [{"role": "assistant", "content": row["chosen"]}],
"rejected": [{"role": "assistant", "content": row["rejected"]}]}
pairs = load_dataset("json", data_files="prefs_train.jsonl")["train"]
pairs = pairs.map(to_pair, remove_columns=["message"])Training with DPO
Here's the training script. It's almost the same as SFT. DPO config adds beta, set to zero point one. And DPO trainer takes our pairs. There's no reference model argument. With LoRA, TRL uses the base model, with the adapter switched off. Run it. The loss falls fast. Reward margin measures how much more the model prefers chosen answers. And accuracy shows it prefers the chosen answer every time.
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import LoraConfig
from trl import DPOTrainer, DPOConfig
from prefs import pairs
NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
model = AutoModelForCausalLM.from_pretrained(NAME)
lora = LoraConfig(r=16, lora_alpha=32, target_modules="all-linear", task_type="CAUSAL_LM")
args = DPOConfig(output_dir="polite-dpo", num_train_epochs=1, learning_rate=3e-4,
per_device_train_batch_size=8, beta=0.1, logging_steps=5,
save_strategy="no", report_to="none")
trainer = DPOTrainer(model=model, args=args, train_dataset=pairs,
processing_class=tok, peft_config=lora)
trainer.train()
for log in trainer.state.log_history[:-1]:
print(f"step {log['step']:2} loss {log['loss']:.3f} "
f"reward margin {log['rewards/margins']:.2f} accuracy {log['rewards/accuracies']:.2f}")
trainer.save_model("polite-dpo")step 5 loss 0.322 reward margin 1.25 accuracy 0.80 step 10 loss 0.022 reward margin 4.16 accuracy 1.00 step 15 loss 0.003 reward margin 5.83 accuracy 1.00 step 20 loss 0.001 reward margin 6.70 accuracy 1.00 step 25 loss 0.001 reward margin 6.97 accuracy 1.00
Also uses prefs.py
from datasets import load_dataset
SYSTEM = "Write a short reply to the customer."
def to_pair(row):
prompt = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": row["message"]}]
return {"prompt": prompt,
"chosen": [{"role": "assistant", "content": row["chosen"]}],
"rejected": [{"role": "assistant", "content": row["rejected"]}]}
pairs = load_dataset("json", data_files="prefs_train.jsonl")["train"]
pairs = pairs.map(to_pair, remove_columns=["message"])Before and after
Now let's compare replies. With the adapter off, we see the original model. With it on, we see the DPO model. Run it. Before, it tells the customer to check the website. That's very like our rejected answers. After, the reply is warmer. In fact, maybe too excited. That's a sign we pushed too far. A larger beta, or fewer steps, would keep it calmer.
import textwrap
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
from prefs import SYSTEM
NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
model = PeftModel.from_pretrained(AutoModelForCausalLM.from_pretrained(NAME), "polite-dpo").eval()
def reply(message):
ids = tok.apply_chat_template([{"role": "system", "content": SYSTEM},
{"role": "user", "content": message}],
add_generation_prompt=True, return_dict=True, return_tensors="pt")
out = model.generate(**ids, max_new_tokens=40, do_sample=False)
return tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)
for message in ["Is Circe in stock?", "My copy of Dune arrived damaged."]:
with model.disable_adapter():
print(textwrap.fill("before: " + reply(message), 86))
print(textwrap.fill("after: " + reply(message), 86), "\n")before: Yes, Circe is currently available in the United States. Please check the current availability on our website for the most up-to-date information. after: We're thrilled to hear that Circe is in stock! We've had a lot of interest from our customers, and we're excited to see you in our store soon. We've had a few before: I'm sorry to hear that your copy of Dune is damaged. I'm here to help you resolve this issue. Please let me know if you have any questions or concerns about the damage to your after: Thank you for sending your copy of Dune. I'm so sorry to hear about the damage. I'm here to help you with any questions or concerns you may have. Please feel free to contact
Also uses _setup.py
import shutil
shutil.copytree('/Users/hussain/Docker Complete Course/shared-data/ft_cache/polite-dpo', 'polite-dpo')Also uses prefs.py
from datasets import load_dataset
SYSTEM = "Write a short reply to the customer."
def to_pair(row):
prompt = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": row["message"]}]
return {"prompt": prompt,
"chosen": [{"role": "assistant", "content": row["chosen"]}],
"rejected": [{"role": "assistant", "content": row["rejected"]}]}
pairs = load_dataset("json", data_files="prefs_train.jsonl")["train"]
pairs = pairs.map(to_pair, remove_columns=["message"])Summary
Let's recap. DPO trainer works like SFT trainer, with pairs, and a beta. With LoRA, the reference model comes for free. Watch reward margin, and accuracy. And check the replies, because you can push too far. Next, other ways to fine-tune efficiently.
Key takeaways- DPOTrainer
- Reward margin
- Don't push too far