Skip to content

Deep Learning › NLP 與 Transformer › Transformer 與 Attention

Transformer 與 Attention (Transformers and Attention) ​

Transformer(Vaswani et al., 2017)拿掉了 RNN 的逐步狀態傳遞,改用 attention:每個 token 直接看整條序列,依相關程度加權彙整其他位置的資訊。這讓長距離依賴更容易學、訓練可完全平行,成為 LLM、BERT、蛋白質語言模型(ESM)與 ViT 的共同骨架。

Scaled Dot-Product Attention ​

每個 token 的向量 x 經三個線性層投影成:

向量角色比喻
Query q=xWQ我在找什麼搜尋關鍵字
Key k=xWK我能提供什麼文件標題
Value v=xWV實際被取走的內容文件內容
Attention(Q,K,V)=softmax(QK⊤dk)V
步驟shape(單一 head,序列長 L)意義
QK⊤(L, L)每對 (query, key) 的相似度
/dk(L, L)縮放;否則維度大時內積過大,softmax 飽和、梯度消失
mask(L, L)padding 或未來位置設成 −∞
softmax(沿 key 維)(L, L)每列總和為 1 的注意力權重
乘 V(L, d_v)每個位置得到其他位置 value 的加權平均
python
import torch
import torch.nn.functional as F

def attention(q, k, v, mask=None):                   # q, k, v: (batch, L, d)
    scores = q @ k.transpose(-2, -1) / q.size(-1) ** 0.5
    if mask is not None:
        scores = scores.masked_fill(mask, float("-inf"))   # mask 為 True 的位置不可看
    w = scores.softmax(dim=-1)
    return w @ v, w

q = k = v = torch.randn(2, 5, 16)
causal = torch.triu(torch.ones(5, 5, dtype=torch.bool), diagonal=1)   # 上三角 = 未來
out, w = attention(q, k, v, causal)
out.shape, w.sum(-1)[0]                              # torch.Size([2, 5, 16]),每列和為 1

# 實務用內建版本(自動選 FlashAttention 等高效實作)
F.scaled_dot_product_attention(q, k, v, is_causal=True)

Multi-Head Attention ​

把 dmodel 切成 h 份,各自做一次 attention(不同的 WQ,WK,WV),再串接投影回 dmodel。不同 head 可以注意不同關係(相鄰位置、語法依存、蛋白質中的接觸殘基對)。

python
from torch import nn

mha = nn.MultiheadAttention(embed_dim=64, num_heads=8, batch_first=True)   # 每個 head 64/8 = 8 維
x = torch.randn(2, 10, 64)
out, weights = mha(x, x, x)                          # self-attention:Q、K、V 都來自 x
out.shape, weights.shape                             # (2, 10, 64), (2, 10, 10)  權重預設對 head 平均
類型Q 來自K、V 來自用在
Self-attention自己自己encoder、decoder
Causal (masked) self-attention自己自己(只看過去)GPT 類生成模型
Cross-attentiondecoderencoder 輸出翻譯、影像描述、條件生成

位置編碼 (Positional Encoding) ​

attention 本身不知道順序:把序列打亂,每個 token 得到的加權平均完全一樣(permutation equivariant)。所以要把位置資訊加進輸入。

方法做法用在
Sinusoidal不同頻率的 sin / cos,直接加到 embedding原始 Transformer
可學習絕對位置nn.Embedding(max_len, d)BERT、ViT;不能超過訓練時的最大長度
相對位置 / RoPE依兩 token 的距離旋轉 Q、K多數現代 LLM、ESM-2;較能外推到更長序列
PE(pos,2i)=sin(pos100002i/d),PE(pos,2i+1)=cos(pos100002i/d)

Sinusoidal positional encoding and causal attention weights

左圖:每個位置得到獨特的 sin / cos 組合,低維度變化快(分辨相鄰位置)、高維度變化慢(分辨遠距離)。右圖:causal mask 下的注意力權重,上三角全為 0,每列總和為 1。

Transformer Block ​

text
x ─► LayerNorm ─► Multi-Head Attention ─► (+) ─► LayerNorm ─► FFN (Linear → GELU → Linear) ─► (+) ─► 輸出
│                                          ▲  │                                                ▲
└──────────────── residual ────────────────┘  └─────────────────── residual ───────────────────┘
元件作用
Residual connection梯度直接回傳,能疊很深(同 ResNet)
LayerNorm穩定訓練;現代模型多放在子層之前(pre-norm)
FFN每個位置各自通過的兩層 MLP,隱藏層通常是 4×dmodel;參數量大半在這裡
python
layer = nn.TransformerEncoderLayer(d_model=64, nhead=8, dim_feedforward=256,
                                   activation="gelu", batch_first=True, norm_first=True)
encoder = nn.TransformerEncoder(layer, num_layers=4)
pad_mask = torch.zeros(2, 10, dtype=torch.bool); pad_mask[1, 7:] = True   # True = padding
encoder(x, src_key_padding_mask=pad_mask).shape                           # torch.Size([2, 10, 64])

三種架構 ​

架構注意力預訓練目標代表模型適合
Encoder-only雙向遮蔽語言模型 (MLM):猜被遮住的 tokenBERT、ESM-2、DNABERT分類、序列標註、抽 embedding
Decoder-onlycausal下一個 token 預測GPT、Llama、ProGen生成、LLM
Encoder-decoder雙向 + cross序列到序列T5、原始 Transformer翻譯、摘要

LLM 的訓練、對齊與使用見 LLM 基礎;fine-tune(LoRA / PEFT)見 Fine-Tuning。

長序列的問題 ​

attention 矩陣是 L×L:序列長度加倍,記憶體與計算變 4 倍。對基因體(調控區域動輒數萬到數十萬 bp)尤其關鍵。

對策例子
高效實作(不改數學)FlashAttention(F.scaled_dot_product_attention 自動使用)
先用 CNN / pooling 縮短序列再接 TransformerEnformer
稀疏 / 局部 attentionLongformer、BigBird
非 attention 的長序列架構狀態空間模型 (state space model)、Hyena 類(HyenaDNA、Caduceus)

常見誤解 ​

誤解實際
attention 權重 = 模型的解釋權重高不等於因果上重要;多層、多 head 混合後更難解讀。需要解釋時用歸因方法並以實驗驗證
Transformer 一定比較好小資料、短序列時 CNN / LSTM / 樹模型常相當,且便宜得多
模型越大越好標註品質、切分方式(同源序列洩漏)的影響常大於模型大小
attention map 看起來像蛋白質接觸圖就代表學到結構ESM 的部分 head 確實與接觸圖相關,但仍需以結構資料驗證