簡介
LoRA 和 QLoRA 是最經濟的微調技術 - 僅更新 0.1-1% 的參數,在免費 GPU 上運行 (Colab T4)。
1. LoRA-直覺
Thay vì update TOÀN BỘ weight matrix W (d × d):
W_new = W + ΔW
LoRA decompose ΔW thành 2 matrices nhỏ:
ΔW = A × B (A: d × r, B: r × d, với r << d)
Ví dụ:
W: 4096 × 4096 = 16.7M params → cập nhật TẤT CẢ
LoRA (r=16): 4096×16 + 16×4096 = 131K params → cập nhật 0.8%
2. QLoRA — 量化 + LoRA
QLoRA = 4-bit quantization base model + LoRA adapters
→ Giảm VRAM từ 32GB → 6GB
→ Chạy được trên Google Colab T4 (16GB)!
3. 實踐 Unsloth
from unsloth import FastLanguageModel
# Load model với 4-bit quantization
model, tokenizer = FastLanguageModel.from_pretrained(
model_name="unsloth/Meta-Llama-3.1-8B-Instruct",
max_seq_length=2048,
load_in_4bit=True,
)
# Add LoRA adapters
model = FastLanguageModel.get_peft_model(
model, r=16, lora_alpha=16,
target_modules=["q_proj","k_proj","v_proj","o_proj"],
lora_dropout=0,
)
# Train
from trl import SFTTrainer
trainer = SFTTrainer(
model=model,
dataset=dataset,
max_seq_length=2048,
args=TrainingArguments(
per_device_train_batch_size=2,
num_train_epochs=3,
learning_rate=2e-4,
output_dir="outputs",
),
)
trainer.train()
總結
- LoRA:僅更新約 1% 的參數 → 節省 GPU 和時間
- QLoRA:新增量化 → 在消費級 GPU 上運行
- Unsloth:比標準 LoRA 訓練快 2 倍
- 成本:Colab 上 0 美元,或雲端 GPU 約 1–3 美元/小時
練習
- 在 Google Colab (QLoRA) 上微調 LLaMA 3 8B
- 輸出比較:LoRA FT vs API FT (Gemini/OpenAI)
- 嘗試排名 r=8 vs r=16 vs r=32 — 比較質量 4.合併LoRA適配器並匯出完整模型