minicpm5-finetune-unsloth
できること
このスキルは、1枚のGPU上でunslothを使い、LoRAまたは4ビットのQLoRAによりMiniCPM5を学習させる方法をAIに案内します。メモリに制限のある一般向けグラフィックスカードを1枚持ち、メモリ使用量を抑えたい人に向けたものです。
使う場面
- ✓メモリに制限のある一般向けGPU1枚でMiniCPM5を微調整したいとき。
- ✓メモリを節約するために、4ビットでQLoRAを試したいとき。
- ✓学習にunslothのFastLanguageModelを使っているとき。
スキルのリンク
https://github.com/OpenBMB/MiniCPM/blob/main/skills/minicpm5-finetune-unsloth/SKILL.mdコピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。
使い方
いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。
貼り付け用メッセージ
Claude Code、Codex、Cursorの場合:プロジェクトのフォルダで実行するとスキルがインストールされます。
SKILL.mdをダウンロードして、エージェントのスキル用フォルダに入れてください。
AIへの頼み方の例
“24GBのグラフィックスカードで、QLoRAを使ってMiniCPM5-1Bを、できるだけメモリを使わないように微調整してください。”
毎週5つの新しいスキル。1分で読めます。
仕組み
このスキルは、torchとtransformersのバージョンを固定したうえでunslothをインストールし、4ビットまたはbf16でモデルを読み込んでLoRAアダプターを学習させる学習スクリプトを実行します。
技術的な内容(元のSKILL.md)
作者による元のテキスト(英語)をGitHubからそのまま表示しています。
Fine-tune MiniCPM5-1B and MiniCPM5-2B with unsloth
Single-GPU LoRA / QLoRA. Heavy custom kernels for memory savings (~2× reduction at 4-bit).
⚠️ Two install-time pins (read this BEFORE running):
transformers==4.57.3— required if vLLM is in the same env (unsloth's vLLM coexistence patch only handles transformers ≤ 4.57.x).torch==2.7.1+torchvision==0.22.1—pip install unslothmay pull a cu13 torch wheel that fails on cu12.x drivers (cuda.is_available()returns False).pip install --force-reinstall "torch==2.7.1" "torchvision==0.22.1" "transformers==4.57.3"
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_unsloth |
required |
LOAD_IN_4BIT |
True (QLoRA, lowest VRAM) / False (LoRA bf16) |
False |
Steps
1. Install (once) — pin transformers to 4.57.3
pip install "unsloth>=2026.5"
pip install --force-reinstall "transformers==4.57.3"
🔑
transformers==4.57.3is required if vLLM is in the same env. unsloth's vLLM coexistence patch only handles transformers ≤ 4.57.x; if you skip this pin you'll get adataclasserror at import time.
2. Train — save as train_unsloth.py
import json, os, torch
os.environ.setdefault("CUDA_VISIBLE_DEVICES", "0")
from unsloth import FastLanguageModel
from datasets import Dataset
from trl import SFTTrainer, SFTConfig
BASE = os.environ["BASE_MODEL"]
DATA = os.environ["DATA"]
OUT = os.environ["OUTPUT_DIR"]
# 1. Load with unsloth's fast wrapper
model, tok = FastLanguageModel.from_pretrained(
model_name=BASE,
max_seq_length=2048,
dtype=torch.bfloat16,
load_in_4bit=os.environ.get("LOAD_IN_4BIT", "False") == "True",
full_finetuning=False,
)
# 2. Add LoRA
model = FastLanguageModel.get_peft_model(
model,
r=16,
target_modules=["q_proj","k_proj","v_proj","o_proj","gate_proj","up_proj","down_proj"],
lora_alpha=32,
lora_dropout=0.05,
bias="none",
use_gradient_checkpointing="unsloth",
random_state=42,
)
# 3. Data — unsloth's TRL wrapper expects a `text` column
rows = [json.loads(l) for l in open(DATA, encoding="utf-8") if l.strip()]
ds = Dataset.from_list([
{"text": tok.apply_chat_template(r["messages"], tokenize=False)}
for r in rows
])
if tok.pad_token is None:
tok.pad_token = tok.eos_token
# 4. Train
trainer = SFTTrainer(
model=model,
args=SFTConfig(
output_dir=OUT,
dataset_text_field="text", # 🔑 needed for unsloth's wrapper
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,
logging_steps=10,
save_steps=200,
seed=42,
report_to="none",
dataloader_num_workers=2,
),
train_dataset=ds,
processing_class=tok,
)
trainer.train()
trainer.model.save_pretrained(f"{OUT}/adapter_final")
3. Run
BASE_MODEL=openbmb/MiniCPM5-2B \
DATA=/path/to/messages.jsonl \
OUTPUT_DIR=./runs/minicpm5_unsloth \
LOAD_IN_4BIT=False \
python train_unsloth.py
For QLoRA on a consumer GPU (24 GB or less), set LOAD_IN_4BIT=True.
4. Validate
You should see:
==((====))== Unsloth: Fast Llama patching. Transformers: 4.57.3.
🦥 Unsloth: Padding-free auto-enabled, enabling faster training.
trainable params: model-size dependent (about 1% with the recipe below)
{'loss': 4.67, 'epoch': 0.2}
{'loss': 3.52, 'epoch': 1.0}
First iter is slow (~13 s, JIT compile); subsequent iters < 600 ms.
Inference
from unsloth import FastLanguageModel
model, tok = FastLanguageModel.from_pretrained(
model_name="./runs/minicpm5_unsloth", # path to adapter
max_seq_length=4096, dtype=torch.bfloat16, load_in_4bit=False,
)
FastLanguageModel.for_inference(model) # 2× faster generation
inputs = tok.apply_chat_template([{"role":"user","content":"用一句话解释 GQA。"}],
add_generation_prompt=True, enable_thinking=True, return_tensors="pt").to("cuda")
out = model.generate(inputs, max_new_tokens=512, temperature=1.0, top_p=0.95)
print(tok.decode(out[0][inputs.shape[-1]:], skip_special_tokens=True))
よくある質問
なぜ特定のバージョンを固定するのですか?
unslothのvLLMパッチはtransformers 4.57以前にしか対応しておらず、一部のtorchビルドはCUDA 12ドライバーで失敗するとスキルは述べています。
4ビットの設定は何をしますか?
LOAD_IN_4BITをTrueにするとQLoRAが有効になり、最も少ないメモリで済みます。
通常のLoRAとの違いは何ですか?
通常のLoRAはbf16で動き、メモリをより多く使います。QLoRAはモデルを4ビットで読み込むため、メモリを少なく抑えられます。
詳細
作者による元の説明
Fine-tune MiniCPM5-1B or MiniCPM5-2B with unsloth for tight-VRAM single-GPU LoRA / QLoRA. Use when the user wants "unsloth", "FastLanguageModel", QLoRA on a 24 GB consumer GPU, or asks for the smallest VRAM footprint.
repo: OpenBMB/MiniCPM
人気
- GitHubのスター
- 12k
- ランキング
- #11544
- ライセンス
- Apache-2.0
- 更新日
- 2026/9/21
コメント
- …
このリポジトリの他のスキル
minicpm5-deploy-litert
12kGoogleのLiteRT-LMランタイムを使い、1つのモデルファイルでMiniCPM5モデルをパソコンやAndroidスマートフォン上で動かすようエージェントを支援します。
minicpm5-deploy-llama-cpp
12kダウンロード可能なGGUFファイルを使い、llama.cppでCPUや家庭用グラフィックスカード上のMiniCPM5モデルを動かす方法をエージェントに示します。
minicpm5-deploy-lmstudio
12kチャット画面を持つデスクトップアプリであるLM StudioでMiniCPM5モデルを動かし、そのローカルのOpenAI形式サーバーを起動するようエージェントを支援します。
minicpm5-deploy-mlx
12k高速なローカルチャットとテキスト生成のために、AppleのMLXフレームワークでApple Silicon搭載Mac上にMiniCPM5モデルをネイティブに動かすようエージェントを支援します。