"""Independent NumPy & scikit-learn lab for Pre-trained Models (Ch 15)."""
import json
import platform
import numpy as np
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.pipeline import Pipeline
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 cosine(a: np.ndarray, b: np.ndarray) -> float:
return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
def run_cases():
cases = []
rng = np.random.default_rng(15)
# 1. Static Word Embeddings vs Contextual Self-Attention on Polysemy ("苹果")
vocab = ["吃", "新鲜", "水果", "苹果", "发布", "新款", "手机", "芯片"]
v2i = {w: i for i, w in enumerate(vocab)}
# Static table: every token has one fixed embedding regardless of context
static_table = np.array([
[1.8, 0.1, 0.2, 0.0], # 吃 (food)
[1.7, 0.2, 0.1, 0.0], # 新鲜 (food)
[1.9, 0.1, 0.0, 0.1], # 水果 (food)
[0.9, 0.9, 0.1, 0.1], # 苹果 (polysemous static average)
[0.0, 1.8, 0.1, 0.2], # 发布 (tech)
[0.1, 1.7, 0.0, 0.2], # 新款 (tech)
[0.0, 1.9, 0.2, 0.1], # 手机 (tech)
[0.1, 1.8, 0.1, 0.2], # 芯片 (tech)
], dtype=float)
sent_fruit = [v2i[w] for w in ["吃", "新鲜", "水果", "苹果"]]
sent_tech = [v2i[w] for w in ["发布", "新款", "苹果", "手机"]]
static_cos = cosine(static_table[v2i["苹果"]], static_table[v2i["苹果"]])
def contextual_encode(ids: list[int]) -> np.ndarray:
x = static_table[ids]
scores = (x @ x.T) / np.sqrt(float(x.shape[-1]))
w = softmax(scores, axis=-1)
return w @ x
ctx_fruit = contextual_encode(sent_fruit)[3] # "苹果" in fruit sentence
ctx_tech = contextual_encode(sent_tech)[2] # "苹果" in tech sentence
ctx_cos = cosine(ctx_fruit, ctx_tech)
sim_fruit_to_fruit = cosine(ctx_fruit, static_table[v2i["水果"]])
sim_fruit_to_phone = cosine(ctx_fruit, static_table[v2i["手机"]])
sim_tech_to_phone = cosine(ctx_tech, static_table[v2i["手机"]])
sim_tech_to_fruit = cosine(ctx_tech, static_table[v2i["水果"]])
c1_ok = (
abs(static_cos - 1.0) < 1e-12
and ctx_cos < 0.90
and sim_fruit_to_fruit > sim_fruit_to_phone
and sim_tech_to_phone > sim_tech_to_fruit
)
cases.append(dict(
name="static_vs_contextual_polysemy",
inputs=dict(target_word="苹果", fruit_sentence="吃 新鲜 水果 苹果", tech_sentence="发布 新款 苹果 手机"),
prerequisites="对比静态词向量查表与自注意力上下文编码在同形多义词“苹果”上的表示差异。",
action="核对静态向量在两语境下余弦相似度恒为 1.0,而动态上下文表示按语境自动分离并分别贴近“水果”与“手机”。",
expected=dict(static_identical=True, contextual_disambiguated=True, domain_alignment_correct=True),
actual=dict(
static_identical=abs(static_cos - 1.0) < 1e-12,
contextual_disambiguated=ctx_cos < 0.90,
domain_alignment_correct=(sim_fruit_to_fruit > sim_fruit_to_phone and sim_tech_to_phone > sim_tech_to_fruit),
),
measurements=dict(
static_cos_same_word=round(static_cos, 4),
contextual_cos_across_senses=round(ctx_cos, 4),
fruit_sense_vs_fruit_sim=round(sim_fruit_to_fruit, 4),
fruit_sense_vs_phone_sim=round(sim_fruit_to_phone, 4),
tech_sense_vs_phone_sim=round(sim_tech_to_phone, 4),
tech_sense_vs_fruit_sim=round(sim_tech_to_fruit, 4),
),
passed=c1_ok,
))
# 2. Four Pretraining Objectives: Causal LM, MLM, NSP, RTD
seq_len, vocab_sz = 6, 10
logits_seq = rng.normal(0.0, 1.0, size=(seq_len, vocab_sz))
targets = np.array([2, 4, 1, 7, 3, 5])
probs_seq = softmax(logits_seq, axis=-1)
# (a) Causal LM: predict each next token w_t given w_<t (5 next-token transitions)
lm_loss = float(np.mean([-np.log(probs_seq[t, targets[t + 1]]) for t in range(seq_len - 1)]))
# (b) MLM: compute loss ONLY on masked position index 2 (e.g., "预训练 [MASK] 很强大")
mask_positions = [2]
mlm_loss = float(np.mean([-np.log(probs_seq[i, targets[i]]) for i in mask_positions]))
# (c) NSP: binary cross-entropy on positive continuous pair vs negative random pair
nsp_logits = np.array([[2.1, -0.8], [-1.2, 1.9]]) # [is_next, not_next]
nsp_probs = softmax(nsp_logits, axis=-1)
nsp_labels = np.array([0, 1]) # 0=IsNext, 1=NotNext
nsp_preds = np.argmax(nsp_probs, axis=-1)
nsp_acc = float(np.mean(nsp_preds == nsp_labels))
# (d) RTD (ELECTRA-style): binary discriminator over ALL 6 tokens (1 replaced at idx 2)
rtd_labels = np.array([0, 0, 1, 0, 0, 0])
rtd_scores = np.array([-2.0, -1.8, 2.3, -1.5, -2.1, -1.7])
rtd_probs = 1.0 / (1.0 + np.exp(-rtd_scores))
rtd_loss = float(-np.mean(rtd_labels * np.log(rtd_probs) + (1 - rtd_labels) * np.log(1 - rtd_probs)))
rtd_acc = float(np.mean((rtd_probs >= 0.5).astype(int) == rtd_labels))
c2_ok = lm_loss > 0 and mlm_loss > 0 and nsp_acc == 1.0 and rtd_acc == 1.0 and len(rtd_labels) == seq_len
cases.append(dict(
name="pretraining_objectives_lm_mlm_nsp_rtd",
inputs=dict(seq_len=seq_len, vocab_size=vocab_sz, mlm_masked_indices=mask_positions),
prerequisites="构造确定性序列 logits,分别计算自回归 LM、单位置 MLM、句对 NSP 及全序列 RTD 损失。",
action="验证 LM 按步移位预测、MLM 仅在遮盖位计损、NSP 区分连续/无关句对,以及 RTD 对全部 6 个位置执行替换检测。",
expected=dict(lm_and_mlm_positive_ce=True, nsp_accuracy_1=True, rtd_all_positions_checked=True),
actual=dict(
lm_and_mlm_positive_ce=(lm_loss > 0 and mlm_loss > 0),
nsp_accuracy_1=(nsp_acc == 1.0),
rtd_all_positions_checked=(rtd_acc == 1.0 and len(rtd_labels) == seq_len),
),
measurements=dict(
lm_ce_loss=round(lm_loss, 4),
mlm_ce_loss=round(mlm_loss, 4),
nsp_acc=round(nsp_acc, 4),
rtd_bce_loss=round(rtd_loss, 4),
rtd_positions_evaluated=int(len(rtd_labels)),
),
passed=c2_ok,
))
# 3. Two-Stage Pretrain + Few-Shot Fine-Tune vs From-Scratch Training
# Build synthetic corpus with 2 latent themes (positive/negative) and rich synonym clusters
pos_vocab_core = ["优秀", "流畅", "稳定", "可靠", "清晰", "高效", "精准", "满意", "出色", "惊艳", "实用", "便捷"]
neg_vocab_core = ["卡顿", "报错", "崩溃", "模糊", "缓慢", "失望", "冗长", "缺陷", "混乱", "低效", "繁琐", "糟糕"]
shared_vocab = ["模型", "系统", "体验", "工具", "处理", "文本", "结果", "版本", "界面", "任务"]
def make_docs(n_per_class: int, local_rng: np.random.Generator, vocab_slice: slice):
docs, labels = [], []
p_words = pos_vocab_core[vocab_slice]
n_words = neg_vocab_core[vocab_slice]
for _ in range(n_per_class):
w = list(local_rng.choice(p_words, size=4, replace=False)) + list(local_rng.choice(shared_vocab, size=2, replace=False))
docs.append(" ".join(w))
labels.append(1)
w2 = list(local_rng.choice(n_words, size=4, replace=False)) + list(local_rng.choice(shared_vocab, size=2, replace=False))
docs.append(" ".join(w2))
labels.append(0)
return docs, np.array(labels)
# Large unlabeled pretraining corpus covers ALL 12 positive + 12 negative co-occurring synonyms
unlabeled_docs, _ = make_docs(150, rng, slice(0, 12))
# Tiny labeled training set (only 12 samples using ONLY first 6 synonyms!)
few_train_docs, few_train_y = make_docs(6, rng, slice(0, 6))
# Held-out test set (80 samples using ONLY the UNSEEN last 6 synonyms!)
holdout_docs, holdout_y = make_docs(40, rng, slice(6, 12))
# Model A: Traditional from-scratch TF-IDF + LogisticRegression trained ONLY on 12 labeled docs
scratch_pipe = Pipeline([
("tfidf", TfidfVectorizer(token_pattern=r"(?u)\b\w+\b")),
("clf", LogisticRegression(random_state=42)),
])
scratch_pipe.fit(few_train_docs, few_train_y)
scratch_acc = float(accuracy_score(holdout_y, scratch_pipe.predict(holdout_docs)))
# Model B: Two-stage Pretrained representation (TF-IDF + TruncatedSVD fit on 300 unlabeled docs) + few-shot head
pre_vec = TfidfVectorizer(token_pattern=r"(?u)\b\w+\b").fit(unlabeled_docs)
pre_svd = TruncatedSVD(n_components=4, random_state=42).fit(pre_vec.transform(unlabeled_docs))
x_tr_pre = pre_svd.transform(pre_vec.transform(few_train_docs))
x_te_pre = pre_svd.transform(pre_vec.transform(holdout_docs))
ft_clf = LogisticRegression(random_state=42).fit(x_tr_pre, few_train_y)
pretrain_acc = float(accuracy_score(holdout_y, ft_clf.predict(x_te_pre)))
c3_ok = pretrain_acc >= 0.90 and scratch_acc <= 0.60 and (pretrain_acc - scratch_acc) >= 0.35
cases.append(dict(
name="few_shot_transfer_vs_from_scratch",
inputs=dict(unlabeled_docs=len(unlabeled_docs), labeled_train=len(few_train_docs), unseen_synonym_test=len(holdout_docs)),
prerequisites="在 300 条无标注语料上预训练 SVD 语义子空间,仅用 12 条前半年同义词标注微调,并在 80 条未见同义词留出测试集评估。",
action="对比从零监督训练与两阶段预训练+微调的跨词泛化准确率。",
expected=dict(pretrained_beats_scratch_by_35pct=True, pretrained_high_acc=True),
actual=dict(
pretrained_beats_scratch_by_35pct=(pretrain_acc - scratch_acc) >= 0.35,
pretrained_high_acc=pretrain_acc >= 0.90,
),
measurements=dict(
from_scratch_holdout_acc=round(scratch_acc, 4),
pretrained_finetune_holdout_acc=round(pretrain_acc, 4),
accuracy_gain=round(pretrain_acc - scratch_acc, 4),
),
passed=c3_ok,
))
# 4. Fine-Tuning Engineering: max_length truncation/padding mask, Early Stopping, INT8 Quantization
raw_lens = [3, 6, 12]
max_len = 8
padded_ids = []
attn_masks = []
for ln in raw_lens:
clipped = list(range(1, min(ln, max_len) + 1))
mask = [1] * len(clipped) + [0] * (max_len - len(clipped))
clipped = clipped + [0] * (max_len - len(clipped))
padded_ids.append(clipped)
attn_masks.append(mask)
# Early stopping simulation on validation loss trajectory (patience=2)
val_losses = [0.68, 0.45, 0.31, 0.33, 0.36, 0.42]
best_loss, wait, stop_epoch = float("inf"), 0, len(val_losses)
for ep, vl in enumerate(val_losses, start=1):
if vl < best_loss - 1e-6:
best_loss = vl
wait = 0
else:
wait += 1
if wait >= 2:
stop_epoch = ep
break
# Symmetric INT8 post-training quantization of FP32 weight matrix
w_fp32 = rng.normal(0.0, 0.5, size=(64, 64)).astype(np.float32)
scale = float(np.max(np.abs(w_fp32)) / 127.0)
w_int8 = np.clip(np.round(w_fp32 / scale), -127, 127).astype(np.int8)
w_deq = w_int8.astype(np.float32) * scale
fp32_bytes = int(w_fp32.nbytes)
int8_bytes = int(w_int8.nbytes)
mem_saving = 1.0 - int8_bytes / fp32_bytes
quant_rmse = float(np.sqrt(np.mean((w_fp32 - w_deq) ** 2)))
c4_ok = (
[len(r) for r in padded_ids] == [8, 8, 8]
and [sum(m) for m in attn_masks] == [3, 6, 8]
and stop_epoch == 5
and abs(mem_saving - 0.75) < 1e-12
and quant_rmse < 0.01
)
cases.append(dict(
name="finetuning_hyperparams_early_stopping_and_quantization",
inputs=dict(raw_lengths=raw_lens, max_length=max_len, patience=2, weight_shape=[64, 64]),
prerequisites="核对序列 max_length 截断填充掩码、验证集早停(patience=2)及 FP32 到 INT8 权重量化。",
action="验证所有样本对齐至 max_length=8、早停在第 5 轮触发避免过拟合、INT8 精确节省 75% 内存且反量化 RMSE <0.01。",
expected=dict(max_length_aligned=True, early_stop_epoch_5=True, int8_saves_75pct_low_err=True),
actual=dict(
max_length_aligned=([len(r) for r in padded_ids] == [8, 8, 8] and [sum(m) for m in attn_masks] == [3, 6, 8]),
early_stop_epoch_5=(stop_epoch == 5),
int8_saves_75pct_low_err=(abs(mem_saving - 0.75) < 1e-12 and quant_rmse < 0.01),
),
measurements=dict(
mask_active_counts=[sum(m) for m in attn_masks],
best_val_loss=best_loss,
early_stop_epoch=stop_epoch,
fp32_bytes=fp32_bytes,
int8_bytes=int8_bytes,
memory_reduction_pct=round(mem_saving * 100.0, 2),
quant_rmse=round(quant_rmse, 6),
),
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-pre-trained-models-lab/explore-pre-trained-models.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-pre-trained-models.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。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a554.zip
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a545.zip