Tôi còn nhớ rõ cái ngày đầu tiên deploy hệ thống RAG cho một doanh nghiệp thương mại điện tử quy mô 500.000 sản phẩm. Đội ngũ kỹ sư AI đã fine-tune Llama 3 8B bằng Axolotl suốt 3 ngày liên tục, nhưng model output cứ "hallucination" như thật. Sau khi debug từng dòng config, chúng tôi phát hiện chỉ cần thay đổi gradient_accumulation_steps và warmup_steps là model đã hoạt động ổn định ngay. Bài viết này sẽ chia sẻ toàn bộ kinh nghiệm thực chiến, kèm code mẫu có thể copy-paste chạy ngay.
Axolotl Là Gì Và Tại Sao Nên Dùng
Axolotl là một công cụ fine-tuning mã nguồn mở được thiết kế để đơn giản hóa quá trình huấn luyện LLM. Thay vì phải viết hàng trăm dòng code training loop từ đầu, bạn chỉ cần khai báo config YAML và Axolotl sẽ lo phần còn lại.
Điểm mạnh của Axolotl nằm ở khả năng hỗ trợ nhiều kiến trúc model (LLaMA, Mistral, Qwen, Phi-3) và nhiều phương pháp fine-tuning (LoRA, QLoRA, Full-fine-tune). Với chi phí huấn luyện chỉ bằng một phần nhỏ so với việc train từ đầu, Axolotl đã trở thành công cụ không thể thiếu của các kỹ sư AI trong cộng đồng.
Cài Đặt Môi Trường
Trước khi bắt đầu, hãy đảm bảo môi trường của bạn đã cài đặt đầy đủ dependencies. Dưới đây là script cài đặt tôi thường dùng cho Ubuntu 22.04 với GPU NVIDIA.
# Cài đặt Axolotl với CUDA 12.1 support
pip install axolotl[flash] torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
Kiểm tra GPU
nvidia-smi
Xác nhận CUDA available
python -c "import torch; print(f'CUDA: {torch.cuda.is_available()}, Device: {torch.cuda.get_device_name(0)}')"
Sau khi cài đặt xong, bạn sẽ thấy thông tin GPU hiển thị như RTX 4090 hoặc A100 với CUDA ready.
Cấu Hình Cơ Bản Cho Fine-Tuning QLoRA
QLoRA (Quantized Low-Rank Adaptation) là phương pháp được ưa chuộng nhất hiện nay vì cho phép fine-tune model lớn trên GPU có VRAM giới hạn. Dưới đây là config YAML hoàn chỉnh mà tôi sử dụng cho dự án chatbot hỗ trợ khách hàng thương mại điện tử.
# config_qlora_ecommerce.yaml
base_model: meta-llama/Meta-Llama-3-8B-Instruct
model_type: LlamaForCausalLM
tokenizer_type: LlamaTokenizer
load_in_4bit: true
bf16: true
tf32: true
dataset_path: ./data/ecommerce_qa.jsonl
dataset_format: alpaca
sequence_len: 4096
sample_packing: true
pad_to_sequence_len: true
gradient_accumulation_steps: 4
micro_batch_size: 2
num_epochs: 3
optimizer: adamw_torch
lr_scheduler: cosine
learning_rate: 0.0002
warmup_ratio: 0.1
weight_decay: 0.01
lora_r: 64
lora_alpha: 128
lora_dropout: 0.05
lora_target_modules:
- q_proj
- k_proj
- v_proj
- o_proj
- gate_proj
- up_proj
- down_proj
logging_steps: 10
eval_steps: 100
save_steps: 200
save_total_limit: 3
autoresume_from_checkpoints: true
adapter: qlora
deepspeed:
stage: 2
offload_optimizer:
device: cpu
pin_memory: true
zero_optimization:
stage: 2
allgather_partitions: true
reduce_scatter: true
overlap_comm: true
contiguous_gradients: true
Chuẩn Bị Dataset Theo Định Dạng Alpaca
Axolotl yêu cầu dataset ở định dạng JSON Lines với cấu trúc cụ thể. Dưới đây là cách tôi format dataset từ file CSV của hệ thống CRM doanh nghiệp.
# Tạo dataset alpaca format từ CSV
import json
import pandas as pd
def create_alpaca_dataset(csv_path, output_path):
"""Chuyển đổi CSV thành Alpaca format cho Axolotl"""
df = pd.read_csv(csv_path)
prompts = []
for _, row in df.iterrows():
prompt = {
"instruction": row['question'],
"input": row.get('context', ''),
"output": row['answer']
}
prompts.append(prompt)
with open(output_path, 'w', encoding='utf-8') as f:
for p in prompts:
f.write(json.dumps(p, ensure_ascii=False) + '\n')
print(f"✓ Đã tạo {len(prompts)} samples tại {output_path}")
return output_path
Sử dụng với HolySheep API để generate synthetic data
import openai
client = openai.OpenAI(
api_key="YOUR_HOLYSHEEP_API_KEY",
base_url="https://api.holysheep.ai/v1"
)
Tạo 1000 synthetic QA pairs cho việc fine-tune
response = client.chat.completions.create(
model="gpt-4.1",
messages=[
{"role": "system", "content": "Bạn là chuyên gia tạo dữ liệu training cho chatbot thương mại điện tử."},
{"role": "user", "content": "Tạo 50 cặp QA về chính sách đổi trả hàng, format JSON array với fields: question, context, answer"}
],
temperature=0.7
)
print(response.choices[0].message.content)
Bắt Đầu Quá Trình Fine-Tuning
Sau khi đã chuẩn bị config và dataset, bạn có thể khởi động training với câu lệnh đơn giản. Tuy nhiên, tôi khuyên bạn nên sử dụng script launch có monitoring để theo dõi tiến trình.
#!/bin/bash
launch_finetune.sh
export CUDA_VISIBLE_DEVICES=0,1
export TRANSFORMERS_CACHE=./cache
export HF_HOME=./cache
Logging với timestamp
LOG_FILE="training_$(date +%Y%m%d_%H%M%S).log"
Bắt đầu training với monitoring
accelerate launch \
--config_file ./configs/deepspeed_zero2.yaml \
--num_processes 2 \
axolotl/main.py \
./configs/config_qlora_ecommerce.yaml \
2>&1 | tee $LOG_FILE
Copy best checkpoint
cp -r ./outputs/best ./checkpoints/final_model
echo "✓ Training hoàn tất. Log: $LOG_FILE"
echo "✓ Model checkpoint: ./checkpoints/final_model"
Đánh Giá Model Sau Fine-Tuning
Sau khi training xong, việc đánh giá model là bước quan trọng để xác nhận chất lượng. Tôi thường dùng kết hợp cả automatic metrics và human evaluation.
# evaluate_model.py
import openai
from rouge_score import rouge_scorer
import json
client = openai.OpenAI(
api_key="YOUR_HOLYSHEEP_API_KEY",
base_url="https://api.holysheep.ai/v1"
)
def evaluate_finetuned_model(model_path, test_data):
"""Đánh giá model với test set"""
scorer = rouge_scorer.RougeScorer(['rouge1', 'rouge2', 'rougeL'], use_stemmer=True)
results = {
"rouge1": [],
"rouge2": [],
"rougeL": [],
"response_times": []
}
for item in test_data:
# Inference với model đã fine-tune
start = time.time()
response = client.chat.completions.create(
model="local-model", # Thay bằng model path của bạn
messages=[
{"role": "system", "content": "Bạn là trợ lý hỗ trợ khách hàng thương mại điện tử."},
{"role": "user", "content": item['question']}
]
)
elapsed = (time.time() - start) * 1000 # ms
results["response_times"].append(elapsed)
# Tính ROUGE score
scores = scorer.score(item['answer'], response.choices[0].message.content)
results["rouge1"].append(scores['rouge1'].fmeasure)
results["rouge2"].append(scores['rouge2'].fmeasure)
results["rougeL"].append(scores['rougeL'].fmeasure)
# Tổng hợp kết quả
print(f"ROUGE-1: {mean(results['rouge1']):.4f}")
print(f"ROUGE-2: {mean(results['rouge2']):.4f}")
print(f"ROUGE-L: {mean(results['rougeL']):.4f}")
print(f"Avg Response Time: {mean(results['response_times']):.2f}ms")
return results
Test inference với HolySheep
test_response = client.chat.completions.create(
model="deepseek-v3.2",
messages=[{"role": "user", "content": "Chính sách đổi trả trong 30 ngày áp dụng cho những sản phẩm nào?"}]
)
print(f"Response: {test_response.choices[0].message.content}")
print(f"Latency: {test_response.usage.total_tokens / test_response.response_ms * 1000:.2f}ms/token")
Tối Ưu Chi Phí Với HolySheep AI
Trong quá trình phát triển và testing, việc sử dụng API từ Đăng ký tại đây giúp tiết kiệm đáng kể chi phí. So sánh giá giữa các provider cho thấy HolySheep có mức giá cạnh tranh nhất thị trường:
- DeepSeek V3.2: $0.42/1M tokens - Lý tưởng cho data generation và testing
- Gemini 2.5 Flash: $2.50/1M tokens - Phù hợp cho batch processing
- GPT-4.1: $8/1M tokens - Dùng cho evaluation và benchmark
- Claude Sonnet 4.5: $15/1M tokens - Cho các task phức tạp
Với tỷ giá quy đổi ¥1=$1 và thanh toán qua WeChat/Alipay, chi phí vận hành giảm đến 85% so với sử dụng OpenAI trực tiếp. Độ trễ trung bình dưới 50ms đảm bảo trải nghiệm mượt mà.
Lỗi Thường Gặp Và Cách Khắc Phục
1. Lỗi CUDA Out Of Memory
Đây là lỗi phổ biến nhất khi fine-tune model lớn. Thay vì mua thêm GPU, hãy tối ưu config.
# Giải pháp: Giảm micro_batch_size và tăng gradient_accumulation_steps
config_qlora_ecommerce.yaml - Phiên bản tối ưu VRAM
micro_batch_size: 1 # Giảm từ 2 xuống 1
gradient_accumulation_steps: 8 # Tăng từ 4 lên 8
load_in_8bit: false # Chỉ dùng 4bit quantization
gradient_checkpointing: true # Bật checkpointing
Hoặc sử dụng DeepSpeed ZeRO-3 với offloading
deepspeed:
stage: 3
stage3_param_persistence_threshold: 1e2
stage3_gather_16bit_weights_on_model_save: true
memory_efficient_linear: false
2. Lỗi Dataset Format Không Tương Thích
Axolotl yêu cầu định dạng chính xác. Lỗi này xảy ra khi thiếu fields bắt buộc.
# Sai format - thiếu field
{"instruction": "Câu hỏi", "response": "Câu trả lời"} # ❌
Đúng format Alpaca
{"instruction": "Câu hỏi", "input": "Ngữ cảnh", "output": "Câu trả lời"} # ✓
Hoặc format chat
{"messages": [
{"role": "system", "content": "System prompt"},
{"role": "user", "content": "User message"},
{"role": "assistant", "content": "Assistant response"}
]} # ✓
Validate dataset trước khi training
import json
def validate_dataset(path):
errors = []
with open(path, 'r') as f:
for i, line in enumerate(f, 1):
try:
data = json.loads(line)
required = ['instruction', 'output']
if not all(k in data for k in required):
errors.append(f"Line {i}: Thiếu required fields")
except:
errors.append(f"Line {i}: JSON invalid")
if errors:
print("Dataset errors found:")
for e in errors[:10]: # Hiển thị 10 lỗi đầu
print(f" - {e}")
raise ValueError("Dataset validation failed")
print("✓ Dataset validation passed")
3. Lỗi Training Collapse - Model Chỉ Sinh Text Vô Nghĩa
Model output toàn ký tự lặp hoặc text vô nghĩa, đây là dấu hiệu của learning rate quá cao hoặc dataset có vấn đề.
# Giải pháp: Điều chỉnh hyperparameters
config_qlora_ecommerce.yaml - Phiên bản stable
learning_rate: 0.0001 # Giảm từ 0.0002
warmup_ratio: 0.2 # Tăng warmup từ 0.1
min_lr_ratio: 0.1 # Thêm min_lr_ratio cho cosine scheduler
Kiểm tra dataset quality
def check_dataset_quality(path, sample_size=100):
"""Phát hiện dataset có vấn đề"""
samples = []
with open(path, 'r') as f:
for i, line in enumerate(f):
if i >= sample_size:
break
samples.append(json.loads(line))
# Kiểm tra độ dài
lengths = [len(s['output'].split()) for s in samples]
avg_len = mean(lengths)
if avg_len < 5:
print(f"⚠️ Warning: Output quá ngắn (avg={avg_len:.1f} words)")
if max(lengths) == min(lengths):
print("⚠️ Warning: Tất cả output có độ dài giống nhau - có thể là template")
# Kiểm tra duplication
outputs = [s['output'] for s in samples]
unique_ratio = len(set(outputs)) / len(outputs)
if unique_ratio < 0.5:
print(f"⚠️ Warning: Dataset có nhiều duplication (unique={unique_ratio:.1%})")
print(f"✓ Dataset quality check passed")
4. Lỗi DeepSpeed Không Initialize
DeepSpeed stage 2 hoặc 3 không khởi tạo đúng cách trên multi-GPU.
# Giải pháp: Kiểm tra config và environment
Đảm bảo deepspeed_config.json tồn tại
configs/deepspeed_zero2.json
{
"fp16": {
"enabled": "auto"
},
"bf16": {
"enabled": "auto"
},
"zero_optimization": {
"stage": 2,
"offload_optimizer": {
"device": "cpu",
"pin_memory": true
},
"allgather_partitions": true,
"reduce_scatter": true,
"overlap_comm": true,
"contiguous_gradients": true
},
"gradient_accumulation_steps": "auto",
"gradient_clipping": "auto",
"steps_per_print": 10,
"train_batch_size": "auto",
"train_micro_batch_size_per_gpu": "auto"
}
Chạy với deepspeed config cụ thể
deepspeed --num_gpus=2 \
axolotl/main.py \
./configs/config_qlora_ecommerce.yaml \
--deepspeed configs/deepspeed_zero2.json
Kết Luận
Qua bài viết này, tôi đã chia sẻ toàn bộ quy trình fine-tune model với Axolotl từ cài đặt, cấu hình, chuẩn bị dataset đến đánh giá model. Điểm mấu chốt nằm ở việc hiểu rõ từng tham số trong config file và cách debug khi gặp lỗi.
Đặc biệt, với HolySheep AI, chi phí vận hành cho các tác vụ AI giảm đến 85%, giúp các dự án startup và doanh nghiệp vừa và nhỏ có thể tiếp cận công nghệ fine-tuning một cách dễ dàng hơn.
Nếu bạn gặp bất kỳ vấn đề nào trong quá trình implement, đừng ngần ngại để lại comment. Tôi sẽ hỗ trợ trong vòng 24 giờ.
👉 Đăng ký HolySheep AI — nhận tín dụng miễn phí khi đăng ký