Bạn muốn tạo một chatbot offline chạy trên di động, sử dụng dữ liệu nội bộ công ty nhưng không biết bắt đầu từ đâu? TinyLLaMA – một mô hình ngôn ngữ nhỏ gọn với 1.1 tỷ tham số – có thể là giải pháp hoàn hảo. Trong bài viết này, chúng ta sẽ khám phá cách tải, huấn luyện, và triển khai TinyLLaMA, cùng với cách xử lý một số lỗi thường gặp trong quá trình này.
Tổng Quan Về TinyLLaMA Và Ứng DụngTinyLLaMA là một mô hình ngôn ngữ mã nguồn mở được phát triển để hoạt động hiệu quả trên phần cứng hạn chế. Với kích thước nhỏ (dưới 500MB sau khi tối ưu), nó phù hợp để tích hợp vào ứng dụng di động chạy offline. Tuy nhiên, TinyLLaMA gốc chủ yếu được huấn luyện trên dữ liệu tiếng Anh, nên để hỗ trợ tiếng Việt hoặc các ngữ cảnh cụ thể (như nội bộ công ty), bạn cần tinh chỉnh (fine-tune) với dữ liệu riêng.Quy trình cơ bản bao gồm:
- Tải mô hình TinyLLaMA từ Hugging Face.
- Chuẩn bị dữ liệu nội bộ (ví dụ: FAQ công ty bằng tiếng Việt).
- Huấn luyện lại mô hình trên máy tính.
- Chuyển đổi và triển khai thành chatbot offline trên di động.
Bài viết này sẽ hướng dẫn chi tiết từng bước, từ tải mô hình đến xử lý lỗi khi huấn luyện.
Hướng Dẫn Chi Tiết Huấn Luyện TinyLLaMA
Bước 1: Tải Và Lưu Mô HìnhĐầu tiên, bạn cần tải TinyLLaMA từ Hugging Face và lưu cục bộ để sử dụng:python
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
model = AutoModelForCausalLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
model.save_pretrained("./tinyllama")
tokenizer.save_pretrained("./tinyllama")
- Kết quả: Mô hình và tokenizer được lưu vào thư mục ./tinyllama.
Bước 2: Chuẩn Bị Dữ LiệuDữ liệu cần ở dạng văn bản đơn giản (file .txt), ví dụ:
Câu hỏi: Làm sao để xin nghỉ phép?
Trả lời: Điền form trên hệ thống và gửi quản lý.
---
Câu hỏi: Chính sách thưởng cuối năm thế nào?
Trả lời: Thưởng dựa trên hiệu suất, tối đa 2 tháng lương.
File dữ liệu huấn luyện : du_lieu_cong_ty.txt
Lưu file này với tên du_lieu_cong_ty.txt.
Bước 3: Huấn Luyện Mô HìnhDùng script sau để tinh chỉnh TinyLLaMA với dữ liệu của bạn:python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
from datasets import load_dataset
# Load mô hình và tokenizer
model_path = "./tinyllama"
model = AutoModelForCausalLM.from_pretrained(model_path).half()
tokenizer = AutoTokenizer.from_pretrained(model_path)
# Load dữ liệu
dataset = load_dataset("text", data_files={"train": "du_lieu_cong_ty.txt"})
# Tokenize dữ liệu
def tokenize_function(examples):
tokenized = tokenizer(examples["text"], padding="max_length", truncation=True, max_length=64)
tokenized["labels"] = tokenized["input_ids"].copy()
return tokenized
tokenized_dataset = dataset.map(tokenize_function, batched=True, remove_columns=["text"])
# Thiết lập tham số huấn luyện
training_args = TrainingArguments(
output_dir="./tinyllama_finetuned",
overwrite_output_dir=True,
num_train_epochs=3,
per_device_train_batch_size=1,
gradient_accumulation_steps=4,
save_steps=500,
save_total_limit=2,
logging_dir="./logs",
logging_steps=100,
report_to="none",
)
# Tạo Trainer tùy chỉnh để tính loss
class CustomTrainer(Trainer):
def compute_loss(self, model, inputs, return_outputs=False):
labels = inputs.pop("labels")
outputs = model(**inputs)
logits = outputs.logits
shift_logits = logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
loss_fct = torch.nn.CrossEntropyLoss()
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
return (loss, outputs) if return_outputs else loss
trainer = CustomTrainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset["train"],
)
# Huấn luyện
print("Bắt đầu huấn luyện TinyLLaMA...")
trainer.train()
print("Huấn luyện hoàn tất!")
# Lưu mô hình
model.save_pretrained("./tinyllama_finetuned")
tokenizer.save_pretrained("./tinyllama_finetuned")
file : train.py
- Chạy: python train_tinyllama.py
- Kết quả: Mô hình được lưu tại ./tinyllama_finetuned.
Bước 4: Kiểm Tra Mô HìnhDùng script sau để kiểm tra chatbot:python
from transformers import pipeline
chatbot = pipeline("text-generation", model="./tinyllama_finetuned", tokenizer="./tinyllama_finetuned")
while True:
user_input = input("Nhập câu hỏi: ")
if user_input.lower() == "exit": break
response = chatbot(user_input, max_length=50)[0]["generated_text"]
print(f"Trả lời: {response}")
file: test.py
Một Số Lỗi Thường Gặp Và Cách Khắc Phục
1. Lỗi "CUDA Out of Memory"Thông báo lỗi:
torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 44.00 MiB...Nguyên nhân: GPU không đủ bộ nhớ (ví dụ: GPU 4GB bị chiếm gần hết).Khắc phục:
- Giảm per_device_train_batch_size xuống 1.
- Thêm gradient_accumulation_steps=4 để mô phỏng batch size lớn hơn.
- Chuyển sang CPU: CUDA_VISIBLE_DEVICES="" python train_tinyllama.py.
- Dùng FP16: model.half().
2. Lỗi Yêu Cầu Xác Thực W&BThông báo lỗi:
wandb: You can find your API key in your browser here: https://wandb.ai/authorizeNguyên nhân: Trainer mặc định gửi log đến Weights & Biases.Khắc phục:
- Thêm report_to="none" vào TrainingArguments.
- Tắt W&B qua lệnh: WANDB_MODE=disabled python train_tinyllama.py.
3. Lỗi "Model Did Not Return a Loss"Thông báo lỗi:
ValueError: The model did not return a loss from the inputs, only the following keys: logits, past_key_valuesNguyên nhân: Dữ liệu thiếu labels hoặc Trainer không tính loss tự động.Khắc phục:
- Thêm labels trong tokenize_function:
tokenized["labels"] = tokenized["input_ids"].copy(). - Dùng CustomTrainer để tính loss thủ công (như trong code trên).
Kết Luận Huấn luyện TinyLLaMA để tạo chatbot offline là một quá trình khả thi ngay cả với phần cứng hạn chế. Bằng cách làm theo các bước trên và xử lý lỗi kịp thời, bạn có thể tạo ra một trợ lý AI tùy chỉnh cho công ty mình. Nếu cần tối ưu thêm hoặc triển khai lên di động, hãy tiếp tục khám phá các công cụ như ONNX hoặc TensorFlow Lite. Chúc bạn thành công!