Site logo
Tác giả
  • avatar Nguyễn Đức Xinh
    Name
    Nguyễn Đức Xinh
    Twitter
Ngày xuất bản
Ngày xuất bản

Fine-tuning mô hình LLM (LLaMA, Mistral) bằng PyTorch + Hugging Face - Hướng dẫn thực chiến

🧠 I. Fine-tuning LLM là gì?

Fine-tuning là quá trình huấn luyện tiếp một mô hình ngôn ngữ đã được pre-trained, nhằm giúp nó hiểu rõ hơn một domain hoặc task cụ thể.

Ví dụ:

  • Model gốc (LLaMA 3) hiểu “general English”.
  • Bạn fine-tune để nó hiểu “code review”, “tư vấn y khoa”, hoặc “trả lời tiếng Việt chính xác hơn”.

⚙️ II. Kiến trúc cơ bản của quy trình fine-tuning

+-------------------+
|   Pretrained LLM  |
| (LLaMA, Mistral)  |
+---------+---------+
          |
          | Add LoRA adapters / fine-tune weights
          v
+-------------------+
|  Fine-tuned Model |
|  (domain-specific)|
+-------------------+

Bước tổng quát:

  1. Chọn base model (VD: meta-llama/Llama-3-8B hoặc mistralai/Mistral-7B-v0.1)
  2. Chuẩn bị dataset (dạng text, instruction → response)
  3. Áp dụng LoRA / QLoRA để giảm tài nguyên huấn luyện
  4. Dùng Hugging Face Transformers + PEFT để fine-tune
  5. Evaluate & Save model
  6. Push model lên Hugging Face Hub hoặc dùng local

💡 III. Công cụ cần thiết

Library Vai trò
PyTorch Nền tảng tính toán & GPU
Transformers (Hugging Face) Tải và quản lý LLM
Datasets (HF) Xử lý và load dữ liệu
PEFT Parameter-Efficient Fine-Tuning (LoRA, QLoRA)
bitsandbytes Huấn luyện mô hình lớn với 4-bit / 8-bit precision
accelerate Tối ưu training đa GPU
trl Training Reinforcement Learning for LLM (optional cho SFT/RLHF)

🧱 IV. Các phương pháp Fine-tuning phổ biến

Phương pháp Mô tả Ưu điểm
Full fine-tune Cập nhật toàn bộ trọng số model Chính xác nhất nhưng tốn tài nguyên
LoRA (Low-Rank Adaptation) Chèn các lớp nhỏ để học thêm thông tin Nhẹ, nhanh, tiết kiệm VRAM
QLoRA LoRA + nén model xuống 4-bit Cực kỳ tiết kiệm, chạy được trên 1 GPU 24GB
Prompt-tuning / Adapter-tuning Thêm prompt embedding để học Nhanh, ít thay đổi model

→ Trong thực tế: QLoRA + Hugging Face PEFT là lựa chọn phổ biến nhất hiện nay.


🧩 V. Quy trình thực tế (ví dụ: Fine-tune LLaMA 3 8B)

1️⃣ Cài đặt môi trường

pip install torch transformers datasets peft bitsandbytes accelerate trl

2️⃣ Load model và tokenizer

from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "meta-llama/Meta-Llama-3-8B"

tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    load_in_4bit=True,  # Dùng QLoRA (4-bit quantization)
    device_map="auto",
)

3️⃣ Chuẩn bị dữ liệu huấn luyện

Dữ liệu có thể ở dạng JSON:

{
  "instruction": "Giải thích về lập trình hướng đối tượng",
  "response": "Lập trình hướng đối tượng (OOP) là mô hình..."
}

Load và tokenize:

from datasets import load_dataset

dataset = load_dataset("json", data_files="train.json")

def format_prompt(example):
    return f"### Instruction:\n{example['instruction']}\n### Response:\n{example['response']}"

def tokenize_fn(example):
    text = format_prompt(example)
    tokens = tokenizer(text, truncation=True, padding="max_length", max_length=1024)
    tokens["labels"] = tokens["input_ids"].copy()
    return tokens

tokenized = dataset["train"].map(tokenize_fn)

4️⃣ Cấu hình LoRA (PEFT)

from peft import LoraConfig, get_peft_model

lora_config = LoraConfig(
    r=8,                # rank
    lora_alpha=32,
    target_modules=["q_proj", "v_proj"],  # module cần chèn adapter
    lora_dropout=0.05,
    bias="none",
    task_type="CAUSAL_LM"
)

model = get_peft_model(model, lora_config)

5️⃣ Huấn luyện

from transformers import Trainer, TrainingArguments

args = TrainingArguments(
    output_dir="./llama3-finetuned",
    per_device_train_batch_size=2,
    gradient_accumulation_steps=4,
    learning_rate=2e-4,
    num_train_epochs=3,
    fp16=True,
    logging_steps=50,
    save_strategy="epoch",
)

trainer = Trainer(
    model=model,
    args=args,
    train_dataset=tokenized,
    tokenizer=tokenizer,
)

trainer.train()

6️⃣ Lưu và sử dụng model

model.save_pretrained("./llama3-finetuned")
tokenizer.save_pretrained("./llama3-finetuned")

Test thử:

from transformers import pipeline

pipe = pipeline("text-generation", model="./llama3-finetuned", tokenizer=tokenizer)
print(pipe("Giải thích về mạng nơ-ron nhân tạo")[0]["generated_text"])

⚙️ VI. Các mẹo tối ưu khi fine-tuning

Sử dụng QLoRA (4-bit) → giảm VRAM 3–4 lần ✅ Batch nhỏ + gradient accumulation nếu GPU yếu ✅ Freeze embedding layers để tránh overfitting ✅ Chuẩn hóa dữ liệu (prompt format consistent)Huấn luyện 3–5 epoch đủ cho domain adaptationDùng wandb để theo dõi loss, perplexity


🧠 VII. Fine-tuning vs Instruct-tuning vs RLHF

Loại Mục tiêu Ví dụ
Fine-tuning Dạy model về domain mới Chatbot nội bộ
Instruction-tuning Dạy model hiểu lệnh người dùng Alpaca, Vicuna
RLHF Dạy model phản hồi tự nhiên, phù hợp con người ChatGPT, Claude

➡️ Bạn có thể kết hợp các bước: Pretrain → Fine-tune → Instruct-tune → RLHF để đạt chất lượng cao nhất.


🧰 VIII. Khi nào nên fine-tune LLM?

Trường hợp Giải pháp
Muốn model nói tiếng Việt tốt hơn Fine-tune với dữ liệu tiếng Việt
Muốn model chuyên về lập trình Fine-tune với code dataset
Muốn model biết quy trình nội bộ công ty Fine-tune trên tài liệu nội bộ
Muốn chatbot hiểu ngữ cảnh riêng Fine-tune hoặc dùng RAG

⚡ IX. So sánh: Fine-tune vs RAG

Tiêu chí Fine-tune RAG (Retrieval-Augmented Generation)
Cách làm Huấn luyện lại model Cung cấp ngữ cảnh qua prompt
Tốn tài nguyên Cao Thấp
Dễ update dữ liệu Khó (phải train lại) Dễ (update database)
Độ chính xác với domain Cao Trung bình–cao
Dùng thực tế Khi domain rất đặc thù Khi dữ liệu hay thay đổi

👉 Thực tế, RAG + Fine-tune nhẹ (LoRA) là giải pháp phổ biến nhất hiện nay.


🧱 X. Kết luận

Nội dung Mô tả
Công nghệ PyTorch + Hugging Face (Transformers, PEFT)
Kỹ thuật chủ đạo LoRA / QLoRA
Ưu điểm Nhanh, tiết kiệm, có thể fine-tune trên 1 GPU
Ứng dụng Chatbot nội bộ, dịch tự động, code assistant, document QA
Ví dụ model phổ biến LLaMA, Mistral, Phi-3, Gemma

💬 Kết luận cuối cùng

Fine-tuning bằng PyTorch + Hugging Face giúp bạn biến một mô hình LLM tổng quát → thành một chuyên gia trong lĩnh vực bạn mong muốn.

Dễ triển khai, dễ mở rộng, và cực mạnh khi kết hợp với RAG hoặc API nội bộ.