Setting the file. One moment. Train Dpo Example · Huggingface LLM Trainer · huggingface/skills · Skills Docs14.10
Unsloth
(opens in a new tab)
scripts/train_dpo_example.py
Python·106 lines·3 KB
17
18Usage with hf_jobs MCP tool:
19 hf_jobs("uv", {
20 "script": '''<paste this entire file>''',
21 "flavor": "a10g-large",
22 "timeout": "3h",
23 "secrets": {"HF_TOKEN": "$HF_TOKEN"},
24 })
25
26Or submit the script content directly inline without saving to a file.
27"""
28
29import trackio
30from datasets import load_dataset
31from trl import DPOTrainer, DPOConfig
32
33
34# Load preference dataset
35print("📦 Loading dataset...")
36dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")
37print(f"✅ Dataset loaded: {len(dataset)} preference pairs")
38
39# Create train/eval split
40print("🔀 Creating train/eval split...")
41dataset_split = dataset.train_test_split(test_size=0.1, seed=42)
42train_dataset = dataset_split["train"]
43eval_dataset = dataset_split["test"]
44print(f" Train: {len(train_dataset)} pairs")
45print(f" Eval: {len(eval_dataset)} pairs")
46
47# Training configuration
48config = DPOConfig(
49 # CRITICAL: Hub settings
50 output_dir="qwen-dpo-aligned",
51 push_to_hub=True,
52 hub_model_id="username/qwen-dpo-aligned",
53 hub_strategy="every_save",
54
55 # DPO-specific parameters
56 beta=0.1, # KL penalty coefficient (higher = stay closer to reference)
57
58 # Training parameters
59 num_train_epochs=1, # DPO typically needs fewer epochs than SFT
60 per_device_train_batch_size=4,
61 gradient_accumulation_steps=4,
62 learning_rate=5e-7, # DPO uses much lower LR than SFT
63 # max_length=1024, # Default - only set if you need different sequence length
64
65 # Logging & checkpointing
66 logging_steps=10,
67 save_strategy="steps",
68 save_steps=100,
69 save_total_limit=2,
70
71 # Evaluation - IMPORTANT: Only enable if eval_dataset provided
72 eval_strategy="steps",
73 eval_steps=100,
74
75 # Optimization
76 warmup_ratio=0.1,
77 lr_scheduler_type="cosine",
78
79 # Monitoring
80 report_to="trackio", # Integrate with Trackio
81 project="meaningful_project_name", # project name for the training name (trackio)
82 run_name="baseline-run", #Descriptive name for this training run
83
84)
85
86# Initialize and train
87# Note: DPO requires an instruct-tuned model as the base
88print("🎯 Initializing trainer...")
89trainer = DPOTrainer(
90 model="Qwen/Qwen2.5-0.5B-Instruct", # Use instruct model, not base model
91 train_dataset=train_dataset,
92 eval_dataset=eval_dataset, # CRITICAL: Must provide eval_dataset when eval_strategy is enabled
93 args=config,
94)
95
96print("🚀 Starting DPO training...")
97trainer.train()
98
99print("💾 Pushing to Hub...")
100trainer.push_to_hub()
101
102# Finish Trackio tracking
103trackio.finish()
104
105print("✅ Complete! Model at: https://huggingface.co/username/qwen-dpo-aligned")
106print("📊 View metrics at: https://huggingface.co/spaces/username/trackio")