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

minicpm5-finetune-unsloth

하는 일

이 스킬은 GPU 한 개에서 unsloth로 LoRA 또는 4비트 QLoRA를 이용해 MiniCPM5를 학습하도록 AI를 안내합니다. 소비자용 그래픽 카드 한 개를 가졌고 메모리 사용량을 낮추려는 사람을 위한 스킬입니다.

사용하는 경우

  • ✓메모리가 제한된 소비자용 GPU 한 개에서 MiniCPM5를 미세 조정하고 싶을 때.
  • ✓메모리를 아끼기 위해 4비트 QLoRA를 써 보고 싶을 때.
  • ✓unsloth의 FastLanguageModel로 학습하는 경우.

스킬 링크

https://github.com/OpenBMB/MiniCPM/blob/main/skills/minicpm5-finetune-unsloth/SKILL.md

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

사용 방법

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

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

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

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):

  1. transformers==4.57.3 — required if vLLM is in the same env (unsloth's vLLM coexistence patch only handles transformers ≤ 4.57.x).
  2. torch==2.7.1 + torchvision==0.22.1 — pip install unsloth may 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.3 is 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 a dataclass error 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.

이 스킬이 유용한가요?

0

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

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬