trl-training
Skill này làm gì
Skill này giúp AI viết và sửa mã huấn luyện để cải thiện model ngôn ngữ sau lần huấn luyện đầu tiên. Skill dành cho lập trình viên muốn tinh chỉnh hoặc căn chỉnh model bằng TRL.
Khi nào nên dùng
- ✓Khi bạn muốn tinh chỉnh một model ngôn ngữ bằng SFT hoặc căn chỉnh nó bằng dữ liệu ưa thích.
- ✓Khi bạn muốn viết hoặc gỡ lỗi mã huấn luyện TRL bằng Python hoặc dòng lệnh.
- ✓Khi bạn cần học tăng cường với hàm thưởng, như GRPO.
Liên kết skill
https://github.com/huggingface/skills/blob/main/skills/trl-training/SKILL.mdSao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.
Cách dùng
Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.
Tin nhắn có sẵn để dán
Dành cho Claude Code, Codex hoặc Cursor: chạy lệnh trong thư mục dự án của bạn và skill sẽ được cài đặt.
Tải tệp SKILL.md về và thả vào thư mục skill của agent.
Ví dụ cách nhờ AI
“Viết script huấn luyện DPO bằng TRL dùng các cặp câu trả lời được chọn và bị từ chối của tôi cho một model Qwen nhỏ.”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
AI chọn trainer phù hợp và cấu hình tương ứng cho phương pháp và loại dataset. Sau đó AI viết hoặc sửa mã Python hoặc lệnh, dùng các lớp và tùy chọn TRL chuẩn.
Nội dung kỹ thuật (SKILL.md gốc)
Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.
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).
Câu hỏi thường gặp
Skill bao quát những phương pháp huấn luyện nào?
Skill bao quát SFT, DPO, GRPO, KTO, reward modeling và distillation, với các phương pháp khác được liệt kê là thử nghiệm.
Dữ liệu cần định dạng gì?
Định dạng phụ thuộc vào trainer, chẳng hạn các cặp được chọn và bị từ chối cho DPO, hoặc prompt kèm hàm thưởng cho GRPO.
Skill có xử lý việc tải model không?
Có. Skill truyền model dưới dạng tên và dùng các tùy chọn tải, thay vì tải model thủ công.
Chi tiết
Mô tả gốc của tác giả
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
Độ phổ biến
- Sao GitHub
- 11k
- Vị trí xếp hạng
- #11783
- Giấy phép
- Apache-2.0
- Cập nhật
- 30/10/2026
Bình luận
- …
Thêm skill từ kho mã này
hf-cli
11kGiúp agent của bạn dùng công cụ dòng lệnh Hugging Face để tải xuống, tải lên và quản lý model, dataset, Spaces, repo và bộ nhớ đệm cục bộ.
hf-cloud-aws-context-discovery
11kGiúp agent của bạn tìm AWS profile, region và thông tin tài khoản trước khi làm bất kỳ việc gì trên cloud, để không phải đoán tài khoản nào sẽ dùng.
hf-cloud-python-env-setup
11kGiúp agent của bạn thiết lập môi trường Python sạch với phiên bản Python phù hợp và thư viện mới nhất trước khi chạy SageMaker hoặc tự động hóa AWS.
hf-cloud-sagemaker-deployment-planner
11kGiúp agent của bạn lên kế hoạch triển khai model lên Amazon SageMaker, chọn lưu trữ thời gian thực, serverless, async hoặc batch với mặc định hợp lý.
Skill tương tự
pytorch-patterns
280kGiúp agent của bạn dùng PyTorch cho các mô hình học máy. Áp dụng thực hành tốt nhất để huấn luyện mô hình hiệu quả và đảm bảo kết quả có thể lặp lại.
evm-token-decimals
280kGiúp agent tránh lỗi về số thập phân khi làm việc với các mạng blockchain khác nhau. Đảm bảo giá trị token chính xác trong giao dịch và phép tính.
ito-inference
280kGiúp agent kiểm tra xem các mô hình AI đã sẵn sàng để dùng chưa. Kết nối yêu cầu tài nguyên tính toán với dịch vụ mô hình đã sẵn sàng.