A
返回 AI 知識
AI 知識2026/05/01 君澤智庫研究員 Bryan Chan7 分鐘閱讀

Transformer 架構理解 — Attention Is All You Need

深入理解 Transformer 的核心組件:Self-Attention、Multi-Head Attention、Positional Encoding,以及它們如何取代 RNN 成為現代 LLM 的基礎架構。

為什麼要有 Transformer?

在 Transformer 出現之前,序列建模主要依賴 RNN / LSTM / GRU。這些架構有一個根本問題:無法並行化。每一步計算都依賴前一步的隱藏狀態,導致訓練速度極慢。

2017 年,Google 發表了《Attention Is All You Need》,提出一個完全基於 Attention 機制的架構,徹底解決了這個問題。

Self-Attention 機制

Self-Attention 的核心思想很簡單:讓序列中的每個 token 都能直接「看到」其他所有 token

計算過程:

  1. 對每個輸入 token 生成三個向量:Query (Q)、Key (K)、Value (V)
  2. 計算 Q 和所有 K 的點積相似度 → 得到 Attention Score
  3. 用 Softmax 歸一化 → 得到 Attention Weight
  4. 對所有 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 進行自回歸生成
  • 規模化後湧現出強大的語言能力

實際應用場景

場景一:機器翻譯系統 Transformer 最初用於德英翻譯。假設你要翻譯 "The cat sat on the mat" 為德語,Self-Attention 讓每個英文詞都能直接關聯到德語對應詞——即使語序完全不同(德語動詞常放在句末)。每個 head 關注不同層面:語法結構、詞性、位置關係。

場景二:程式碼生成(GPT 系列) 當你輸入 "寫一個 Python 函數來排序列表",GPT 的 Masked Self-Attention 讓每個生成的 token 都能看到之前所有已生成的代碼。這就是為什麼 LLM 能生成語法正確的代碼——它在每一步都「回顧」了完整的上下文。

操作演示:用 Python 實現 Self-Attention

import torch
import torch.nn.functional as F

def self_attention(Q, K, V, d_k):
    # Q, K, V 形狀: [batch_size, seq_len, d_model]
    scores = torch.matmul(Q, K.transpose(-2, -1)) / torch.sqrt(d_k)
    attention_weights = F.softmax(scores, dim=-1)
    output = torch.matmul(attention_weights, V)
    return output

# 測試:2 個句子,每個 5 個 token,模型維度 64
Q = torch.randn(2, 5, 64)
K = torch.randn(2, 5, 64)
V = torch.randn(2, 5, 64)
output = self_attention(Q, K, V, d_k=64)
print(output.shape)  # torch.Size([2, 5, 64])

推薦閱讀