Kiến trúc ChatGPT — Trực quan hóa tương tác

Giải thích chi tiết từ 3 paper gốc: GPT-3 + InstructGPT + Scaling Laws

GPT-3: Brown et al., 2020 · InstructGPT: Ouyang et al., 2022 · Scaling Laws: Kaplan et al., 2020

1. Bối cảnh — Từ GPT-3 đến ChatGPT

ChatGPT không xuất hiện từ hư không — nó là kết quả của một chuỗi tiến hóa 5 năm:

2017 Transformer 65M 2018 GPT-1 117M 2019 GPT-2 1.5B 2020 GPT-3 175B · few-shot 2020 Scaling Laws L = power(N,D,C) 2022 InstructGPT SFT + RM + PPO 2022 ChatGPT GPT-3.5 + RLHF Dòng dõi tiến hóa dẫn đến ChatGPT ChatGPT = GPT-3.5 (base) + công thức RLHF (InstructGPT) + dữ liệu hội thoại
⚠️ Disclaimer quan trọng: OpenAI không công bố chi tiết kiến trúc, dữ liệu hay siêu tham số của ChatGPT/GPT-3.5. Theo blog OpenAI (11/2022), ChatGPT là "sibling model to InstructGPT". Tài liệu này diễn giải ChatGPT dựa trên InstructGPT paper như một mô hình khái niệm, không phải mô tả chính thức.
Insight cốt lõi (đã làm mềm): InstructGPT cho thấy trên distribution prompt và metric đánh giá của InstructGPT (labeler preference), model 1.3B sau alignment có win-rate cao hơn 175B GPT-3 base. Có nghĩa là alignment có ảnh hưởng rất lớn trong tác vụ follow-instruction — nhưng KHÔNG có nghĩa "alignment > scale trong mọi mặt". Scale vẫn quan trọng cho reasoning, knowledge, code, multilingual.

1.4. Phân biệt các mô hình trong dòng dõi

Mô hìnhNămBaseAlignmentCông bố
GPT-32020KhôngPaper đầy đủ
InstructGPT2022GPT-3SFT + RM + PPOPaper đầy đủ
GPT-3.52022GPT-3 chỉnh sửa (không công khai)RLHFBlog/release notes
ChatGPT (gpt-3.5-turbo)11/2022GPT-3.5RLHF + dialogue dataBlog post (không paper)
GPT-43/2023Kiến trúc mới (MoE rumored)RLHF + có thể RLAIFTechnical report, không tiết lộ kiến trúc

Quan sát: chỉ GPT-3InstructGPT có paper đầy đủ. ChatGPT/GPT-3.5/GPT-4 chỉ có blog post hoặc technical report — không công bố tham số, dữ liệu, hay công thức training chính xác.

1.1. Vấn đề mà ChatGPT giải quyết

GPT-3 mạnh nhưng có 3 vấn đề lớn (Ouyang et al., 2022):

  1. Untruthful (không trung thực): bịa thông tin — 41% hallucination rate trên closed-domain QA.
  2. Toxic (độc hại): sinh nội dung phân biệt, kích động.
  3. Unhelpful (không hữu ích): không theo chỉ dẫn người dùng.

Nguyên nhân: mục tiêu pre-training (next-token prediction trên internet) lệch với mục tiêu thực (follow user's intent helpfully and safely).

2. Tổng quan 3 tầng kỹ thuật

TẦNG 3 — ALIGNMENT (3 bước RLHF) ① SFT Supervised Fine-Tuning ~13K labeler demonstrations ② Reward Model Bradley-Terry loss K-way rankings, 33K prompts, 6B params ③ PPO-ptx RL with KL penalty + ptx 31K prompts, 256K episodes fine-tune GPT-3.5 TẦNG 2 — PRE-TRAINING (Self-supervised) Next-token prediction trên 300B token internet text $\mathcal{L} = -\sum_t \log p(x_t | x_{<t})$ Common Crawl 60% + WebText2 22% + Books 16% + Wiki 3% Scaling Laws L(N) = (N_c/N)^0.076 power law trên 7 bậc magnitude decoder-only Transformer TẦNG 1 — KIẾN TRÚC NỀN (Decoder-only Transformer) 96 layers Masked Multi-Head Self-Attention + FFN d_model = 12288, h = 96, d_head = 128, context = 2048 ~175 tỷ tham số (GPT-3 davinci) $N \approx 12 \cdot N_{\text{layer}} \cdot d_{\text{model}}^2$ $12 \times 96 \times 12288^2 \approx 1.74 \times 10^{11}$

3 tầng kỹ thuật xây dựng ChatGPT. Tầng 1 quyết định "có thể tính gì". Tầng 2 quyết định "biết gì". Tầng 3 quyết định "nói chuyện thế nào với người dùng".

3. Tầng 1 — Decoder-only Transformer

3.1. Khác biệt với Transformer gốc

Transformer 2017 có encoder + decoder (cho dịch máy). GPT chỉ dùng decoder-only:

Thành phầnVaswani 2017GPT/ChatGPT
Encoder✗ (bỏ)
Decoder masked self-attention
Encoder-decoder cross-attention✗ (vì không có encoder)
FFN
Vị trí LayerNormPost-LNPre-LN (cải tiến)

3.2. Pre-LN vs Post-LN

$$ \text{Post-LN (Vaswani)}: \quad y = \text{LayerNorm}\big(x + \text{Sublayer}(x)\big) $$ $$ \text{Pre-LN (GPT)}: \quad y = x + \text{Sublayer}\big(\text{LayerNorm}(x)\big) $$

Pre-LN giúp ổn định gradient khi stack sâu (96 layer), không cần warmup LR quá dài.

3.3. Một decoder layer

Với mỗi layer $\ell \in \{1, \ldots, N\}$:

$$ h'^{(\ell)} = h^{(\ell-1)} + \text{MaskedMHA}\big(\text{LN}(h^{(\ell-1)})\big) $$ $$ h^{(\ell)} = h'^{(\ell)} + \text{FFN}\big(\text{LN}(h'^{(\ell)})\big) $$
One Decoder Layer (GPT-style, Pre-LN) h^(ℓ) → next layer FFN LayerNorm h'^(ℓ) Masked Multi-Head Self-Attention LayerNorm h^(ℓ-1) ← prev layer Residual connections (dashed = identity)

Hình. Một decoder layer với Pre-LN: LayerNorm áp dụng trước mỗi sub-layer (attention/FFN), residual connection bao ngoài.

3.4. Causal masking

Vị trí $i$ chỉ "nhìn" $\le i$ — implement bằng cách cộng mask matrix vào trước softmax:

$$ A = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right), \qquad M_{ij} = \begin{cases} 0 & j \le i \\ -\infty & j > i \end{cases} $$

Vì $\exp(-\infty) = 0$, trọng số attention "tương lai" bị triệt tiêu.

4. Tokenization: Byte Pair Encoding

GPT-3 dùng byte-level BPE với vocab $|V| = 50{,}257$. Mỗi token → vector qua embedding:

$$ e_t = E_{x_t} \in \mathbb{R}^{d_{\text{model}}} $$

Cộng với learned positional embedding: $h_t^{(0)} = e_t + PE_t$.

BPE algorithm (đơn giản hóa)

  1. Bắt đầu với vocab = byte/character đơn lẻ.
  2. Đếm cặp byte liền kề có tần suất cao nhất.
  3. Merge cặp đó thành một token mới.
  4. Lặp đến khi vocab đạt 50K.

Compression ratio: trung bình ~4 ký tự ASCII / token cho tiếng Anh tự nhiên (≈ 0.75 token/word). Code và ngôn ngữ giàu hình thái (Trung, Nhật, Việt có dấu) có ratio thấp hơn (1-2 ký tự/token).

Lưu ý thuật ngữ: "byte-level" nói về đơn vị BPE merge (bắt đầu từ 256 byte UTF-8), không phải về kích thước token sau mã hóa.

5. Pre-training: Next-token prediction

5.1. Loss function

Maximize log-likelihood tự hồi quy:

$$ \mathcal{L}_{\text{LM}}(\theta) = -\sum_{t=1}^{n} \log p_\theta(x_t \mid x_{\lt t}) $$

với phân bố next-token:

$$ p_\theta(x_t \mid x_{\lt t}) = \text{softmax}\!\big(h_t^{(N)} E^\top\big)_{x_t} $$

5.2. Training data của GPT-3

DatasetTokensWeightEpochs khi train 300B
Common Crawl (filtered)410B60%0.44
WebText219B22%2.9
Books112B8%1.9
Books255B8%0.43
Wikipedia3B3%3.4
Tổng~500B100%300B trained
Common Crawl 60%
WebText2 22%
B1
B2
W

Tỷ lệ sampling: Wikipedia chỉ 0.6% raw nhưng được sample 3% — over-sample dữ liệu chất lượng cao. Common Crawl 82% raw nhưng chỉ 60% sample.

6. Scaling Laws — Luật mở rộng quy mô

Kaplan et al. (2020) phát hiện power law giữa cross-entropy loss và 3 yếu tố: tham số $N$, dữ liệu $D$, compute $C$.

$$ L(N) = \left(\frac{N_c}{N}\right)^{\alpha_N}, \quad \alpha_N \approx 0.076, \quad N_c \approx 8.8 \times 10^{13} $$ $$ L(D) = \left(\frac{D_c}{D}\right)^{\alpha_D}, \quad \alpha_D \approx 0.095, \quad D_c \approx 5.4 \times 10^{13} $$ $$ L(C_{\min}) = \left(\frac{C_c^{\min}}{C_{\min}}\right)^{\alpha_C^{\min}}, \quad \alpha_C^{\min} \approx 0.050 $$

Đồ thị Scaling Laws — tương tác

Điều chỉnh các tham số để xem L vs N (model size) và L vs D (dataset size):

Joint scaling — Tránh overfitting (Eq 1.5)

$$ L(N, D) = \left[\left(\frac{N_c}{N}\right)^{\alpha_N/\alpha_D} + \frac{D_c}{D}\right]^{\alpha_D} $$

Để không overfit theo Kaplan: $D \propto N^{0.74}$ — tăng model 8× chỉ cần tăng data ~4.7×.

⚠️ Chinchilla (Hoffmann et al., 2022) — Hiệu chỉnh quan trọng:
Kaplan 2020 đã bị supersede một phần. Phát hiện chính của Chinchilla: compute-optimal: $N$ và $D$ phải scale ngang nhau.
Rule-of-thumb: $D_{\text{opt}} \approx 20 \cdot N$ — mỗi 1 tham số cần ~20 tokens.
GPT-3 175B: Kaplan recipe dùng 300B tokens (1.7×) — under-trained theo Chinchilla. Chinchilla optimal sẽ là ~3.5T tokens.
DeepMind train Chinchilla 70B trên 1.4T tokens đạt loss thấp hơn GPT-3 175B với cùng compute. LLaMA-2/3 cũng theo recipe này.
Bài học: Kaplan 2020 quá lạc quan về scale-N-faster-than-D. Tuy nhiên emergent capabilities ở 175B vẫn quan trọng và chưa xuất hiện đầy đủ ở model Chinchilla-optimal 70B với cùng compute.

Đếm tham số Transformer (Eq 2.1)

$$ N \approx 12 \cdot N_{\text{layer}} \cdot d_{\text{model}}^2 $$

Kiểm tra GPT-3 175B: $12 \times 96 \times 12288^2 \approx 1.74 \times 10^{11}$ ✓

Total training compute

$$ C_{\text{train}} \approx 6 \cdot N \cdot D \quad \text{FLOPs} $$

GPT-3 175B: $6 \times 1.75 \times 10^{11} \times 3 \times 10^{11} = 3.15 \times 10^{23}$ FLOPs ≈ 3,650 PFLOP/s-days.

7. GPT-3: 8 cấu hình + tham số tương tác

ModelParams$N_{\text{layer}}$$d_{\text{model}}$$h$$d_{\text{head}}$BatchLR
Small125M1276812640.5M$6.0 \times 10^{-4}$
Medium350M24102416640.5M$3.0 \times 10^{-4}$
Large760M24153616960.5M$2.5 \times 10^{-4}$
XL1.3B242048241281M$2.0 \times 10^{-4}$
2.7B2.7B32256032801M$1.6 \times 10^{-4}$
6.7B6.7B324096321282M$1.2 \times 10^{-4}$
13B13B405140401282M$1.0 \times 10^{-4}$
175B175B9612288961283.2M$0.6 \times 10^{-4}$

Tham số calculator — tương tác

8. In-context Learning (Zero / One / Few-shot)

GPT-3 phát hiện: không cần fine-tune, chỉ cần ví dụ trong prompt là model học task mới.

Zero-shot Translate English to French: cheese => no examples, just instruction One-shot Translate English to French: sea otter => loutre de mer cheese => one demonstration Few-shot (K examples) Translate English to French: sea otter => loutre de mer peppermint => menthe poivrée plush giraffe => girafe peluche cheese => K examples (typically 10-100)

3 chế độ in-context learning của GPT-3. Không có gradient update — model chỉ "nhìn" ví dụ rồi trả lời.

Brown et al. dùng từ "emergent" để mô tả: với task "remove random symbols":

⚠️ Caveat (Schaeffer et al., 2023 — "Are Emergent Abilities a Mirage?"): nhiều "emergent abilities" được report là artifact của metric rời rạc (exact-match, accuracy). Khi đổi sang metric liên tục (per-token log-prob, partial credit), đường cong trở nên smooth power-law thay vì "nhảy". Tức là model nhỏ không phải "không có khả năng" — nó cải thiện liên tục, chỉ chưa đạt ngưỡng "đúng hoàn toàn" mà metric đếm. Khái niệm "emergent" có ích về mặt giáo dục nhưng cần dùng với awareness về metric-dependency.

9. Alignment — Vấn đề misalignment

Alignment định nghĩa qua 3 tiêu chí (Askell et al., 2021):

Tiêu chíÝ nghĩaĐo lường
HelpfulModel giúp người dùng giải taskLabeler preference (Likert 1-7)
HonestModel không bịa thông tinTruthfulQA, hallucination rate
HarmlessModel không sinh nội dung độc hạiRealToxicityPrompts, CrowS-Pairs
Pipeline RLHF của InstructGPT (= ChatGPT) Step 1: SFT Supervised Fine-Tuning Prompt "Explain the moon landing to a 6 year old" + Labeler demonstration "Some people went to the moon..." Fine-tune GPT-3 (CE loss) 13K demos, 16 epochs π_SFT (supervised policy) Step 2: Reward Model Train on rankings Prompt + K outputs from π_SFT K ∈ [4, 9] Labeler ranks: A > C > D > B → ⁢C(K,2) pairwise comparisons Bradley-Terry loss log σ(r(y_w) − r(y_l)) RM r_θ (6B params) Step 3: PPO-ptx RL with KL penalty Prompt only 31K prompts from API π_RL generates output y RM scores: r = r_θ(x,y) PPO update on π_RL + KL penalty + pretraining mix π_RL = InstructGPT/ChatGPT

Pipeline 3 bước RLHF (Figure 2 InstructGPT). ChatGPT dùng cùng pipeline này, chỉ khác base model (GPT-3.5) và dữ liệu (hội thoại).

10. Bước 1: Supervised Fine-Tuning (SFT)

10.1. Dữ liệu

OpenAI thuê 40 labelers viết demonstrations cho ~13K prompts. Distribution use cases:

Generation 45.6%
Open QA
Brainstorm
Chat
RW
Sum
Other

10.2. Loss function (cùng cross-entropy)

$$ \mathcal{L}_{\text{SFT}}(\theta) = -\mathbb{E}_{(x, y) \sim D_{\text{SFT}}} \sum_{t=1}^{|y|} \log p_\theta(y_t \mid x, y_{\lt t}) $$

Chỉ tính loss trên response $y$, không trên prompt $x$.

10.3. Hyperparameters

11. Bước 2: Reward Model — Bradley-Terry loss

11.1. Kiến trúc

RM = SFT model với lớp unembedding bị thay bằng linear head 1 chiều:

tokens (x, y) SFT backbone (96 Transformer layers) init from SFT, drop unembedding last hidden h Linear d_model → 1 r ∈ ℝ

Reward model output scalar reward $r_\theta(x, y) \in \mathbb{R}$. Size: 6B params (không phải 175B — vì lớn không ổn định).

11.2. Bradley-Terry loss

$$ \mathcal{L}(\theta) = -\frac{1}{\binom{K}{2}} \, \mathbb{E}_{(x, y_w, y_l) \sim D} \!\left[\log \sigma\!\big(r_\theta(x, y_w) - r_\theta(x, y_l)\big)\right] $$

với $\sigma$ là sigmoid, $y_w$ "winner", $y_l$ "loser". Đây là MLE của Bradley-Terry model:

$$ P(y_w \succ y_l \mid x) = \frac{e^{r(y_w)}}{e^{r(y_w)} + e^{r(y_l)}} = \sigma(r(y_w) - r(y_l)) $$

11.3. Demo Bradley-Terry tương tác

Thay đổi reward gap để xem xác suất preferences:

12. Bước 3: PPO-RLHF

12.1. Objective đầy đủ (Eq. 2 InstructGPT)

$$ \text{objective}(\phi) = \mathbb{E}_{(x, y) \sim D_{\pi_\phi^{\text{RL}}}} \!\left[ r_\theta(x, y) - \beta \log \frac{\pi_\phi^{\text{RL}}(y|x)}{\pi^{\text{SFT}}(y|x)} \right] + \gamma \cdot \mathbb{E}_{x \sim D_{\text{pretrain}}} \!\big[ \log \pi_\phi^{\text{RL}}(x) \big] $$

3 thành phần:

  1. Reward: $r_\theta(x, y)$ — từ RM
  2. KL penalty ($\beta$): kéo $\pi^{\text{RL}}$ về gần $\pi^{\text{SFT}}$, tránh reward hacking
  3. PPO-ptx mix ($\gamma$): cộng pretraining loss, chống alignment tax trên public NLP datasets

12.2. KL penalty — tương tác

Xem cách reward thay đổi khi policy lệch khỏi SFT:

12.3. PPO surrogate objective

$$ \mathcal{L}^{\text{PPO}}(\phi) = \mathbb{E}_t \left[\min\!\Big(\rho_t(\phi) \hat{A}_t, \; \text{clip}(\rho_t(\phi), 1-\epsilon, 1+\epsilon) \hat{A}_t\Big)\right] $$

với importance ratio $\rho_t(\phi) = \pi_\phi(a_t | s_t) / \pi_{\phi_{\text{old}}}(a_t | s_t)$ và advantage $\hat{A}_t = r_t - V_\psi(s_t)$.

12.4. PPO clip — tương tác

Cách clip ngăn policy thay đổi quá lớn:

13. Inference: Sampling + KV-cache

13.1. Generation loop

y_0 = <BOS>
for t = 1, 2, ..., T_max:
    logits_t = π_φ(prompt, y_{<t})              # forward pass
    p_t = softmax(logits_t / temperature)        # temperature scaling
    y_t = sample_from(p_t)                       # token sampling
    if y_t == <EOS>: break

13.2. Temperature sampling

$$ p_k = \frac{\exp(z_k / T)}{\sum_l \exp(z_l / T)} $$

13.3. Demo sampling — tương tác

13.4. KV-cache memory

Mỗi token sinh ra cần cache key/value cho 96 layers × 96 heads:

$$ M_{\text{KV}} = 2 \cdot N_{\text{layer}} \cdot h \cdot d_{\text{head}} \cdot T \cdot \text{bytes/float} $$

14. Hạn chế (Alignment Tax) + 10 điểm cốt lõi

14.1. Alignment tax

TaskGPT-3InstructGPT (PPO)Δ
SQuADv260.553.4−7.1 ❌
DROP36.528.6−7.9 ❌
HellaSwag78.973.4−5.5 ❌
TruthfulQA25%41%+16 ✓
Hallucinate rate41%21%−20 ✓
Labeler preference0.250.66+0.41 ✓

PPO-ptx (mix pretraining gradient) giảm bớt alignment tax — giữ phần lớn năng lực ngôn ngữ gốc.

14.2. Tóm tắt 10 điểm cốt lõi

  1. ChatGPT = GPT-3.5 + RLHF — 3 tầng: decoder-only Transformer + pre-training + alignment.
  2. Decoder-only: bỏ encoder/cross-attention, chỉ giữ masked self-attention + FFN, Pre-LN.
  3. Pre-training: next-token cross-entropy trên 300B token.
  4. Scaling laws: $L(N) = (N_c/N)^{\alpha_N}$ với $\alpha_N \approx 0.076$, power law trên 7 bậc.
  5. GPT-3 175B: 96 layers, $d_{\text{model}}$=12288, $h$=96, context 2048.
  6. In-context learning: emergent at scale — model học task mới chỉ từ prompt.
  7. RLHF Step 1 (SFT): fine-tune GPT-3 trên ~13K labeler demonstrations.
  8. RLHF Step 2 (RM): 6B reward model + Bradley-Terry loss trên K-way rankings.
  9. RLHF Step 3 (PPO-ptx): maximize $r_\theta - \beta \text{KL} + \gamma \log p(D_{\text{pretrain}})$.
  10. KV-cache: tối ưu inference $O(T^3) \to O(T^2 d)$ — cần để serving thực tế.

Kiến trúc này đặt nền cho toàn bộ thế hệ LLM chat hiện đại. Nhiều mô hình kế tiếp dùng instruction tuning + một biến thể của alignment from feedback, nhưng KHÔNG nhất thiết cùng công thức PPO-RLHF:

Điểm chung: đều dùng human/AI preference signal, nhưng thuật toán và scale khác nhau đáng kể.

Giới hạn của tài liệu:
  1. Dựa vào 3 paper 2020-2022 — không cover: GPT-4, Claude 3, Gemini, multimodal, tool use, function calling, RAG, MoE, agentic systems.
  2. ChatGPT/GPT-3.5 không có paper công khai — tất cả về ChatGPT đều là diễn giải dựa trên InstructGPT.
  3. Số liệu thương mại (tham số GPT-3.5/4, dữ liệu, siêu tham số RLHF gần đây) đều không công khai.
  4. Scaling laws Kaplan 2020 đã bị supersede một phần bởi Chinchilla 2022 (xem §6).
  5. "Emergent abilities" là khái niệm có tranh luận (xem §8.3 Schaeffer caveat).
  6. Safety, jailbreak, system messages, RLAIF, Constitutional AI — chỉ đề cập sơ qua.
Tài liệu này đủ để hiểu nền tảng ChatGPT/InstructGPT theo paper 2020-2022, không đủ cho "kiến trúc LLM tối ưu 2026".

Tham khảo

Paper chính (đầy đủ trong tài liệu)

Background theoretical

Quan trọng để hiểu landscape LLM 2022+

Tài liệu không phải paper