|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
""" |
|
|
Production-ready DPO training example for preference learning. |
|
|
|
|
|
DPO (Direct Preference Optimization) trains models on preference pairs |
|
|
(chosen vs rejected responses) without requiring a reward model. |
|
|
|
|
|
Usage with hf_jobs MCP tool: |
|
|
hf_jobs("uv", { |
|
|
"script": '''<paste this entire file>''', |
|
|
"flavor": "a10g-large", |
|
|
"timeout": "3h", |
|
|
"secrets": {"HF_TOKEN": "$HF_TOKEN"}, |
|
|
}) |
|
|
|
|
|
Or submit the script content directly inline without saving to a file. |
|
|
""" |
|
|
|
|
|
import trackio |
|
|
from datasets import load_dataset |
|
|
from trl import DPOTrainer, DPOConfig |
|
|
|
|
|
|
|
|
trackio.init( |
|
|
project="qwen-dpo-alignment", |
|
|
space_id="username/trackio", |
|
|
config={ |
|
|
"model": "Qwen/Qwen2.5-0.5B-Instruct", |
|
|
"dataset": "trl-lib/ultrafeedback_binarized", |
|
|
"method": "DPO", |
|
|
"beta": 0.1, |
|
|
"num_epochs": 1, |
|
|
} |
|
|
) |
|
|
|
|
|
|
|
|
print("π¦ Loading dataset...") |
|
|
dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") |
|
|
print(f"β
Dataset loaded: {len(dataset)} preference pairs") |
|
|
|
|
|
|
|
|
print("π Creating train/eval split...") |
|
|
dataset_split = dataset.train_test_split(test_size=0.1, seed=42) |
|
|
train_dataset = dataset_split["train"] |
|
|
eval_dataset = dataset_split["test"] |
|
|
print(f" Train: {len(train_dataset)} pairs") |
|
|
print(f" Eval: {len(eval_dataset)} pairs") |
|
|
|
|
|
|
|
|
config = DPOConfig( |
|
|
|
|
|
output_dir="qwen-dpo-aligned", |
|
|
push_to_hub=True, |
|
|
hub_model_id="username/qwen-dpo-aligned", |
|
|
hub_strategy="every_save", |
|
|
|
|
|
|
|
|
beta=0.1, |
|
|
|
|
|
|
|
|
num_train_epochs=1, |
|
|
per_device_train_batch_size=4, |
|
|
gradient_accumulation_steps=4, |
|
|
learning_rate=5e-7, |
|
|
|
|
|
|
|
|
logging_steps=10, |
|
|
save_strategy="steps", |
|
|
save_steps=100, |
|
|
save_total_limit=2, |
|
|
|
|
|
|
|
|
eval_strategy="steps", |
|
|
eval_steps=100, |
|
|
|
|
|
|
|
|
warmup_ratio=0.1, |
|
|
lr_scheduler_type="cosine", |
|
|
|
|
|
|
|
|
report_to="trackio", |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
print("π― Initializing trainer...") |
|
|
trainer = DPOTrainer( |
|
|
model="Qwen/Qwen2.5-0.5B-Instruct", |
|
|
train_dataset=train_dataset, |
|
|
eval_dataset=eval_dataset, |
|
|
args=config, |
|
|
) |
|
|
|
|
|
print("π Starting DPO training...") |
|
|
trainer.train() |
|
|
|
|
|
print("πΎ Pushing to Hub...") |
|
|
trainer.push_to_hub() |
|
|
|
|
|
|
|
|
trackio.finish() |
|
|
|
|
|
print("β
Complete! Model at: https://huggingface.co/username/qwen-dpo-aligned") |
|
|
print("π View metrics at: https://huggingface.co/spaces/username/trackio") |
|
|
|