BERT

Bidirectional Encoder Representations from Transformers
Devlin et al., Google, 2018 — arXiv:1810.04805

Pasted image 20260508162651.png


核心定位

維度 說明
架構 Transformer encoder-only
方向性 雙向(同時看左右上下文)
目標 預訓練通用語言表示,再 fine-tune 各下游任務
對比 GPT GPT 是 decoder-only、單向左→右;BERT 是 encoder-only、雙向

模型規格

BERT-base BERT-large
Layers 12 24
Hidden size 768 1024
Attention heads 12 16
Parameters 110M 340M
Max seq length 512 512

Input Representation

每個 token 的 embedding = Token + Segment + Position 三者相加

[CLS] 台灣 的 首都 [SEP] 台北 是 答案 [SEP]
  ↑                  ↑                  ↑
句首標記          句子分隔符           句末

預訓練任務

1. MLM — Masked Language Modeling

2. NSP — Next Sentence Prediction


Fine-tuning 範式

預訓練 BERT
    ↓  加上 task-specific head
分類任務 → 取 [CLS] → Linear → softmax
NER     → 取每個 token → Linear → label
QA      → 取 span 的 start/end logits

只需少量標注資料 + 幾個 epoch fine-tune,即可在各 NLP benchmark 達到 SOTA。


HuggingFace 快速使用

from transformers import BertTokenizer, BertModel
import torch

tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
model = BertModel.from_pretrained("bert-base-uncased")

inputs = tokenizer("Hello, BERT!", return_tensors="pt")
with torch.no_grad():
    outputs = model(**inputs)

# outputs.last_hidden_state: [batch, seq_len, 768]
# outputs.pooler_output:     [batch, 768]  ← [CLS] 經過線性層
cls_vec = outputs.pooler_output

BERT 系列演進

模型 年份 改進重點
RoBERTa 2019, Meta 移除 NSP、更多資料、動態 masking、更大 batch
ALBERT 2019, Google Factorized embedding、跨層參數共享、SOP 取代 NSP,大幅降低參數量
DistilBERT 2019, HuggingFace Knowledge distillation,小 40%、快 60%,保留 97% 性能
ELECTRA 2020, Google Replaced Token Detection(判斷每個 token 是否被替換),更高效
DeBERTa 2020, Microsoft Disentangled Attention(position 與 content 分開計算),多項 benchmark SOTA
mBERT 2019, Google 多語言版本,104 種語言
BERT 系列(中文) CKIP-BERT、MacBERT、RoBERTa-wwm-ext

限制


適用場景


References

Powered by Forestry.md