Transformers และ GPT
Attention: ให้แต่ละคำเลือกเองว่าจะสนใจคำไหน
Transformer แทน LSTM ด้วย self-attention: แต่ละ token สร้าง query, key และ value แล้วให้น้ำหนักกับ token อื่นตามความคล้ายของ query–key ส่วน GPT คือ Transformer ที่มี causal mask จึงทายคำถัดไปได้
โค้ดตัวอย่างคำนวณ attention ของ 4 คำและแสดงตารางน้ำหนัก: ส่วนบนขวาเป็น 0 เพราะ mask ไม่ให้มองอนาคต
Attention(Q, K, V) = softmax( Q·Kᵀ / √d + mask ) · V
mask[i, j] = −∞ ถ้า j > i
| ส่วน | หน้าที่ |
|---|---|
| Multi-head attention | หลาย head มองความสัมพันธ์หลายแบบพร้อมกัน |
| Positional encoding | บอกลำดับของ token |
| Layer norm + skip | ทำให้ซ้อนหลายชั้นได้อย่างเสถียร |
| Encoder / Decoder | BERT = encoder, GPT = decoder, T5 = ทั้งสอง |
สิ่งที่ควรจำ
- Attention มองทุกคำพร้อมกัน จึงฝึกแบบขนานได้และจำบริบทยาวได้
- ChatGPT คือ GPT ขนาดใหญ่ + การฝึกให้ทำตามคำสั่ง (RLHF)
import torch
torch.manual_seed(0)
tokens = ["the", "cat", "sat", "down"]
d = 8
x = torch.randn(len(tokens), d) # token embeddings
Wq, Wk, Wv = (torch.randn(d, d) / d ** 0.5 for _ in range(3))
Q, K, V = x @ Wq, x @ Wk, x @ Wv
scores = Q @ K.T / d ** 0.5 # how much each token looks at each other
mask = torch.triu(torch.ones(len(tokens), len(tokens)), diagonal=1).bool()
scores = scores.masked_fill(mask, float("-inf")) # causal mask: no peeking at the future
weights = torch.softmax(scores, dim=-1)
out = weights @ V
print("attention weights (row = query token):")
print(" " + "".join(f"{t:>7}" for t in tokens))
for t, row in zip(tokens, weights):
print(f"{t:>6}" + "".join(f"{w:7.2f}" for w in row))
print("output shape:", tuple(out.shape))
ผลลัพธ์
attention weights (row = query token):
the cat sat down
the 1.00 0.00 0.00 0.00
cat 0.40 0.60 0.00 0.00
sat 0.38 0.59 0.04 0.00
down 0.09 0.13 0.68 0.10
output shape: (4, 8)
- #GenerativeAI
- #DeepLearning
- #PythonສຳລັບຄົນLaos
- #AI
- #ບອກຕໍ່ຄວາມຮູ້