본문으로 건너뛰기
cccskills
무료GitHub에 공개

trl-training

Write and debug code for further training large language models with TRL. Match training methods to dataset formats, configure supervised or preference-based training, and set up reward functions through Python or the command line.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

원문원문 설명 보기

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.

연동 도구Hugging Face
설치 방법 보기

이럴 때 유용합니다

  • Training a language model on example responses
  • Training with preferred and rejected response pairs
  • Debugging GRPO reward functions and batch settings
  • Running training from the command line

포함된 파일(1)

  • SKILL.md4.2 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

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.

TrainerDataset type
SFTTrainerlanguage modeling or prompt-completion
DPOTrainerpreference (chosen/rejected pairs)
GRPOTrainerprompt-only + reward function(s)
DistillationTrainerprompt-only + a teacher model (on-policy distillation)
KTOTrainerunpaired preference (per-sample bool label)
RewardTrainerpreference (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).

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

hf-cli

무료

Manage Hugging Face Hub through the hf command line tool. Download and upload models or datasets, organize cloud storage, manage authentication and local caches, run scheduled jobs, and deploy or maintain model inference services.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Download or publish models and datasets
  • Sync training checkpoints to cloud storage
  • Inspect and clean the local cache
huggingface/skills1.1만2026년 10월 9일 업데이트

Check the AWS profile, region, account ID, and caller identity before starting AWS work. Read local configuration and validate credentials, then flag missing settings, expired access, or possible IAM restrictions associated with SSO authentication.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Check the AWS account and region before deployment
  • Identify the active profile when none was specified
  • Detect expired credentials or missing configuration
huggingface/skills1.1만2026년 10월 9일 업데이트

Prepare an isolated Python environment for SageMaker deployments and AWS automation. The skill selects a supported Python version, installs current AWS packages, and checks versions so installation and execution use the same environment.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Prepare a Python environment for SageMaker deployment
  • Separate AWS automation dependencies from system Python
  • Check installed AWS package versions
huggingface/skills1.1만2026년 10월 9일 업데이트

Plan how to serve a model on Amazon SageMaker AI. The skill uses model type, traffic, response time, and cost constraints to recommend a deployment route, check instance quotas, and coordinate specialized setup and deployment skills.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Plan AWS hosting for a language model
  • Choose a serving route for an embedding model
  • Plan asynchronous inference for image generation
huggingface/skills1.1만2026년 10월 9일 업데이트

Prepare SageMaker deployments and training by finding existing execution roles, checking trust settings, and reviewing required permissions. Guides role creation only when necessary and identifies permission issues that require an AWS administrator.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Check execution roles before deploying a SageMaker endpoint
  • Find an existing role when no ARN is provided
  • Investigate IAM AccessDenied errors
huggingface/skills1.1만2026년 10월 9일 업데이트

Deploy SageMaker endpoints, the services that answer model requests, with automatic capacity scaling, CloudWatch alarms, and resource tags. Supports real-time and asynchronous inference, scaling down to zero instances, deployment checks, and resource cleanup.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Deploying a real-time model endpoint
  • Scaling a sparse workload down to zero instances
  • Running long inference jobs asynchronously
huggingface/skills1.1만2026년 10월 9일 업데이트

huggingface의 스킬 모두 보기

이 스킬의 문제 신고