본문으로 건너뛰기
Skillpedia
머신러닝11k · #11783

trl-training

하는 일

이 스킬은 AI가 언어 모델의 첫 학습 후에 그것을 개선하는 학습 코드를 작성하고 고치도록 돕습니다. TRL로 모델을 파인튜닝하거나 정렬하려는 개발자를 위한 스킬입니다.

사용하는 경우

  • ✓SFT로 언어 모델을 파인튜닝하거나 선호 데이터로 정렬하고 싶을 때.
  • ✓Python이나 명령줄에서 TRL 학습 코드를 작성하거나 디버그하고 싶을 때.
  • ✓GRPO처럼 보상 함수를 쓰는 강화 학습이 필요할 때.

스킬 링크

https://github.com/huggingface/skills/blob/main/skills/trl-training/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/huggingface/skills/blob/main/skills/trl-training/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“작은 Qwen 모델을 위해 제가 고른 답변 쌍으로 DPO 학습 스크립트를 TRL로 작성해 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

AI는 방법과 데이터셋 유형에 맞는 학습기와 설정을 고릅니다. 그다음 표준 TRL 클래스와 옵션을 써서 Python 코드나 명령을 작성하거나 고칩니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

TRL

Each method pairs a *Trainer class with a *Config dataclass. Configs extend transformers.TrainingArguments, so all of its arguments work in any trainer config.

Trainer Dataset type
SFTTrainer language modeling or prompt-completion
DPOTrainer preference (chosen/rejected pairs)
GRPOTrainer prompt-only + reward function(s)
DistillationTrainer prompt-only + a teacher model (on-policy distillation)
KTOTrainer unpaired preference (per-sample bool label)
RewardTrainer preference (chosen/rejected pairs); trains a scalar reward model, not a policy

Many more trainers (OnlineDPO, ORPO, CPO, GKD, …) live in trl.experimental with unstable APIs: https://huggingface.co/docs/trl/experimental_overview

from datasets import load_dataset
from trl import SFTConfig, SFTTrainer

trainer = SFTTrainer(
    model="Qwen/Qwen2.5-0.5B",  # model ID or a PreTrainedModel instance
    args=SFTConfig(output_dir="Qwen2.5-0.5B-SFT"),
    train_dataset=load_dataset("trl-lib/Capybara", split="train"),
)
trainer.train()

Pass model as a string and route loading kwargs through model_init_kwargs (e.g. {"dtype": "bfloat16", "attn_implementation": "kernels-community/flash-attn2"}) instead of calling from_pretrained yourself. The tokenizer/processor is inferred from the model; pass processing_class only when it differs. For LoRA, pass peft_config=LoraConfig(...).

Dataset formats

Conversational: {"messages": [{"role": ..., "content": ...}]} (language modeling) or {"prompt": [...], "completion": [...]}. The chat template is applied automatically — never apply it yourself. Extra columns are allowed; GRPO forwards them to reward functions. Reference: https://huggingface.co/docs/trl/dataset_formats

SFT: the fields that matter

SFTConfig(
    max_length=1024,        # truncation length; None disables truncation
    packing=True,           # pack sequences into max_length blocks: fewer pad tokens, higher throughput
    padding_free=True,      # flatten batch, no padding; requires FlashAttention; implied by packing
    use_liger_kernel=True,  # fused Liger kernels, reduces peak memory
    assistant_only_loss=True,  # loss only on assistant turns (conversational datasets)
)

GRPO: online RL

def reward_len(completions, **kwargs):
    return [-abs(20 - len(c[0]["content"])) for c in completions]

trainer = GRPOTrainer(
    model="Qwen/Qwen2.5-0.5B-Instruct",
    reward_funcs=reward_len,  # or a list; rewards are summed
    args=GRPOConfig(output_dir="Qwen2.5-0.5B-GRPO", max_completion_length=512),
    train_dataset=load_dataset("trl-lib/DeepMath-103K", split="train"),
)

Reward functions are called with keyword arguments prompts, completions, completion_ids, trainer_state, plus every extra dataset column — accept **kwargs for the ones you ignore. Return list[float], one reward per completion. With conversational data, completions is a list of message lists, not strings.

The generation batch is per_device_train_batch_size × num_processes × steps_per_generation (or set generation_batch_size directly) and must be divisible by num_generations (default 8). Generation is the usual bottleneck — enable vLLM with use_vllm=True: vllm_mode="colocate" shares the training GPUs (size with vllm_gpu_memory_utilization); vllm_mode="server" uses a separate trl vllm-serve --model <model_id>.

AsyncGRPOTrainer (trl.experimental.async_grpo) implements the same algorithm with generation decoupled from training: a background worker streams completions from a vLLM server while the training loop consumes them, so the two overlap instead of alternating.

CLI

Flags mirror the config fields: trl sft --model_name_or_path Qwen/Qwen2.5-0.5B --dataset_name trl-lib/Capybara. YAML via --config; distributed presets via --accelerate_config zero3 (Python scripts: accelerate launch train.py).

자주 묻는 질문

어떤 학습 방법을 다루나요?

SFT, DPO, GRPO, KTO, 보상 모델링, 증류를 다루며, 실험적인 방법도 더 나열되어 있습니다.

데이터는 어떤 형식이어야 하나요?

학습기에 따라 다르며, DPO는 선택된 답과 거부된 답의 쌍, GRPO는 보상 함수가 있는 프롬프트가 필요합니다.

모델 불러오기도 처리하나요?

네. 모델을 직접 불러오는 대신 이름으로 넘기고 불러오기 옵션을 사용합니다.

상세 정보

작성자의 원본 설명

Post-train LLMs with TRL (Transformers Reinforcement Learning) — SFT, DPO, GRPO, KTO, and reward-model training. Use when writing or debugging training code with the TRL Python API or the trl CLI.

repo: huggingface/skills

인기도

GitHub 스타
11k
순위
#11783
라이선스
Apache-2.0
업데이트
2026. 10. 30.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬