GPT
GPT - Mô hình ngôn ngữ tự hồi quy
"Tôi yêu ___" — hãy đoán token tiếp theo mà GPT có khả năng sinh ra nhất!
GPT sinh văn bản theo kiểu autoregressive: mỗi bước nó đọc toàn bộ context đã có, tính attention, xuất ra một phân phối xác suất trên toàn bộ từ vựng (~50K tokens với GPT-2, ~100K với GPT-4), sample một token, và lặp lại. Kéo thanh trượt để xem từng bước.
Hình minh họa
Sequence (prompt + generated)
Prompt gốc Đã sinh Đang dự đoán
Attention trên context (token hiện tại nhìn vào đâu?)
Attention cho biết khi dự đoán token tiếp theo, model "nhìn"vào token nào trong context nhiều nhất. Thường các token gần sẽ có trọng số cao hơn, nhưng không phải luôn luôn — tuỳ pattern cú pháp.
Causal mask — GPT chỉ nhìn về quá khứ
Ma trận tam giác dưới: ô xanh = được phép, ô xám = bị mask −∞. Đây là lý do GPT chỉ sinh được text theo chiều trái→phải.
Top-10 token ứng viên (sau khi áp sampling)
T=1.00 · k=10 · p=1.00Logit → chia temperature → softmax → top-k filter → top-p filter → sample. Với T=0.01, gần như luôn chọn #1 (greedy). Với T=2.0 và top-p=0.95, model có thể chọn bất ngờ hơn.
Điều khiển sampling
Preset nhanh:
GPT chỉ làm MỘT VIỆC: dự đoán token tiếp theo. Nhưng khi được huấn luyện trên hàng tỷ câu với mục tiêu , nó "hiểu" ngôn ngữ đủ sâu để viết văn, trả lời câu hỏi, viết code, giải toán — và thậm chí reason qua nhiều bước!
Như người kể chuyện giỏi: chỉ dựa vào những gì đã nói để tiếp tục, nhưng nhờ đọc hàng tỷ câu chuyện nên kể rất mạch lạc. Và khi đủ lớn, nó xuất hiện những khả năng mà không ai hard-code được — đó chính là emergent abilities.
GPT đọc một chiều (trái→phải) nên lý thuyết KHÔNG giỏi HIỂU ngữ cảnh bằng BERT. Nhưng tại sao ChatGPT lại trả lời câu hỏi rất tốt?
Logit là đầu ra thô của layer cuối (trước softmax). Sampling:
T → 0: phân phối sharper, gần như argmax (greedy). T = 1: softmax chuẩn. T → ∞: phân phối uniform (chọn ngẫu nhiên).
- T=0 / Greedy: Trích xuất thông tin, code completion — cần ổn định.
- T=0.7, top-p=0.9: Mặc định ChatGPT — cân bằng fluency và đa dạng.
- T=1.0+, top-p=0.95: Brainstorm, viết văn sáng tạo — chấp nhận surprise.
- T=2.0+: Thường tạo văn bản vô nghĩa — tránh trừ khi nghiên cứu.
Khác với sampling, beam search duy trì k ứng viên sequence tốt nhất ở mỗi bước và chọn sequence có xác suất tích luỹ cao nhất. Dùng cho dịch máy, tóm tắt (cần kết quả đúng hơn sáng tạo). Nhưng beam search thường tạo câu lặp lại và "an toàn quá" nên ChatGPT không dùng — ưu tiên sampling.
Khi T > 1.5, phân phối trở nên gần uniform: model có thể chọn cả token có logit thấp → xuất hiện "hallucination" hoặc văn bản phi logic. Top-p = 0.95 giúp kiềm chế điều này (cắt long tail) nhưng không loại bỏ hoàn toàn.
Một trong những khám phá quan trọng nhất của NLP hiện đại: perplexity giảm theo power law với kích thước model (khi dữ liệu và compute tương xứng). Đây là biểu đồ log-log cho các thế hệ GPT:
Hình minh họa
Model size (params) vs Perplexity (WikiText) — log-log
Đường gạch tím: mô hình power-law L(N) ∝ N^(−α). Mỗi thế hệ mới tiếp tục trượt xuống — chưa có bằng chứng saturate.
Bạn muốn model tạo một đoạn code Python chính xác theo spec. Chọn sampling nào phù hợp nhất?
Giải thích
GPT (Generative Pre-trained Transformer, OpenAI 2018) dùng Transformer Decoder với self-attention dạng masked (causal) để sinh văn bản tự hồi quy — dự đoán token tiếp theo dựa trên tất cả token trước đó. Trước khi mô hình xử lý, văn bản được chia nhỏ bằng tokenization (BPE / SentencePiece) thành các subword token. So với BERT (encoder hai chiều), GPT tối ưu cho việc sinh văn bản thay vì hiểu toàn câu.
Tối đa xác suất chuỗi (log-likelihood):
Với mỗi token, model xuất ra phân phối xác suất trên toàn bộ vocab (50K–100K tokens). Loss là cross-entropy giữa distribution dự đoán và one-hot ground truth. Gradient truyền ngược qua mọi layer.
là logit cho token i, là temperature, và |V| là kích thước vocab. Đây là công thức CỐT LÕI của sampling trong mọi LLM hiện đại.
GPT-1 (2018): 117M params, 12 layers, trained on BooksCorpus (~5GB) — chứng minh pre-training + fine-tuning vượt trội.
GPT-2 (2019): 1.5B params, 48 layers, 40GB WebText — sinh text giống người; OpenAI ban đầu không release vì lo ngại misuse.
GPT-3 (2020): 175B params, 96 layers, 570GB filtered Common Crawl — xuất hiện few-shot learning, viết code, giải toán đơn giản.
GPT-3.5 / ChatGPT (2022): + RLHF (Reinforcement Learning from Human Feedback) — model biết follow instruction, từ chối câu hỏi độc hại.
GPT-4 (2023): Ước tính ~1T+ params (MoE) — multimodal (vision), reasoning phức tạp, pass bar exam ở top 10%.
"""
Sinh văn bản tiếng Việt với Hugging Face Transformers.
Yêu cầu: pip install transformers torch
"""
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
# ─── 1. Load model và tokenizer ───
# Dùng GPT-2 (nếu có Vietnamese version: VietAI/gpt-neo-1.3B-vietnamese-news)
model_name = "gpt2" # hoặc "VietAI/gpt-j-6B-vietnamese-news"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
model.eval()
# ─── 2. Tokenize prompt ───
prompt = "Tôi yêu"
input_ids = tokenizer.encode(prompt, return_tensors="pt")
print(f"Token IDs: {input_ids.tolist()}")
print(f"Tokens: {tokenizer.convert_ids_to_tokens(input_ids[0])}")
# ─── 3. Generation với các strategy khác nhau ───
# 3a. Greedy decode (deterministic, lặp lại)
with torch.no_grad():
out_greedy = model.generate(
input_ids,
max_length=30,
do_sample=False, # greedy
)
print("Greedy:", tokenizer.decode(out_greedy[0], skip_special_tokens=True))
# 3b. Temperature + top-k + top-p (ChatGPT style)
with torch.no_grad():
out_sampled = model.generate(
input_ids,
max_length=30,
do_sample=True,
temperature=0.7, # cân bằng
top_k=50, # chỉ xét 50 token cao nhất
top_p=0.9, # nucleus sampling
num_return_sequences=3, # tạo 3 biến thể
)
for i, seq in enumerate(out_sampled):
print(f"Sample {i+1}:", tokenizer.decode(seq, skip_special_tokens=True))
# 3c. Beam search (ổn định hơn, cho dịch/tóm tắt)
with torch.no_grad():
out_beam = model.generate(
input_ids,
max_length=30,
num_beams=5,
early_stopping=True,
no_repeat_ngram_size=2, # tránh lặp bigram
)
print("Beam:", tokenizer.decode(out_beam[0], skip_special_tokens=True))"""
Tự implement softmax sampling với temperature + top-k + top-p.
Giúp hiểu rõ chuyện gì xảy ra bên trong .generate().
"""
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
model.eval()
def sample_next_token(logits, temperature=1.0, top_k=50, top_p=0.9):
"""Áp dụng sampling pipeline chuẩn."""
# Chia temperature
logits = logits / temperature
# Top-k: giữ k token cao nhất
if top_k > 0:
top_k_vals, _ = torch.topk(logits, top_k)
thresh = top_k_vals[..., -1, None]
logits = torch.where(logits < thresh, torch.full_like(logits, -float("inf")), logits)
# Top-p (nucleus)
sorted_logits, sorted_idx = torch.sort(logits, descending=True)
sorted_probs = F.softmax(sorted_logits, dim=-1)
cum_probs = torch.cumsum(sorted_probs, dim=-1)
sorted_mask = cum_probs > top_p
sorted_mask[..., 1:] = sorted_mask[..., :-1].clone()
sorted_mask[..., 0] = False
idx_to_remove = sorted_mask.scatter(-1, sorted_idx, sorted_mask)
logits = logits.masked_fill(idx_to_remove, -float("inf"))
# Softmax → sample
probs = F.softmax(logits, dim=-1)
next_token = torch.multinomial(probs, num_samples=1)
return next_token
# ─── Autoregressive loop ───
prompt = "Tôi yêu"
input_ids = tokenizer.encode(prompt, return_tensors="pt")
generated = input_ids.clone()
for step in range(20):
with torch.no_grad():
outputs = model(generated)
# logits của token cuối cùng
logits = outputs.logits[:, -1, :] # shape: [batch, vocab]
# Sample
next_token = sample_next_token(logits, temperature=0.8, top_k=40, top_p=0.95)
generated = torch.cat([generated, next_token], dim=-1)
# Dừng nếu gặp EOS
if next_token.item() == tokenizer.eos_token_id:
break
print(tokenizer.decode(generated[0], skip_special_tokens=True))
# Ví dụ output: "Tôi yêu em rất nhiều và mãi mãi bên em..."ChatGPT không chỉ là GPT-3 raw. Nó trải qua 3 giai đoạn: (1) pre-training (next-token prediction trên corpus khổng lồ), (2) supervised fine-tuning (SFT) (human viết câu trả lời lý tưởng), (3) RLHF (human rank nhiều output → train reward model → PPO). Nhờ vậy model biết follow instruction, từ chối nội dung độc hại, và trả lời hữu ích — không chỉ là "autocomplete thông minh".
- GPT = Transformer Decoder-only đọc MỘT CHIỀU (trái→phải) với causal mask, tối đa P(w_t | w_<t) — autoregressive language modeling.
- Mỗi bước sinh: context → self-attention → logits → softmax(l/T) → top-k / top-p filter → sample → lặp lại cho đến EOS hoặc max_length.
- Causal mask = ma trận tam giác dưới với −∞ ở trên đường chéo → token hiện tại KHÔNG nhìn thấy token tương lai.
- Temperature điều khiển 'độ sáng tạo': T thấp → greedy/ổn định (code); T cao → đa dạng/bất ngờ (creative writing). Top-k và top-p cắt long tail.
- Scaling laws (Kaplan 2020): loss giảm theo power law với N (params), D (tokens), C (compute) — GPT-1 117M → GPT-4 ~1T, perplexity từ 35.8 → 5.2.
- GPT giỏi SINH; BERT giỏi HIỂU. ChatGPT = GPT + SFT + RLHF — từ 'autocomplete' thô thành assistant follow-instruction an toàn và hữu ích.
Kiểm tra hiểu biết
GPT và BERT đều dùng Transformer. Điểm khác biệt cốt lõi là gì?