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

Evaluating routing across providers.

Start learning
← Học tăng cường

AI Researcher

Mạng Q sâu

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

Kết hợp Q-Learning với mạng nơ-ron sâu để xử lý không gian trạng thái lớn

lesson120 minHọc tăng cườngAI Researcher

Dự đoán

Atari game Breakout có frame 210×160×3 pixels ≈ 100K giá trị mỗi ảnh. Nếu lưu Q-table cho toàn bộ state khả dĩ thì cần bao nhiêu entries?

Mỗi pixel ∈ {0,...,255} → mỗi state có 256^100000 giá trị khả dĩ. Dù giảm grayscale + 84×84 vẫn là 256^7056 — bất khả thi. DQN dùng CNN để 'học' hàm Q(s, a) thay vì lưu bảng, và chia sẻ tham số giữa state tương tự.

Khoảnh khắc Aha

DQN = Q-Learning + mạng nơ-ron sâu + 2 mẹo quyết định: Experience Replay và Target Network. Ba thành phần này không mới riêng lẻ, nhưng kết hợp lại biến RL từ một đề tài thí nghiệm nhỏ thành hệ thống đánh bại con người trên 49 trò Atari (Mnih et al., Nature 2015). Đây là "AlexNet moment" của RL — mở ra kỷ nguyên Deep Reinforcement Learning.

Thử thách

Replay buffer của bạn chứa 1M transitions. Mỗi bước train trên một mini-batch 32 transitions được sample ngẫu nhiên. Vì sao dùng random thay vì lấy 32 bước mới nhất?

Data từ 1 episode cực kỳ tương quan (agent đi 1 quỹ đạo). Train trực tiếp → bias về experience gần, catastrophic forgetting. Random sampling: mỗi batch có transitions đa dạng từ nhiều episode → gradient ổn định, học đều; đồng thời mỗi transition được tái sử dụng nhiều lần → sample-efficient.

Bạn thấy Q-values tăng không kiểm soát (explode) sau ~1M steps. Diagnosis và fix?

Q explode là triệu chứng kinh điển của moving target kết hợp max bias. Luôn kiểm tra: (1) có target network chưa? (2) C đủ lớn chưa? (3) reward clip? (4) thử Double DQN — trong nhiều game giảm Q value trung bình xuống 30–50% và cải thiện policy.

Mục tiêu của DQN

Deep Q-Network (DQN) xấp xỉ hàm action-value Q(s, a) bằng neural network Q(s, a; θ). Training tối thiểu hoá loss Bellman theo target bootstrap:

L(θ)=E(s,a,r,s′)∼D[(r+γmax⁡a′Q(s′,a′;θ−)−Q(s,a;θ))2]\mathcal{L}(\theta) = \mathbb{E}_{(s, a, r, s') \sim \mathcal{D}}\left[\left(r + \gamma \max_{a'} Q(s', a'; \theta^-) - Q(s, a; \theta)\right)^2\right]

Ở đây θ−\theta^- là tham số target network (bản sao đóng băng), D\mathcal{D} là replay buffer. Gradient:

∇θL=−E[δ⋅∇θQ(s,a;θ)],δ=r+γmax⁡a′Q(s′,a′;θ−)−Q(s,a;θ)\nabla_\theta \mathcal{L} = -\mathbb{E}\left[\delta \cdot \nabla_\theta Q(s, a; \theta)\right], \quad \delta = r + \gamma \max_{a'} Q(s', a'; \theta^-) - Q(s, a; \theta)

Ba thành phần ổn định

Ba thành phần ổn định training:

  1. Experience Replay: buffer cỡ 10⁵–10⁶ lưu transitions; mỗi bước sample mini-batch 32 i.i.d. Ưu điểm: (i) phá tương quan, (ii) tái sử dụng data, (iii) cho phép off-policy update.
  2. Target Network: θ⁻ chỉ copy từ θ mỗi C (10K) bước (hard-update) hoặc soft-update θ−←τθ+(1−τ)θ−\theta^- \leftarrow \tau \theta + (1-\tau) \theta^- với τ = 0.005. Tránh "moving target".
  3. Reward clipping: cắt r về ±1 để gradient có cùng scale giữa các game.

ε-greedy exploration schedule. Thường khởi ε = 1.0, anneal tuyến tính xuống 0.1 trong 1M bước đầu, giữ 0.1 trong testing. Công thức:

Biến thể và giới hạn

εt=max⁡(εmin⁡,ε0−tTanneal)\varepsilon_t = \max\left(\varepsilon_{\min}, \varepsilon_0 - \frac{t}{T_{\text{anneal}}}\right)

Code mẫu

DQN minimal với PyTorch

import random
from collections import deque
from dataclasses import dataclass
from typing import Deque

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np


@dataclass
class Transition:
    s: np.ndarray
    a: int
    r: float
    s_next: np.ndarray
    done: bool


class QNet(nn.Module):
    """MLP Q-network cho state vector nhỏ; đổi thành CNN cho Atari."""

    def __init__(self, state_dim: int, n_actions: int):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(state_dim, 128), nn.ReLU(),
            nn.Linear(128, 128), nn.ReLU(),
            nn.Linear(128, n_actions),
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:  # (B, state_dim) → (B, A)
        return self.net(x)


class ReplayBuffer:
    """Uniform replay buffer — FIFO deque."""

    def __init__(self, capacity: int = 100_000):
        self.buf: Deque[Transition] = deque(maxlen=capacity)

    def push(self, t: Transition) -> None:
        self.buf.append(t)

    def sample(self, batch_size: int) -> list[Transition]:
        return random.sample(self.buf, batch_size)

    def __len__(self) -> int:
        return len(self.buf)


def train_step(
    online: QNet,
    target: QNet,
    opt: torch.optim.Optimizer,
    batch: list[Transition],
    gamma: float = 0.99,
) -> float:
    """Một bước TD-error: minibatch → L2 loss → backward."""
    s = torch.as_tensor(np.stack([t.s for t in batch]), dtype=torch.float32)
    a = torch.as_tensor([t.a for t in batch], dtype=torch.long).unsqueeze(1)
    r = torch.as_tensor([t.r for t in batch], dtype=torch.float32)
    s_next = torch.as_tensor(np.stack([t.s_next for t in batch]), dtype=torch.float32)
    done = torch.as_tensor([t.done for t in batch], dtype=torch.float32)

    # Q(s, a) từ online net
    q_sa = online(s).gather(1, a).squeeze(1)

    # Target: r + gamma * max_a' Q_target(s', a')
    with torch.no_grad():
        max_q_next = target(s_next).max(dim=1).values
        y = r + gamma * max_q_next * (1 - done)

    loss = F.smooth_l1_loss(q_sa, y)  # Huber cho ổn định
    opt.zero_grad()
    loss.backward()
    torch.nn.utils.clip_grad_norm_(online.parameters(), max_norm=10.0)
    opt.step()
    return float(loss.item())


def select_action(q: QNet, s: np.ndarray, eps: float, n_actions: int) -> int:
    if random.random() < eps:
        return random.randrange(n_actions)
    with torch.no_grad():
        qv = q(torch.as_tensor(s, dtype=torch.float32).unsqueeze(0))
    return int(qv.argmax(dim=1).item())

Vòng training DQN đầy đủ với target update & ε-anneal

import gymnasium as gym
import numpy as np
import torch


def run_dqn(
    env_name: str = "CartPole-v1",
    total_steps: int = 200_000,
    batch_size: int = 64,
    buffer_capacity: int = 50_000,
    gamma: float = 0.99,
    lr: float = 1e-3,
    target_update_every: int = 500,
    eps_start: float = 1.0,
    eps_end: float = 0.05,
    eps_decay_steps: int = 50_000,
    warmup: int = 1_000,
    seed: int = 0,
) -> QNet:
    env = gym.make(env_name)
    state_dim = env.observation_space.shape[0]
    n_actions = env.action_space.n

    online = QNet(state_dim, n_actions)
    target = QNet(state_dim, n_actions)
    target.load_state_dict(online.state_dict())
    for p in target.parameters():
        p.requires_grad = False

    opt = torch.optim.Adam(online.parameters(), lr=lr)
    buf = ReplayBuffer(capacity=buffer_capacity)

    s, _ = env.reset(seed=seed)
    episode_return = 0.0
    log = []
    for t in range(total_steps):
        eps = max(
            eps_end,
            eps_start - (eps_start - eps_end) * (t / eps_decay_steps),
        )
        a = select_action(online, s, eps, n_actions)
        s_next, r, terminated, truncated, _ = env.step(a)
        done = terminated or truncated
        buf.push(Transition(s, a, float(r), s_next, bool(done)))
        s = s_next
        episode_return += r

        if len(buf) >= max(batch_size, warmup):
            batch = buf.sample(batch_size)
            loss = train_step(online, target, opt, batch, gamma=gamma)
        else:
            loss = 0.0

        if t % target_update_every == 0 and t > 0:
            # Hard update: copy toàn bộ trọng số
            target.load_state_dict(online.state_dict())

        if done:
            log.append(episode_return)
            episode_return = 0.0
            s, _ = env.reset()
            if len(log) % 20 == 0:
                print(
                    f"step={t:>7d} | eps={eps:.2f} | "
                    f"return(20 ep mean)={np.mean(log[-20:]):.1f}"
                )

    env.close()
    return online


if __name__ == "__main__":
    _ = run_dqn()
    # CartPole-v1 thường đạt return ~500 (max) sau ~50K–100K steps.

Các biến thể hiện đại

Các biến thể hiện đại của DQN. Rainbow DQN (Hessel et al. 2018) tổng hợp 6 cải tiến vào một agent: Double DQN, Dueling, Prioritized Replay, Multi-step learning, Distributional RL (C51), Noisy Networks. Kết quả trên Atari Suite: median human-normalized score cao gấp đôi DQN gốc.

  • Double DQN: sửa overestimation.
  • Dueling DQN: tách V/A.
  • Prioritized Experience Replay: sample theo |TD-error|.
  • Multi-step (n-step) returns: target dùng n-step thay vì 1-step để giảm bias ở early training.
  • C51 / Distributional: học phân phối reward thay vì kỳ vọng — thêm tín hiệu cho network.
  • Noisy Networks: thêm noise vào weights thay vì ε-greedy — exploration theo state.
  • Implicit Quantile Networks (IQN): mở rộng C51 với quantile regression.

Vì sao target network giúp ổn định

Fitted Q-Iteration cổ điển (Riedmiller 2005) xem mỗi lần cập nhật là một phép regress: với target yi = r i + γ·max Q(s′i, a′; θold), huấn luyện θnew ← argmin Σ(Q(si, a i; θ) − yi)². Nếu giữ θold cố định trong một số bước, bài toán trở thành regression tĩnh với target cố định → hội tụ như supervised learning.

DQN "gần đúng" chiến lược này bằng target network cập nhật mỗi C bước. Nếu C quá nhỏ, ta gần với TD online (θ- = θ) — moving target, dao động. Nếu C quá lớn, target lỗi thời → học chậm. Thực nghiệm: C = 10K bước là sweet spot cho Atari.

Soft-update (Lillicrap et al. 2016, DDPG) là biến thể: θ- ← τθ + (1 − τ)θ- mỗi bước với τ ≈ 0.005. Ưu điểm: smoother, thường ổn định hơn hard update cho continuous control.

Lỗi thường gặp và hyperparameter

  • Quên no_grad trên target: target net vẫn tính gradient → memory leak và học sai.
  • Sample từ buffer trống: gọi sample khi len(buf) < batch_size → crash; dùng warmup steps.
  • Không normalise state: pixel 0–255 hoặc feature không cùng scale → gradient bất ổn.
  • Target update quá thường xuyên: C quá nhỏ → oscillation. Quá lớn → hội tụ chậm.
  • Reward không clip: game có reward rất lớn (Frostbite +200) → Q values explode.
  • ε decay quá nhanh: agent chưa đủ explore → mắc kẹt local policy.
  • Buffer quá nhỏ: correlation vẫn cao, training dao động.
  • Không gradient clip: TD error có thể rất lớn ở early training → exploding gradient.
  • Dùng MSE thay vì Huber: outlier lớn (do bootstrap) làm loss nổ.
  • Không track running returns: khó biết agent có tiến bộ không — luôn log return trung bình 100 episode gần nhất.

Một ghi chú thực tế: training DQN trên Atari cần 1–2 tuần GPU đơn thời 2015 (theo nguồn bài, chưa kiểm chứng). Với TPU/multi-GPU ngày nay, Rainbow có thể hoàn thành trong vài giờ — nhưng pipeline cơ bản vẫn giống hệt.

Bảng hyperparameter tham khảo (Atari DQN, Mnih 2015)

  • Buffer capacity: 1,000,000 transitions (≈ 4–8 GB RAM)
  • Batch size: 32
  • Target update: mỗi 10,000 gradient steps (hard update)
  • Discount γ: 0.99 — ưu tiên reward dài hạn, ngưỡng ổn định
  • Optimizer: RMSProp (lr 2.5e-4, momentum 0.95) — hoặc Adam với lr 1e-4 cho implementation hiện đại
  • ε schedule: 1.0 → 0.1 trong 1M bước; eval với ε = 0.05
  • Frame-skip: 4 (agent quan sát mỗi 4 frame)
  • Frame-stack: 4 (input CNN = [4, 84, 84])
  • Reward clip: sign(r) ∈ {−1, 0, +1}
  • Gradient clip: norm ≤ 10
  • Warm-up: 50,000 bước thuần random trước khi học
  • Tổng bước training: ~50M frames (~200M steps)

Liên hệ với Q-Learning và policy gradient

DQN là nền tảng để bước sang Actor-Critic và policy gradient cho không gian action liên tục. Ôn lại nền tảng ở Q-Learning và MLP nếu cần.

Tại sao off-policy lại quan trọng? DQN có thể học từ transitions được sinh ra bởi policy cũ hoặc cả policy ngẫu nhiên. Điều này cho phép: (1) tái sử dụng buffer khi policy thay đổi, (2) học từ demonstration (DQfD — Deep Q-learning from Demonstrations), (3) offline RL (học hoàn toàn từ dataset cố định, không tương tác môi trường). Các phương pháp on-policy như A2C/PPO không có lợi thế này.

Liên hệ với Q-Learning cổ điển. DQN không phải là một thuật toán mới hoàn toàn — nó thực chất là Q-Learning với 3 thay đổi kỹ thuật: (1) hàm Q được tham số hoá, (2) cập nhật bằng gradient thay vì look-up, (3) dữ liệu được lưu và tái sử dụng. Cốt lõi vẫn là phương trình Bellman optimality Q*(s, a) = 𝔼[r + γ max Q*(s′, a′)]. Hiểu Q-learning là điều kiện tiên quyết để hiểu DQN.

Tóm tắt

  • DQN = Q-Learning + neural network tham số hoá Q(s, a; θ). Xử lý được state lớn (pixels Atari) mà Q-table không thể lưu nổi.
  • Experience Replay: buffer 1M transitions, sample mini-batch ngẫu nhiên để phá tương quan thời gian, tái sử dụng data, ổn định gradient.
  • Target Network: bản sao đóng băng θ⁻, cập nhật mỗi C=10K bước (hoặc soft-update τ=0.005). Tránh moving target khi bootstrap TD.
  • Double DQN sửa overestimation do max bias: online net chọn action, target net đánh giá giá trị. Dueling DQN tách Q = V + A.
  • Rainbow DQN gộp 6 cải tiến: Double, Dueling, Prioritized Replay, Multi-step, C51, Noisy Nets — score Atari gấp đôi DQN gốc.
  • Dấu ấn lịch sử: DQN (DeepMind 2015) đánh bại người chơi ở 49 game Atari — 'AlexNet moment' của RL, khởi đầu kỷ nguyên Deep RL.

Continue the module

Lesson 3 of 5