minicpm5-finetune-trl
Skill này làm gì
Skill này hướng dẫn AI huấn luyện MiniCPM5 bằng TRL và PEFT trong một script Python thuần. Skill dành cho developer muốn kiểm soát đầy đủ và không dùng file cấu hình.
Khi nào nên dùng
- ✓Khi bạn muốn fine-tune MiniCPM5 bằng một script Python ngắn, không dùng YAML.
- ✓Khi bạn muốn loss huấn luyện chỉ tính trên câu trả lời của trợ lý.
- ✓Khi bạn dùng SFTTrainer hoặc LoraConfig và cần giúp đỡ về thiết lập.
Liên kết skill
https://github.com/OpenBMB/MiniCPM/blob/main/skills/minicpm5-finetune-trl/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 một script Python fine-tune MiniCPM5-2B bằng LoRA trên file chat của tôi, và chỉ huấn luyện trên các câu trả lời của trợ lý.”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
Skill vá mẫu chat để chỉ các câu trả lời của trợ lý được tính vào loss, thiết lập cấu hình LoRA và chạy SFT trainer trên dữ liệu của bạ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.
Fine-tune MiniCPM5-1B and MiniCPM5-2B with TRL + PEFT
Bare-metal Python recipe with assistant-only loss mask. Minimal abstractions, full control.
Required input
| Var | Example | Default |
|---|---|---|
BASE_MODEL |
openbmb/MiniCPM5-2B |
required; openbmb/MiniCPM5-1B also works |
DATA |
path to messages-format jsonl | required |
OUTPUT_DIR |
./runs/minicpm5_trl |
required |
Steps
1. Install (once)
# latest (CUDA 13.x driver hosts)
pip install "torch>=2.11" "torchvision" \
"trl>=0.21" "peft>=0.13" "transformers>=5.6,<6" \
datasets accelerate
# fallback for CUDA 12.x driver hosts:
# pip install "torch==2.7.1" "torchvision==0.22.1" \
# "trl==0.20.0" "peft==0.11.1" "transformers==4.57.3" \
# datasets accelerate
2. Patch the tokenizer with a training-only chat template
Save as train_lora.py:
import json, os, torch
from datasets import Dataset
from peft import LoraConfig, get_peft_model
from transformers import AutoModelForCausalLM, AutoTokenizer, set_seed
from trl import SFTConfig, SFTTrainer
BASE = os.environ["BASE_MODEL"]
DATA = os.environ["DATA"]
OUT = os.environ["OUTPUT_DIR"]
# Training-only chat template — adds {% generation %} so SFTConfig(assistant_only_loss=True)
# masks all non-assistant tokens. Token sequence stays identical to the model's full chat
# template, so the trained adapter is fully compatible at inference time.
TRAIN_CHAT_TEMPLATE = (
"{{- bos_token }}"
"{%- for message in messages %}"
"{%- if message['role'] == 'system' %}"
"{{- '<|im_start|>system\\n' + message['content'] + '<|im_end|>\\n' }}"
"{%- elif message['role'] == 'user' %}"
"{{- '<|im_start|>user\\n' + message['content'] + '<|im_end|>\\n' }}"
"{%- elif message['role'] == 'assistant' %}"
"{{- '<|im_start|>assistant\\n' }}"
"{%- generation %}"
"{{- message['content'] + '<|im_end|>' }}"
"{%- endgeneration %}"
"{{- '\\n' }}"
"{%- endif %}"
"{%- endfor %}"
"{%- if add_generation_prompt %}"
"{{- '<|im_start|>assistant\\n' }}"
"{%- endif %}"
)
set_seed(42)
tok = AutoTokenizer.from_pretrained(BASE, use_fast=True)
if tok.pad_token is None:
tok.pad_token = tok.eos_token
tok.chat_template = TRAIN_CHAT_TEMPLATE # 🔑 do NOT save back to disk
rows = [json.loads(l) for l in open(DATA, encoding="utf-8") if l.strip()]
ds = Dataset.from_list([{"messages": r["messages"]} for r in rows])
model = AutoModelForCausalLM.from_pretrained(BASE, torch_dtype=torch.bfloat16, attn_implementation="sdpa")
model.config.use_cache = False
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
lora = LoraConfig(
r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM",
target_modules=["q_proj","k_proj","v_proj","o_proj","gate_proj","up_proj","down_proj"],
)
model = get_peft_model(model, lora)
model.print_trainable_parameters()
trainer = SFTTrainer(
model=model,
args=SFTConfig(
output_dir=OUT,
num_train_epochs=2,
per_device_train_batch_size=4,
gradient_accumulation_steps=4,
learning_rate=2e-4,
warmup_ratio=0.03,
lr_scheduler_type="cosine",
bf16=True,
max_length=2048,
packing=False,
assistant_only_loss=True, # 🔑 only assistant tokens contribute to loss
logging_steps=10,
save_steps=200,
save_total_limit=2,
report_to=["tensorboard"],
dataloader_num_workers=2,
remove_unused_columns=False,
seed=42,
),
train_dataset=ds,
processing_class=tok,
)
trainer.train()
trainer.model.save_pretrained(f"{OUT}/adapter_final")
3. Train
BASE_MODEL=openbmb/MiniCPM5-2B \
DATA=/path/to/messages.jsonl \
OUTPUT_DIR=./runs/minicpm5_trl \
CUDA_VISIBLE_DEVICES=0 python train_lora.py
4. Validate
You should see:
trainable params: model-size dependent (about 1% with the recipe below)
{'loss': 4.07, 'mean_token_accuracy': 0.29, 'epoch': 0.2}
{'loss': 3.52, 'mean_token_accuracy': 0.36, 'epoch': 1.0}
Adapter saved to ${OUTPUT_DIR}/adapter_final/adapter_model.safetensors.
Inference with the LoRA
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
base = AutoModelForCausalLM.from_pretrained("openbmb/MiniCPM5-2B", torch_dtype=torch.bfloat16, device_map="auto")
mod
Câu hỏi thường gặp
Assistant-only loss là gì?
Nghĩa là điểm huấn luyện chỉ dựa trên câu trả lời của trợ lý, không dựa trên tin nhắn của người dùng.
Mẫu chat có làm thay đổi đầu ra của model không?
Skill nói chuỗi token giữ nguyên, và mẫu đã vá chỉ dùng cho huấn luyện.
Skill dùng những phiên bản nào?
Skill liệt kê các gói mới nhất, cùng một bộ dự phòng cho hệ thống có driver CUDA 12.
Chi tiết
Mô tả gốc của tác giả
Fine-tune MiniCPM5-1B or MiniCPM5-2B with bare-metal TRL + PEFT, including assistant-only loss via a chat-template patch. Use when the user wants minimal Python, no YAML, full control, or asks for "TRL", "SFTTrainer", "PEFT", "LoraConfig", "assistant_only_loss".
repo: OpenBMB/MiniCPM
Độ phổ biến
- Sao GitHub
- 12k
- Vị trí xếp hạng
- #11543
- Giấy phép
- Apache-2.0
- Cập nhật
- 21/9/2026
Bình luận
- …
Thêm skill từ kho mã này
minicpm5-deploy-litert
12kGiúp agent chạy các model MiniCPM5 trên máy tính hoặc điện thoại Android bằng runtime LiteRT-LM của Google, chỉ với một file model.
minicpm5-deploy-llama-cpp
12kChỉ cho agent cách chạy model MiniCPM5 bằng llama.cpp trên CPU hoặc card đồ họa gia đình, dùng file GGUF có sẵn.
minicpm5-deploy-lmstudio
12kGiúp agent chạy các model MiniCPM5 trong LM Studio, ứng dụng desktop có cửa sổ chat, và khởi động máy chủ cục bộ kiểu OpenAI của nó.
minicpm5-deploy-mlx
12kGiúp agent chạy các model MiniCPM5 trực tiếp trên máy Mac Apple Silicon bằng framework MLX của Apple, để chat và sinh văn bản cục bộ nhanh.
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.