본문 바로가기
C.W.K.
Stream
Lesson 07 of 08 · published

TRL: RLHF, DPO, Preference Optimization

~24 min · ops, trl, rlhf

Level 0스카우트
0 XP0/50 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

TRL은 선호 정렬을 위한 학습 도구를 모아 둬

trl은 SFT, DPO, PPO, KTO, IPO, ORPO, GRPO 같은 선호·강화학습 방식을 제공해. 2026년의 흔한 출발점은 별도 보상 모델과 PPO 루프 없이 선호 쌍을 직접 학습하는 DPO야.

DPO는 선택된 답과 거절된 답의 간격을 벌려

데이터 한 행은 (prompt, chosen, rejected)를 가져. DPO는 closed-form 목적함수로 같은 prompt에서 chosen의 확률을 rejected보다 높여. 구현 흐름은 손실 함수가 다른 SFT와 비슷하고 별도 보상 모델이 없어 비교적 단순하지만, 선호 데이터의 일관성과 기준이 곧 학습 품질이야.

Code

preference 데이터셋의 trl DPO·python
# pip install trl
from trl import DPOTrainer, DPOConfig
from transformers import AutoModelForCausalLM, AutoTokenizer
from datasets import load_dataset
import torch

base = "Qwen/Qwen2.5-1.5B-Instruct"
tok = AutoTokenizer.from_pretrained(base)
model = AutoModelForCausalLM.from_pretrained(base, torch_dtype=torch.bfloat16)

# Reference 모델 (frozen) — DPO 가 학습 모델 logprob 을 이 baseline 과 비교
ref = AutoModelForCausalLM.from_pretrained(base, torch_dtype=torch.bfloat16)

# Preference 데이터셋: 각 행이 'prompt', 'chosen', 'rejected' 가짐
ds = load_dataset("trl-lib/ultrafeedback_binarized", split="train")

cfg = DPOConfig(
    output_dir="./dpo-out",
    per_device_train_batch_size=2,
    num_train_epochs=1,
    learning_rate=5e-7,           # DPO lr 낮음 (종종 1e-6 to 5e-7)
    bf16=True,
    beta=0.1,                     # KL strength
)

trainer = DPOTrainer(model=model, ref_model=ref, args=cfg, tokenizer=tok, train_dataset=ds)
trainer.train()

External links

Exercise

training 트랙의 SFT-tuned 모델. 작은 preference 데이터셋 (예: trl-lib/ultrafeedback_binarized, 200 example) 에 DPO-tune. held-out 10 프롬프트 비교: SFT-only 출력 vs SFT+DPO 출력. 어떤 axis 변하는지 (helpfulness, conciseness, refusal style) 메모.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.