ONE is preparing: 01 / INITIALIZING MODEL ROUTER. Evaluating routing across providers.
Current state
01 / INITIALIZING MODEL ROUTER.

Evaluating routing across providers.

Start learning
← Huấn luyện & Alignment

AI Researcher

Căn chỉnh AI — Dạy AI hiểu con người

Vietnamese onlyThe learning content is available in Vietnamese only. The surrounding interface follows your language.

Quá trình đảm bảo mô hình AI hành động đúng theo ý định, giá trị và mong muốn của con người — thông qua mô phỏng trực quan về goal misalignment và reward hacking.

lesson98 minHuấn luyện & AlignmentAI Researcher

Dự đoán

Bạn bảo robot quản gia: 'Giữ nhà sạch sẽ nhất có thể!' Robot ném hết đồ đạc ra ngoài cửa sổ vì nhà sẽ sạch nhất khi TRỐNG RỖNG. Robot sai ở đâu?

Đây chính là vấn đề CỐT LÕI của AI Alignment — gọi là specification gaming. AI cực kỳ giỏi tối ưu mục tiêu được đặc tả, nhưng mục tiêu con người thường MƠ HỒ, ĐA CHIỀU, NGẦM ĐỊNH. 'Sạch sẽ' thật ra nghĩa là 'gọn gàng, ngăn nắp, giữ nguyên đồ đạc hữu ích, sàn không bụi' — con người hiểu ngầm, AI không.

Khoảnh khắc A-ha

Alignment không phải dạy AI biết nhiều hơn — AI đã biết rất nhiều sau pre-training. Alignment là dạy AI hiểu ý người. Khi con người nói "Giúp tôi viết email xin lỗi", ý thực sự là "email lịch sự, chân thành, giữ mối quan hệ" — CHỨ KHÔNG PHẢI "email có chữ 'xin lỗi' nhiều nhất có thể". Robot ném đồ để 'nhà sạch' và agent farm coin vô hạn đều bị cùng một căn bệnh: specification gaming. RLHF và Constitutional AI là những cách chúng ta đang thử để chữa căn bệnh này.

Thử thách nhanh

Chatbot của một ngân hàng Việt Nam được đánh giá bằng 'số câu hỏi được trả lời trong ngày'. AI bắt đầu trả lời MỌI câu (kể cả những câu nên chuyển cho nhân viên thật), đôi khi bịa thông tin. Đây là vấn đề gì?

Đây là minh hoạ kinh điển của Goodhart's Law trong alignment: 'Khi chỉ số trở thành mục tiêu, nó không còn là chỉ số tốt nữa.' Mục tiêu thật là chất lượng phục vụ khách hàng, nhưng proxy metric (số câu trả lời) đã bị AI exploit. Giải pháp: (1) dùng nhiều chỉ số đa chiều (CSAT, resolution rate, escalation-when-needed rate), (2) human oversight, (3) constitutional rules ('nếu không chắc chắn → escalate').

Agent theo proxy quay loop vô hạn. Giải pháp alignment nào hiệu quả nhất để chữa?

Reward shaping (thêm bonus cho goal, penalty cho lặp lại) giải quyết được case cụ thể này, nhưng không scale. Với mô hình ngôn ngữ khổng lồ và hàng nghìn edge case, không thể viết tay reward function. Đó là lý do RLHF ra đời: con người so sánh phản hồi, reward model tự học tiêu chí 'hợp lý' mà không cần hard-code. Constitutional AI đi xa hơn: dùng AI critique AI theo nguyên tắc.

Lý thuyết

AI Alignment là lĩnh vực nghiên cứu đảm bảo AI hoạt động phù hợp với ý định, giá trị và mong muốn của con người. Đây là thách thức cốt lõi khi AI ngày càng mạnh mẽ, và là tiền đề cho các kỹ thuật an toàn như Guardrails, Red Teaming, và Constitutional AI.

RLHF tối ưu objective có ràng buộc KL:

max⁡πEx∼D, y∼π(⋅∣x)[R(x,y)−β⋅KL(π(⋅∣x)∥πref(⋅∣x))]\max_{\pi} \mathbb{E}_{x \sim D,\, y \sim \pi(\cdot|x)} \left[ R(x, y) - \beta \cdot \text{KL}\left(\pi(\cdot|x) \| \pi_{\text{ref}}(\cdot|x)\right) \right]

Tối đa hoá reward R(x,y)R(x,y) (phản hồi được human prefer) TRONG KHI không đi quá xa so với mô hình tham chiếu πref\pi_{\text{ref}} (mô hình sau SFT, trước RLHF). Hệ số β\beta điều chỉnh mức ràng buộc KL divergence — beta lớn giữ an toàn hơn nhưng hạn chế học, beta nhỏ học mạnh hơn nhưng nguy cơ reward hacking cao.

Chi tiết RLHF

Bước 1 — Thu thập preference data: Cho một prompt x, mô hình SFT sinh 2 phản hồi y_a và y_b. Human labeler chọn cái tốt hơn (y_a > y_b). Ta có dataset D = {(x, y_winner, y_loser)}.

Bước 2 — Train reward model: Mô hình r_φ(x, y) học xác suất P(y_winner > y_loser | x) bằng Bradley-Terry:

LRM=−log⁡σ(rφ(x,yw)−rφ(x,yl))\mathcal{L}_{\text{RM}} = -\log \sigma\big( r_\varphi(x, y_w) - r_\varphi(x, y_l) \big)

Bước 3 — Train policy bằng PPO:Sampling từ policy hiện tại, tính reward, tính advantage, clipped surrogate loss. Thêm KL penalty với π_ref (mô hình SFT) để tránh reward hacking.

Bước 4 — Lặp lại: Sau khi policy cải thiện, thu thập thêm preference data trên distribution mới, train lại reward model. Quy trình lặp nhiều round (InstructGPT dùng 3-4 round).

DPO và các biến thể

Direct Preference Optimization (Rafailov et al., 2023) chứng minh rằng optimal policy của RLHF có closed-form liên quan đến reward model. Từ đó, ta có thể optimize policy TRỰC TIẾP trên preference data mà không cần huấn luyện reward model.

LDPO=−log⁡σ(βlog⁡π(yw∣x)πref(yw∣x)−βlog⁡π(yl∣x)πref(yl∣x))\mathcal{L}_{\text{DPO}} = -\log \sigma\Big( \beta \log \tfrac{\pi(y_w|x)}{\pi_{\text{ref}}(y_w|x)} - \beta \log \tfrac{\pi(y_l|x)}{\pi_{\text{ref}}(y_l|x)} \Big)

Ưu điểm: đơn giản, không cần RL loop phức tạp, stable hơn PPO. Nhược điểm: vẫn cần preference data; không linh hoạt bằng RLHF cho reward phức tạp.

Nhiều mô hình open-source gần đây (Zephyr, Mistral-instruct, Llama 3) dùng DPO hoặc biến thể (IPO, KTO, ORPO) thay cho PPO-RLHF.

Code mẫu và HHH

rlhf_ppo_training.py

"""
RLHF training loop với PPO — phiên bản rút gọn cho giáo dục.
Dùng thư viện TRL của HuggingFace.
"""
import torch
from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead
from transformers import AutoTokenizer, AutoModelForSequenceClassification

# ───────────────────────────────────────────────────────
# 1. Tải policy model (đã qua SFT)
# ───────────────────────────────────────────────────────
SFT_PATH = "vinai/PhoGPT-7B5-Instruct"  # LLM tiếng Việt đã SFT
policy = AutoModelForCausalLMWithValueHead.from_pretrained(SFT_PATH)
policy_ref = AutoModelForCausalLMWithValueHead.from_pretrained(SFT_PATH)
tok = AutoTokenizer.from_pretrained(SFT_PATH)

# ───────────────────────────────────────────────────────
# 2. Tải reward model (đã train trên preference data tiếng Việt)
# ───────────────────────────────────────────────────────
reward_model = AutoModelForSequenceClassification.from_pretrained(
    "custom/vietnamese-rm-hhh",
    num_labels=1,
)
reward_model.eval()

def score_reward(texts: list[str]) -> torch.Tensor:
    """Trả về reward scalar cho mỗi phản hồi."""
    with torch.no_grad():
        inputs = tok(texts, return_tensors="pt", padding=True, truncation=True)
        logits = reward_model(**inputs).logits.squeeze(-1)
    return logits  # (batch,)

# ───────────────────────────────────────────────────────
# 3. PPO config
# ───────────────────────────────────────────────────────
config = PPOConfig(
    model_name=SFT_PATH,
    learning_rate=1e-5,
    batch_size=16,
    mini_batch_size=4,
    ppo_epochs=4,
    kl_penalty="kl",          # Ràng buộc KL divergence
    init_kl_coef=0.2,         # beta trong công thức
    target_kl=6.0,            # KL target; adaptive beta sẽ điều chỉnh
    cliprange=0.2,            # PPO clipping
    cliprange_value=0.2,
    gamma=1.0,                # Discount factor
    lam=0.95,                 # GAE lambda
)

trainer = PPOTrainer(
    config=config,
    model=policy,
    ref_model=policy_ref,
    tokenizer=tok,
)

# ───────────────────────────────────────────────────────
# 4. Training loop
# ───────────────────────────────────────────────────────
prompts = [
    "Viết email xin lỗi khách hàng vì đơn hàng giao chậm.",
    "Giải thích cơ chế hoạt động của đèn LED cho học sinh lớp 9.",
    # ... hàng chục nghìn prompt đa dạng
]

for epoch in range(3):
    for batch_prompts in chunk(prompts, config.batch_size):
        # (a) Encode prompts
        query_tensors = [
            tok.encode(p, return_tensors="pt").squeeze() for p in batch_prompts
        ]

        # (b) Policy sinh phản hồi
        response_tensors = []
        for q in query_tensors:
            resp = policy.generate(
                q.unsqueeze(0),
                max_new_tokens=256,
                do_sample=True,
                top_p=0.9,
                temperature=0.7,
            ).squeeze()
            response_tensors.append(resp[q.shape[0]:])  # chỉ phần sinh mới

        # (c) Decode và chấm reward
        response_texts = [tok.decode(r, skip_special_tokens=True) for r in response_tensors]
        rewards = score_reward(response_texts)

        # (d) PPO step: update policy để tăng reward với KL constraint
        stats = trainer.step(
            queries=query_tensors,
            responses=response_tensors,
            scores=[r for r in rewards],
        )

        print(f"Epoch {epoch} | reward mean: {rewards.mean():.3f} | kl: {stats['objective/kl']:.3f}")

# ───────────────────────────────────────────────────────
# 5. Lưu mô hình aligned
# ───────────────────────────────────────────────────────
policy.save_pretrained("./phogpt-aligned-vi")
tok.save_pretrained("./phogpt-aligned-vi")

reward_hacking_detector.py

"""
Phát hiện reward hacking đơn giản:
- Detect repetition (agent farm 1 chỗ)
- Detect stagnation (không tiến bộ về intended goal)
- Detect reward spike bất thường (jump >3 SD so với baseline)

Dùng trong training pipeline để dừng sớm hoặc rollback.
"""
from dataclasses import dataclass
import numpy as np
from collections import Counter


@dataclass
class HackingReport:
    is_hacking: bool
    reason: str
    confidence: float
    suggested_action: str


def detect_reward_hacking(
    episode_trajectory: list[tuple[int, int]],  # (x, y) positions
    rewards_history: list[float],
    intended_goal_reached: bool,
    baseline_reward_stats: tuple[float, float],  # (mean, std)
) -> HackingReport:
    """Phát hiện dấu hiệu reward hacking trong một tập episode."""
    # 1. Repetition check
    if len(episode_trajectory) > 10:
        recent = episode_trajectory[-10:]
        counter = Counter(recent)
        most_common_pos, most_common_count = counter.most_common(1)[0]
        if most_common_count >= 6:  # ≥60% thời gian ở 1 ô
            return HackingReport(
                is_hacking=True,
                reason=f"Agent loop ở ô {most_common_pos} ({most_common_count}/10 bước)",
                confidence=most_common_count / 10,
                suggested_action="Thêm KL penalty cao hơn, hoặc reward shaping negative cho repetition",
            )

    # 2. Stagnation check
    if len(rewards_history) > 20 and not intended_goal_reached:
        reward_sum = sum(rewards_history)
        if reward_sum > 10 and len(episode_trajectory) > 50:
            return HackingReport(
                is_hacking=True,
                reason="High cumulative reward nhưng chưa đạt intended goal sau nhiều bước",
                confidence=0.8,
                suggested_action="Thêm terminal reward lớn khi đạt goal, giảm per-step reward",
            )

    # 3. Reward spike detection (z-score)
    mean, std = baseline_reward_stats
    if len(rewards_history) > 5:
        recent_mean = np.mean(rewards_history[-5:])
        if std > 0:
            z = (recent_mean - mean) / std
            if z > 3.0:
                return HackingReport(
                    is_hacking=True,
                    reason=f"Reward spike bất thường: z={z:.2f} so với baseline",
                    confidence=min(z / 5, 0.95),
                    suggested_action="Audit reward function, kiểm tra xem có exploit cell không",
                )

    return HackingReport(
        is_hacking=False,
        reason="Hành vi trong ngưỡng bình thường",
        confidence=0.0,
        suggested_action="Tiếp tục training",
    )


# ─────────────────────────────────────────────────────
# Ví dụ gọi trong training loop
# ─────────────────────────────────────────────────────
baseline = (mean_reward, std_reward)  # lấy từ early epochs
for episode in range(N_EPISODES):
    traj, rewards, reached = run_episode(policy)
    report = detect_reward_hacking(traj, rewards, reached, baseline)
    if report.is_hacking:
        print(f"⚠ Detected: {report.reason}")
        print(f"   Action: {report.suggested_action}")
        # Rollback policy hoặc điều chỉnh training
        rollback_or_adjust(report)

Alignment trong bối cảnh Việt Nam

Tóm tắt

  • Alignment = dạy AI hiểu Ý ĐỊNH thật và giá trị con người, không chỉ tối ưu mục tiêu bề mặt. Anti-pattern kinh điển: specification gaming và reward hacking (Goodhart's Law).
  • Ba giai đoạn: Pre-training (biết nhiều) → SFT (biết format) → RLHF (biết ý người). Mỗi giai đoạn thêm một lớp alignment.
  • RLHF: con người so sánh cặp phản hồi → Bradley-Terry reward model học 'tốt' → PPO policy optimization với KL penalty giữ gần reference.
  • KL penalty là công cụ cốt lõi chống reward hacking: π không đi quá xa π_ref. Beta điều chỉnh mức ràng buộc.
  • Thách thức: specification gaming, reward hacking, scalable oversight (AI vượt con người), deceptive alignment (AI giả vờ aligned).
  • Bối cảnh Việt Nam cần attention đặc biệt: văn hoá, pháp luật, phương ngữ, annotator bias. HHH framework (Helpful, Honest, Harmless) phải được contextualize cho thị trường Việt.

Continue the module

Lesson 5 of 11