BERT 系列模型
核对 BERT 三重嵌入、Post-LN GELU 编码器勘误、15%(80/10/10)与中文 WWM 全词遮盖、BERT-base/large 与 ALBERT 精确参数核算及 Adapter/LoRA 低秩微调实测。
学完这一章,你能够
- 核对 BERT 三重嵌入、Post-LN GELU 编码器勘误、15%(80/10/10)与中文 WWM 全词遮盖、BERT-base/large 与 ALBERT 精确参数核算及 Adapter/LoRA 低秩微调实测。
BERT 三重嵌入、Post-LN GELU 编码器与 MLM 预训练
BERT(Bidirectional Encoder Representations from Transformers)由 Google 于 2018 年提出,仅采用 Transformer 编码器堆叠实现深度双向上下文建模。在输入层,文本切分为词或子词序列(预训练时随机将部分位置替换为 [MASK]),经 Embedding 层相加融合三部分向量:词嵌入(Token Embeddings,编码词汇语义)、位置嵌入(Position Embeddings,标注序列位置)与段嵌入(Segment Embeddings,区分句对中的句子 A/B)。随后输入多层 Transformer 编码器块,每层由双向自注意力、前馈网络以及残差连接与层归一化组成,输出每个位置融合左右上下文的隐向量表示。
预训练包含掩码语言建模(MLM,随机选取约 15% 词元,其中 80% 换为 [MASK]、10% 换为随机词、10% 保持原词以缓解微调无 [MASK] 的失配)与下一句预测(NSP)两项任务。MLM 分类头将遮蔽位隐向量依次经全连接层、GELU 激活函数、层归一化与词表投影 Softmax,预测被遮盖的原词。实现勘误提示:来源简化编码器代码将层归一化写作 `src + self.norm1(src2)` 且采用 ReLU,而原版 BERT 实际采用 Post-LN 顺序 `LayerNorm(src + Sublayer(src))` 与 GELU 激活(中间维 4H)。本站纯 NumPy 实测完整三重嵌入 + Post-LN GELU 编码器与 MLM 头:修改 [MASK] 右侧词项可使掩码位词表概率发生 0.01849 的实时偏移(确证双向上下文流通),切换段嵌入产生 0.2012 的特征迁移,且 GELU(-1.0) = -0.1587 保持负区平滑非零;在 20,000 词元采样中实测 15% MLM 命中 14.82%(其中 [MASK] 80.03%、随机词 10.43%、原词保留 9.55%)。BERT-base 与 BERT-large 规格对比见下表 1。
标准微调流程与参数高效微调(Adapter / LoRA)实测
下游微调时只需在 BERT 顶层挂载分类或回归适配头,以较小学习率(2e-5 至 5e-5)、批大小 16 或 32 训练 2 至 4 轮即可在多数任务收敛。随着模型体量增大,除全参数微调与冻结特征提取外,参数高效微调(PEFT,见下表 2)如瓶颈适配器(Adapter)、提示学习(Prompt)及低秩适配(LoRA,在冻结权重 W₀ 上叠加低秩增量 (α/r)AB)成为降本利器。本站按 BERT-base 精确参数(109.48M)核算对比:仅训二分类头需 1,538 参数;每层注入 2 处 m = 64 瓶颈 Adapter 需 2,380,802 参数(仅占 2.175%);对每层 Q/V 注入秩 r = 8 的 LoRA 仅需 296,450 参数(低至 0.271%)。并在冻结主干 W₀ 上实测 LoRA 低秩更新:按规范零初始化矩阵 B 使初始扰动范数精确为 0.0,120 步梯度下降即令二分类损失由 0.7796 降至 0.0070(训练准确率 1.0000)。
主流变体(RoBERTa / ALBERT / DistilBERT / ELECTRA)与中文模型
围绕 BERT 的效率与训练机制衍生出众多经典变体:RoBERTa 通过扩大批次(8k 对 256)、延长训练、移除 NSP 任务与改用动态遮盖模式,在 GLUE 基准上平均提升 2–3%;ALBERT 创新性地将词嵌入分解为 V×E 与 E×H 两小矩阵并跨层共享 Transformer 参数,官方报告参数骤减约 89%、速度提升约 1.7 倍——本站按词表 30,522、最大长度 512 精确公式实测:BERT-base 为 109.48M、BERT-large 为 335.14M,应用 ALBERT(E = 128 且 12 层共享)后降至 11.75M,参数压缩比精确达 89.27%。此外,DistilBERT 借助知识蒸馏瘦身,ELECTRA 用生成器-判别器替换词检测取代 MLM,SpanBERT 专注连续文本跨度遮盖以强化问答与共指解析。
中文生态代表模型见下表 3(哈工大 BERT-wwm 与 RoBERTa-wwm-ext、百度 ERNIE、华为 NEZHA),可通过 Hugging Face 加载如 `bert-base-chinese` 处理中文语料。中文微调建议优先选用全词遮盖(WWM)版本、留意中文词边界切分,并在专业垂直领域开展领域自适应继续预训练。本站对比“自然语言处理很有趣”的遮盖差异:单字遮盖产出“自然[MASK]言处理很有趣”易被字面搭配泄露,而中文 WWM 将整词“自然语言”同步遮盖为“[MASK][MASK][MASK][MASK]处理很有趣”,迫使模型真正依据上下文语义推理。
学习路线图与推荐资料
建议沿着“Transformer 编码器 → BERT 基础预训练与微调 → RoBERTa/ALBERT/WWM 变体与 PEFT 压缩”的路径循序渐进,延伸阅读可参考原始 BERT 论文(arXiv:1810.04805)及 RoBERTa/ALBERT 论文,结合 Hugging Face Transformers、中文 BERT 开源仓库以及 Coursera 自然语言处理专项课与李宏毅深度学习课程持续实践。
BERT-base 与 BERT-large 核心结构配置对比
| 参数 | BERT-base | BERT-large |
|---|---|---|
| 层数 | 12 层 Transformer 编码器 | 24 层 Transformer 编码器 |
| 隐藏层大小 | 768(FFN 中间维 3072) | 1024(FFN 中间维 4096) |
| 注意力头数 | 12 头(每头 d_k = 64) | 16 头(每头 d_k = 64) |
| 总参数量 | 约 110M(词表 30,522 精确核算 109.48M) | 约 340M(词表 30,522 精确核算 335.14M) |
BERT 常用微调与参数高效适配策略对比
| 方法 | 优点 | 缺点 |
|---|---|---|
| 全参数微调 | 端到端更新全部层权重,下游任务精度上限最优 | 显存与算力开销大,每任务需存储完整副本 |
| 特征提取(冻结BERT) | 仅训练任务头(实测二分类头仅 1,538 参数),计算极高效 | 底层特征不适配领域漂移,性能往往次优 |
| 适配器(Adapter) | 冻结主干仅训瓶颈模块(实测占 2.175%,同属 PEFT 的 LoRA 仅占 0.271%) | 传统串行 Adapter 需改动编码器结构并略增推理延迟 |
| 提示学习(Prompt) | 将分类转为完形填空,小样本与零样本场景表现突出 | 效果对提示模板与标签词设计较为敏感 |
中文 BERT 系列代表模型概览
| 模型 | 机构 | 特点 |
|---|---|---|
| BERT-wwm | 哈工大讯飞联合实验室 | 采用中文全词遮盖(Whole Word Masking),整词同步遮蔽防字面泄露 |
| RoBERTa-wwm-ext | 哈工大讯飞联合实验室 | 结合全词遮盖、去除 NSP 与扩展大规模中文语料训练 |
| ERNIE (百度) | 百度 | 引入实体与短语级知识遮盖,融入外部知识图谱语义 |
| NEZHA | 华为诺亚方舟实验室 | 引入函数式相对位置编码、全词遮盖与 LAMB 优化器提升长句表现 |
运行 BERT 三重嵌入双向核验、MLM/WWM 遮盖、ALBERT 压缩核算与 LoRA 低秩更新实验
"""Independent pure-NumPy lab for BERT Encoder Models (Ch 16)."""
import json
import math
import platform
import numpy as np
def gelu(x: np.ndarray) -> np.ndarray:
# Exact Gaussian Error Linear Unit: 0.5 * x * (1 + erf(x / sqrt(2)))
erf_vec = np.vectorize(math.erf)
return 0.5 * x * (1.0 + erf_vec(x / math.sqrt(2.0)))
def softmax(x: np.ndarray, axis: int = -1) -> np.ndarray:
shifted = x - np.max(x, axis=axis, keepdims=True)
ex = np.exp(shifted)
return ex / np.sum(ex, axis=axis, keepdims=True)
def layer_norm(x: np.ndarray, eps: float = 1e-5) -> np.ndarray:
mean = np.mean(x, axis=-1, keepdims=True)
var = np.var(x, axis=-1, keepdims=True)
return (x - mean) / np.sqrt(var + eps)
def run_cases():
cases = []
rng = np.random.default_rng(16)
# 1. BERT Triple Embedding + Post-LN GELU Encoder + Bidirectional Context Flow to [MASK]
vocab_sz, max_pos, n_seg, d_model, d_ff = 30, 16, 2, 16, 64
tok_emb = rng.normal(0.0, 0.5, size=(vocab_sz, d_model))
pos_emb = rng.normal(0.0, 0.2, size=(max_pos, d_model))
seg_emb = rng.normal(0.0, 0.2, size=(n_seg, d_model))
wq = rng.normal(0.0, 0.35, size=(d_model, d_model))
wk = rng.normal(0.0, 0.35, size=(d_model, d_model))
wv = rng.normal(0.0, 0.35, size=(d_model, d_model))
w1 = rng.normal(0.0, 0.3, size=(d_model, d_ff))
w2 = rng.normal(0.0, 0.3, size=(d_ff, d_model))
w_mlm_dense = rng.normal(0.0, 0.35, size=(d_model, d_model))
w_mlm_out = tok_emb.T # tied output embedding (d_model, vocab_sz)
def bert_encoder_mlm(token_ids: list[int], segment_ids: list[int]):
seq_len = len(token_ids)
h = tok_emb[token_ids] + pos_emb[:seq_len] + seg_emb[segment_ids]
h = layer_norm(h)
q, k, v = h @ wq, h @ wk, h @ wv
attn = softmax((q @ k.T) / np.sqrt(float(d_model)), axis=-1) @ v
# Standard BERT Post-LN: LayerNorm(h + Sublayer(h))
h1 = layer_norm(h + attn)
ffn = gelu(h1 @ w1) @ w2
h_out = layer_norm(h1 + ffn)
# MLM head: Linear -> GELU -> LayerNorm -> Vocab Linear -> Softmax
mlm_h = layer_norm(gelu(h_out @ w_mlm_dense))
mlm_probs = softmax(mlm_h @ w_mlm_out, axis=-1)
return h_out, mlm_probs
# Sequence with [CLS]=1, [MASK]=4 at idx 3, [SEP]=2 at idx 5, sentence B at idx 6..7
ids_a = [1, 5, 6, 4, 7, 2, 8, 9]
segs = [0, 0, 0, 0, 0, 0, 1, 1]
out_a, probs_a = bert_encoder_mlm(ids_a, segs)
# Change right-hand token at idx 4 (after [MASK]) -> bidirectional BERT updates [MASK] probabilities!
ids_right_changed = [1, 5, 6, 4, 19, 2, 8, 9]
_, probs_right = bert_encoder_mlm(ids_right_changed, segs)
right_ctx_delta = float(np.max(np.abs(probs_a[3] - probs_right[3])))
# Also change segment embedding (0 vs 1) on identical tokens -> representation shifts
out_seg_all0, _ = bert_encoder_mlm(ids_a, [0] * 8)
seg_delta = float(np.mean(np.abs(out_a[6:] - out_seg_all0[6:])))
gelu_zero = float(gelu(np.array([0.0]))[0])
gelu_neg = float(gelu(np.array([-1.0]))[0])
c1_ok = (
out_a.shape == (8, d_model)
and abs(float(np.sum(probs_a[3])) - 1.0) < 1e-12
and right_ctx_delta > 1e-4
and seg_delta > 0.05
and abs(gelu_zero) < 1e-12
and gelu_neg < 0.0
)
cases.append(dict(
name="bert_triple_embedding_and_gelu_encoder",
inputs=dict(seq_len=8, mask_index=3, d_model=d_model, d_ff=d_ff),
prerequisites="实现 BERT 三重嵌入(Token+Position+Segment)、Post-LN GELU 编码器层及 MLM 分类头。",
action="验证修改 [MASK] 右侧词项能实时改变掩码位词表概率(双向建模)、段嵌入有效区分句对,及 GELU 在负区平滑非零。",
expected=dict(bidirectional_right_context_active=True, segment_embedding_active=True, gelu_smooth_negative=True),
actual=dict(
bidirectional_right_context_active=right_ctx_delta > 1e-4,
segment_embedding_active=seg_delta > 0.05,
gelu_smooth_negative=(abs(gelu_zero) < 1e-12 and gelu_neg < 0.0),
),
measurements=dict(
encoder_output_shape=list(out_a.shape),
mask_prob_delta_from_right_token=round(right_ctx_delta, 5),
segment_shift_mean_abs=round(seg_delta, 4),
gelu_at_minus1=round(gelu_neg, 4),
),
passed=c1_ok,
))
# 2. BERT 15% MLM (80/10/10 Rule) + Dynamic Masking (RoBERTa) + Chinese Whole Word Masking (WWM)
n_tokens = 20000
selected = rng.random(n_tokens) < 0.15
n_sel = int(np.sum(selected))
sub_draw = rng.random(n_sel)
n_mask = int(np.sum(sub_draw < 0.80))
n_rand = int(np.sum((sub_draw >= 0.80) & (sub_draw < 0.90)))
n_keep = int(np.sum(sub_draw >= 0.90))
sel_ratio = n_sel / n_tokens
mask_ratio = n_mask / n_sel
rand_ratio = n_rand / n_sel
keep_ratio = n_keep / n_sel
# Chinese WWM vs Char-level masking on "自然语言处理很有趣"
words_zh = ["自然语言", "处理", "很", "有趣"]
chars_zh = list("".join(words_zh))
# Char-level masks only char index 2 ('语') -> partial word leakage
char_masked = [("[MASK]" if i == 2 else ch) for i, ch in enumerate(chars_zh)]
# WWM masks the entire word "自然语言" (indices 0..3) when any char inside it is selected
wwm_masked = []
for w in words_zh:
if w == "自然语言":
wwm_masked.extend(["[MASK]"] * len(w))
else:
wwm_masked.extend(list(w))
c2_ok = (
0.14 <= sel_ratio <= 0.16
and 0.77 <= mask_ratio <= 0.83
and 0.08 <= rand_ratio <= 0.12
and 0.08 <= keep_ratio <= 0.12
and char_masked.count("[MASK]") == 1
and wwm_masked[:4] == ["[MASK]"] * 4
)
cases.append(dict(
name="bert_mlm_80_10_10_and_wwm_masking",
inputs=dict(simulated_tokens=n_tokens, zh_sentence="自然语言处理很有趣"),
prerequisites="在 20,000 个位置上运行 BERT 15%(80/10/10)采样,并对比单字遮盖与中文全词遮盖(WWM)。",
action="验证遮盖比例贴近 15% 与 80%/10%/10% 分布,且 WWM 对“自然语言”整词 4 字同步置 [MASK] 避免词内泄露。",
expected=dict(mlm_ratios_within_bounds=True, wwm_masks_whole_word=True),
actual=dict(
mlm_ratios_within_bounds=(0.14 <= sel_ratio <= 0.16 and 0.77 <= mask_ratio <= 0.83),
wwm_masks_whole_word=(char_masked.count("[MASK]") == 1 and wwm_masked[:4] == ["[MASK]"] * 4),
),
measurements=dict(
selected_pct=round(sel_ratio * 100.0, 2),
replaced_mask_pct=round(mask_ratio * 100.0, 2),
replaced_random_pct=round(rand_ratio * 100.0, 2),
kept_original_pct=round(keep_ratio * 100.0, 2),
char_level_masked_str="".join(char_masked),
wwm_masked_str="".join(wwm_masked),
),
passed=c2_ok,
))
# 3. Exact Parameter Counts: BERT-base (110M), BERT-large (340M), ALBERT (~89% compression)
def bert_param_count(layers: int, hidden: int, vocab: int = 30522, max_p: int = 512, emb_dim: int | None = None, share_layers: bool = False) -> int:
if emb_dim is None:
emb_params = (vocab + max_p + 2) * hidden + 2 * hidden
else:
# ALBERT factorized embedding: V*E + E*H + pos/seg*E
emb_params = (vocab + max_p + 2) * emb_dim + 2 * emb_dim + (emb_dim * hidden + hidden)
# One Transformer block: Q,K,V,O (4*H^2 + 4H) + FFN (2*H*4H + 4H + H) + 2*LN (4H)
per_layer = 4 * (hidden * hidden + hidden) + (hidden * 4 * hidden + 4 * hidden) + (4 * hidden * hidden + hidden) + 4 * hidden
encoder_params = per_layer if share_layers else layers * per_layer
pooler = hidden * hidden + hidden
return emb_params + encoder_params + pooler
p_base = bert_param_count(12, 768)
p_large = bert_param_count(24, 1024)
p_albert = bert_param_count(12, 768, emb_dim=128, share_layers=True)
albert_reduction = 1.0 - p_albert / p_base
c3_ok = (
108_000_000 <= p_base <= 112_000_000
and 333_000_000 <= p_large <= 342_000_000
and 0.88 <= albert_reduction <= 0.91
)
cases.append(dict(
name="bert_architecture_params_and_albert_compression",
inputs=dict(vocab_size=30522, max_position=512, albert_emb_dim=128),
prerequisites="按 BERT 嵌入层、多头注意力、4H 前馈层、层归一化与池化层精确公式核算参数量。",
action="验证 BERT-base 约 110M、BERT-large 约 340M,且 ALBERT 嵌入分解与跨层参数共享使参数量压缩约 89%。",
expected=dict(bert_base_approx_110m=True, bert_large_approx_340m=True, albert_reduction_approx_89pct=True),
actual=dict(
bert_base_approx_110m=(108_000_000 <= p_base <= 112_000_000),
bert_large_approx_340m=(333_000_000 <= p_large <= 342_000_000),
albert_reduction_approx_89pct=(0.88 <= albert_reduction <= 0.91),
),
measurements=dict(
bert_base_params_m=round(p_base / 1e6, 2),
bert_large_params_m=round(p_large / 1e6, 2),
albert_base_params_m=round(p_albert / 1e6, 2),
albert_reduction_pct=round(albert_reduction * 100.0, 2),
),
passed=c3_ok,
))
# 4. PEFT Parameter Efficiency & LoRA Low-Rank Adapter Math Verification
# Across 12 layers of BERT-base (H=768): compare trainable params for Full FT, Frozen Head, Adapter (m=64), LoRA (r=8 on Q,V)
H, L_num, num_classes = 768, 12, 2
head_params = H * num_classes + num_classes
adapter_params = L_num * 2 * (H * 64 + 64 + 64 * H + H) + head_params # 2 bottleneck adapters per layer
lora_params = L_num * 2 * (H * 8 + 8 * H) + head_params # LoRA r=8 on W_q and W_v per layer
adapter_pct = adapter_params / p_base * 100.0
lora_pct = lora_params / p_base * 100.0
# Functional LoRA training check on frozen random projection W0 (16 -> 16) + linear classifier
n_samples, dim, rank, alpha = 80, 16, 2, 4.0
x_data = rng.normal(0.0, 1.0, size=(n_samples, dim))
true_w = rng.normal(0.0, 1.0, size=(dim,))
y_bin = (x_data @ true_w > 0).astype(float)
w0 = rng.normal(0.0, 0.4, size=(dim, dim)) # frozen base weight
A = rng.normal(0.0, 0.1, size=(dim, rank))
B = np.zeros((rank, dim)) # LoRA B initialized to 0 => exact zero initial perturbation
init_delta_norm = float(np.linalg.norm((alpha / rank) * (A @ B)))
cls_w = rng.normal(0.0, 0.2, size=(dim,))
# Train only A, B, cls_w via simple GD for 120 steps (keeping w0 frozen)
scale_lora = alpha / rank
init_loss = None
final_loss = None
for step in range(120):
h = x_data @ (w0 + scale_lora * (A @ B))
logits = h @ cls_w
preds = 1.0 / (1.0 + np.exp(-np.clip(logits, -20, 20)))
loss = float(-np.mean(y_bin * np.log(preds + 1e-12) + (1 - y_bin) * np.log(1 - preds + 1e-12)))
if step == 0:
init_loss = loss
final_loss = loss
d_logits = (preds - y_bin) / n_samples
d_cls = h.T @ d_logits
d_h = np.outer(d_logits, cls_w)
d_w_eff = x_data.T @ d_h
d_A = scale_lora * (d_w_eff @ B.T)
d_B = scale_lora * (A.T @ d_w_eff)
cls_w -= 0.4 * d_cls
A -= 0.4 * d_A
B -= 0.4 * d_B
final_acc = float(np.mean((preds >= 0.5).astype(float) == y_bin))
c4_ok = (
init_delta_norm == 0.0
and lora_pct < 0.5
and adapter_pct < 2.5
and final_loss < init_loss * 0.25
and final_acc >= 0.90
)
cases.append(dict(
name="peft_adapter_and_lora_vs_full_finetune",
inputs=dict(base_hidden=H, layers=L_num, adapter_bottleneck=64, lora_rank=8, toy_rank=rank),
prerequisites="对比 BERT-base 全参微调、冻结特征提取、Adapter 与 LoRA 可训练参数占比,并实测冻结主干 W0 的 LoRA 低秩更新。",
action="验证 LoRA 零初始化(B=0 时增量 ΔW=0)、参数量低于总参 0.5%,以及仅更新低秩矩阵即可使二分类损失大幅下降。",
expected=dict(lora_zero_init_exact=True, peft_under_3pct=True, lora_converges_frozen_backbone=True),
actual=dict(
lora_zero_init_exact=(init_delta_norm == 0.0),
peft_under_3pct=(lora_pct < 0.5 and adapter_pct < 2.5),
lora_converges_frozen_backbone=(final_loss < init_loss * 0.25 and final_acc >= 0.90),
),
measurements=dict(
frozen_head_params=head_params,
lora_r8_params=lora_params,
lora_r8_pct_of_base=round(lora_pct, 3),
adapter_b64_params=adapter_params,
adapter_b64_pct_of_base=round(adapter_pct, 3),
lora_init_delta_norm=init_delta_norm,
lora_init_loss=round(init_loss, 4),
lora_final_loss=round(final_loss, 4),
lora_train_acc=round(final_acc, 4),
),
passed=c4_ok,
))
print(json.dumps(dict(
version=platform.python_version(),
system=platform.system(),
cases=cases,
), ensure_ascii=False))
if __name__ == "__main__":
run_cases()
- 核对右侧词变化传递至 [MASK](双向)、15% 80/10/10 与中文 WWM 整词遮盖、BERT-base 109.48M→ALBERT 11.75M(减 89.27%)及 LoRA 0.271% 零初始化收敛。
所需环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。
当前源码 SHA256:dc885979e1c95b27353c71f9aca26e07d8da61e1ac9c931160a66b3ba361ee06
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。
ZIP SHA256:064c7c5c217f38e6567e54fc485e2a32339ae20825d494c52448b32ba7ea4d62
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么 BERT 在预训练 MLM 阶段只对被选中的 15% 词元中的 80% 替换为 [MASK],而保留 10% 随机词与 10% 原词?
展开参考解答
因为下游微调与推理输入中并不会出现 [MASK] 标记;若 100% 替换为 [MASK] 会造成预训练与微调的输入分布割裂,保留 10% 原词与 10% 随机词迫使模型对所有位置都保持高质量上下文语义编码。