為什麼要有 Transformer?
在 Transformer 出現之前,序列建模主要依賴 RNN / LSTM / GRU。這些架構有一個根本問題:無法並行化。每一步計算都依賴前一步的隱藏狀態,導致訓練速度極慢。
2017 年,Google 發表了《Attention Is All You Need》,提出一個完全基於 Attention 機制的架構,徹底解決了這個問題。
Self-Attention 機制
Self-Attention 的核心思想很簡單:讓序列中的每個 token 都能直接「看到」其他所有 token。
計算過程:
- 對每個輸入 token 生成三個向量:Query (Q)、Key (K)、Value (V)
- 計算 Q 和所有 K 的點積相似度 → 得到 Attention Score
- 用 Softmax 歸一化 → 得到 Attention Weight
- 對所有 V 加權求和 → 得到輸出
Attention(Q, K, V) = softmax(QK^T / √d_k) V
除以 √d_k 是為了防止點積過大導致 Softmax 梯度消失。
Multi-Head Attention
與其做一次 Attention,不如做多次(多個 head),每個 head 關注不同的特徵:
- 有些 head 關注語法關係
- 有些 head 關注語義關聯
- 有些 head 關注位置鄰近
每個 head 的結果拼接後再做一次線性變換。
Positional Encoding
因為 Attention 本身不關心位置(它是「無序」的),需要額外注入位置信息。原始論文使用正弦/餘弦函數:
PE(pos, 2i) = sin(pos / 10000^(2i/d_model))
PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))
從 Transformer 到 GPT
GPT 的本質就是 Transformer Decoder-only 架構:
- 只使用 Masked Self-Attention(只看左側上下文)
- 通過 Next Token Prediction 進行自回歸生成
- 規模化後湧現出強大的語言能力
推薦閱讀
- The Illustrated Transformer — 最直觀的圖解
- Attention Is All You Need (arXiv) — 原始論文
- The Annotated Transformer — 代碼級實現