Cách tinh chỉnh LLM để giải toán trắc nghiệm tiếng Việt bằng Reinforcement Learning

Bài viết hướng dẫn chi tiết cách tinh chỉnh mô hình ngôn ngữ lớn (LLM) — cụ thể là Llama 3.2-1B — để giải bài toán trắc nghiệm tiếng Việt bằng cách kết hợp LoRAGRPO. Bạn sẽ nắm được quy trình từ cài đặt, chuẩn bị dữ liệu, huấn luyện đến đánh giá mô hình.

Mục tiêu của tinh chỉnh

Chúng ta muốn xây dựng một mô hình có thể:

  • Giải đúng bài toán trắc nghiệm tiếng Việt,
  • Giải thích rõ ràng từng bước suy luận,
  • Đưa ra đáp án cuối cùng một cách chuẩn xác.

Đầu vào: Một câu hỏi toán học tiếng Việt,
Đầu ra: Chuỗi suy luận trong thẻ <thinking>...</thinking> và đáp án trong <SOLUTION>...</SOLUTION>.

Tổng quan quy trình tinh chỉnh

Pipeline 7 bước mà bạn sẽ thực hiện:

  1. Thiết lập môi trường,
  2. Tải mô hình gốc,
  3. Cấu hình LoRA,
  4. Chuẩn bị và tiền xử lý dữ liệu,
  5. Định nghĩa Reward Function,
  6. Huấn luyện bằng GRPO,
  7. Đánh giá và inference mô hình.

Bước 1: Thiết lập môi trường

Cài đặt các thư viện cần thiết:

bash

pip install unsloth vllm==0.7.3 datasets trl

Import các thư viện trong Python:

pythonfrom vllm import SamplingParams
from unsloth import FastLanguageModel
from datasets import load_dataset, Dataset
from trl import GRPOConfig, GRPOTrainer

Bước 2: Tải mô hình gốc Llama 3.2-1B

pythonmodel, tokenizer = FastLanguageModel.from_pretrained(
model_name="meta-llama/Llama-3.2-1B-Instruct",
max_seq_length=2048,
load_in_4bit=False,
fast_inference=True,
max_lora_rank=64,
gpu_memory_utilization=0.8
)

Bước 3: Cấu hình LoRA

pythonmodel = FastLanguageModel.get_peft_model(
model,
r=64,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
lora_alpha=64,
use_gradient_checkpointing="unsloth",
random_state=3407
)

Lưu ý: LoRA giúp giảm tài nguyên, chỉ tinh chỉnh adapter nhỏ, không phải toàn bộ mô hình.

Bước 4: Chuẩn bị và tiền xử lý dữ liệu

Tải bộ dữ liệu MetaMathQA-40K (tiếng Việt):

python

dataset = load_dataset("5CD-AI/Vietnamese-meta-math-MetaMathQA-40K-gg-translated", split="train")

Trích xuất câu hỏiđáp án từ bộ dữ liệu:

pythonimport re

answer_pattern = re.compile(r"(đáp án là:|câu trả lời là:)\s*(.*)", re.IGNORECASE)
formatted_dataset = []

for item in dataset:
response = item["response_vi"].strip().lower()
match = answer_pattern.search(response)
if match:
answer = match.group(2).strip()
formatted_dataset.append({"question": item["query_vi"], "answer": answer})

Định nghĩa system prompt:

pythonsystem_prompt = """You are given a problem.
Think about the problem and provide your thought process.
Place it between <thinking> and </thinking>.
Then, provide your final answer between <SOLUTION> and </SOLUTION>"""

Chuẩn hóa thành train_dataset:

pythontrain_dataset = Dataset.from_list(formatted_dataset[:8000])
train_dataset = train_dataset.map(lambda x: {
"prompt": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": x["question"]}
],
"answer": x["answer"]
})

Bước 5: Định nghĩa Reward Function

Bạn cần reward cho:

  • Đúng định dạng reasoning + answer,
  • Đúng đáp án cuối cùng.

Ví dụ hàm reward kiểm tra định dạng:

pythondef match_format_exactly(completions, **kwargs):
scores = []
for completion in completions:
response = completion[0]["content"]
if "<thinking>" in response and "</thinking>" in response and "<SOLUTION>" in response and "</SOLUTION>" in response:
scores.append(3.0)
else:
scores.append(0)
return scores

Bước 6: Huấn luyện bằng GRPO

Cấu hình GRPO:

pythontraining_args = GRPOConfig(
learning_rate=5e-6,
weight_decay=5e-4,
warmup_ratio=0.1,
lr_scheduler_type="cosine",
optim="adamw_torch_fused",
logging_steps=1,
per_device_train_batch_size=2,
gradient_accumulation_steps=64,
num_generations=8,
num_train_epochs=1,
save_steps=250,
output_dir="outputs_bz2"
)

Huấn luyện:

pythontrainer = GRPOTrainer(
model=model,
processing_class=tokenizer,
reward_funcs=[match_format_exactly], # có thể thêm reward khác
args=training_args,
train_dataset=train_dataset
)
trainer.train()

Bước 7: Đánh giá và inference mô hình

Lưu adapter LoRA đã tinh chỉnh:

python

model.save_lora("grpo_saved_lora")

Thử chạy một ví dụ:

pythonmessages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": train_dataset[0]["question"]}
]

sampling_params = SamplingParams(temperature=0.8, top_p=0.95, max_tokens=1024)
text = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)

output = model.fast_generate(
[text],
sampling_params=sampling_params,
lora_request=model.load_lora("grpo_saved_lora")
)[0].outputs[0].text

print("Question:", train_dataset[0]["question"])
print("Response:", output)
print("GT Answer:", train_dataset[0]["answer"])

Kỳ vọng: Mô hình sẽ sinh ra chuỗi suy nghĩ hợp lýđáp án đúng như ví dụ:

php-template<thinking>
Reggie đã chi 48 - 38 = 10 đô. 5 cuốn sách → 5x = 10 → x = 2.
</thinking>
<SOLUTION>2</SOLUTION>

Kết luận

Với pipeline 7 bước này, bạn có thể tinh chỉnh một mô hình LLM giải toán tiếng Việt hiệu quả, ít tốn tài nguyên, lại đưa ra lời giải dễ hiểu.
Sự kết hợp LoRA + GRPO không chỉ tiết kiệm chi phí mà còn tăng độ chính xác và tính giải thích được của mô hình.

[+++]

Lưu ý: Bài viết chỉ cung cấp góc nhìn và không phải là lời khuyên đầu tư.

Đọc các Sách chính thống về Blockchain, Bitcoin, Crypto

Combo 5 sách Bitcoin
Combo 5 sách Bitcoin
Để nhận ưu đãi giảm phí giao dịch, đăng ký tài khoản tại các sàn giao dịch sau:

👉 Nếu bạn cần Dịch vụ quảng cáo crypto, liên hệ Click Digital ngay. 🤗

Cảm ơn bạn đã đọc. Chúc bạn đầu tư thành công. 🤗

Giới thiệu token Saigon (SGN):

  • Đầu tư vào các công ty quảng cáo blockchain hàng đầu bằng cách MUA token Saigon (SGN) trên Pancakeswap: https://t.co/KJbk71cFe8/ (đừng lo lắng về tính thanh khoản, hãy trở thành nhà đầu tư sớm)
  • Được hỗ trợ bởi Công ty Click Digital
  • Nâng cao kiến thức về blockchain và crypto
  • Lợi nhuận sẽ dùng để mua lại SGN hoặc đốt bớt nguồn cung SGN để đẩy giá SGN tăng.
  • Địa chỉ token trên mạng BSC: 0xa29c5da6673fd66e96065f44da94e351a3e2af65
  • Twitter X: https://twitter.com/SaigonSGN135/
  • Staking SGN: http://135web.net/

Rate this post

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *