"""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()
本例需在 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。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境: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。
入口文件:projects/nlp-bert-encoder-lab/explore-bert-encoder.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-bert-encoder.py,或下载右侧课程工程包。 - 确认本地已准备 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。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a545.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a546.zip