预训练模型
核对预训练+微调范式、三代语言表示演进、Encoder/Decoder/Enc-Dec 架构与四类预训练任务,离线实测动态一词多义消歧、小样本迁移增益、早停与 INT8 量化。
学完这一章,你能够
- 核对预训练+微调范式、三代语言表示演进、Encoder/Decoder/Enc-Dec 架构与四类预训练任务,离线实测动态一词多义消歧、小样本迁移增益、早停与 INT8 量化。
预训练模型核心思想、传统对比与三代演进
预训练模型(Pre-trained Models)先在海量无标注文本上学习通用语言规律,再迁移至下游任务进行轻量微调(Fine-tuning),其核心支柱为“两阶段学习、跨任务迁移学习与底层参数共享”。相较从零训练的传统监督 NLP 模型,预训练范式大幅降低标注成本并显著提升泛化与开发效率(详见下表 1)。
其发展历程可分为三代:(1)词嵌入时代(2013–2017)以 Word2Vec、GloVe、FastText 为代表(常用 Gensim 训练词向量),产出上下文无关的静态词表,无法区分一词多义;(2)上下文感知时代(2018–2019)由 ELMo、ULMFiT 引入双向语言模型与动态词向量,首次按语境区分多义词;(3)Transformer 时代(2019 至今)以 BERT、GPT、T5 为里程碑,依托自注意力架构与大规模预训练实现强大的跨任务迁移。本站实测同形多义词“苹果”在“吃 新鲜 水果 苹果”与“发布 新款 苹果 手机”两语境下的向量表现:静态查表余弦相似度恒为 1.0000 无法区分词义,经自注意力上下文编码后两语境向量余弦相似度降至 0.3484,水果语境下的“苹果”与“水果”相似度达 0.9875(对“手机”仅 0.2020),科技语境下与“手机”相似度达 0.9865(对“水果”仅 0.2092)。
三大主流架构与自回归/MLM/NSP/RTD 预训练目标
基于 Transformer 的主流预训练模型演化出三大架构路线:(1)纯编码器(Encoder)架构,如 BERT、RoBERTa、ALBERT,依托双向自注意力深度理解全文,擅长分类、抽取式问答与序列标注;(2)纯解码器(Decoder)架构,如 GPT-3、GPT-4,采用自左向右的单向因果注意力,擅长开放文本生成与对话;(3)编码器-解码器(Encoder-Decoder)架构,如 T5、BART,兼顾双向源端编码与自回归目标生成,适配翻译与摘要等序列转换任务。
围绕不同架构衍生出多类自监督预训练目标:(1)自回归语言模型(LM)按链式条件概率 P(w_t | w_1, ..., w_{t-1}) 逐步预测下一词;(2)掩码语言模型(MLM)随机遮盖部分词项(如将“预训练模型很强大”遮蔽为“预训练[MASK]很强大”)并仅在遮盖位预测原词“模型”;(3)下一句预测(NSP)二分类判定两句是否连续(如正例“预训练模型很强大”接“它们可以处理多种NLP任务”,负例接无关句“今天天气真好”);(4)其他目标如 ELECTRA 的替换 token 检测(RTD,对全序列逐位判别是否被生成器替换)与 ALBERT 的句子顺序预测(SOP)。本站实测确定性 6 词序列四项任务损失,核对自回归 LM 交叉熵 2.4713、单掩码位 MLM 交叉熵 3.9316、NSP 句对判别准确率 1.0000,以及 RTD 覆盖全部 6 个位置的二元交叉熵 0.1434。
迁移微调实战、关键超参数与量化早停验证
工程上可借助 Hugging Face Transformers 的 pipeline 快速推理(注:默认 sentiment-analysis 管线多加载英文权重,中文情感分析应显式指定中文微调权重而非直接喂中文),或按“加载预训练权重 → 准备标注集 → 挂载任务头 → Trainer 微调”四步定制下游模型(典型超参数见下表 2)。为离线验证“预训练+少样本微调”的迁移优势,本站在 300 条无标注语料上先学习 4 维 SVD 语义表示,再仅用 12 条前半组同义词标注样本微调分类头,于 80 条完全由未见后半组同义词构成的留出测试集评测:从零训练的 TF-IDF 基线准确率仅 0.5500(近似随机猜测),而两阶段预训练+微调准确率跃升至 1.0000,净增益 +0.4500。
预训练模型几乎覆盖全部核心 NLP 应用场景:文本分类(情感分析、垃圾邮件检测、主题分类)、问答系统(抽取式与开放域问答)、文本生成(摘要、对话与内容创作),以及命名实体识别(NER)、机器翻译与语义相似度计算。
工程选型实践建议与未来演进方向
落地微调可遵循四条实践准则:(1)模型选型:理解分类优先 BERT 类、生成选 GPT 类、边缘受限考虑 DistilBERT 蒸馏版;(2)资源管理:显存不足时调小 batch_size(配梯度累积)、严控 max_length 截断填充掩码并启用量化压缩;(3)性能优化:微调学习率宜小(常在 2e-5 附近)、启用 Early Stopping 防过拟合、优先使用 AdamW 解耦权重衰减;(4)持续跟进 Hugging Face 社区、arXiv 论文与开源实践。本站实测核验了上述工程控件:长度 [3, 6, 12] 的批次经 max_length = 8 统一截断/补零后有效掩码计数精确为 [3, 6, 8];验证损失在第 3 轮触底 0.31 后连续两轮回升,patience = 2 早停于第 5 轮精准触发;64×64 FP32 权重(16,384 字节)经对称 INT8 量化降至 4,096 字节(内存精确节省 75.00%),反量化 RMSE 仅 0.005313。
展望未来,预训练模型将沿着更大参数与上下文规模(如万亿级前沿模型)、文本/图像/语音深度多模态融合、更高训练推理能效优化、垂直专业领域自适应,以及消除社会偏见与有害输出的伦理安全治理五大方向持续演进。
传统 NLP 模型与预训练模型核心维度对比
| 特征 | 传统NLP模型 | 预训练模型 |
| 数据需求 | 高度依赖大规模任务专属人工标注数据 | 只需少量下游标注数据即可通过迁移取得高准确率(实测 12 条微调达 1.00) |
| 训练方式 | 针对单一任务从随机初始化从零开始训练 | 大规模无标注通用预训练 + 小规模任务微调两阶段范式 |
| 泛化能力 | 仅限训练集词表与单一任务(实测未见同义词仅 0.55) | 跨词与跨任务通用语义迁移能力强 |
| 开发效率 | 低,每项新任务均需重新设计特征与训练 | 高,复用统一预训练底座并快速适配任务头 |
预训练模型微调关键超参数与典型值
| 参数 | 说明 | 典型值 |
| learning_rate | 微调学习率,需保持较小步长以免破坏已学通用权重 | 2e-5(常在 1e-5 ~ 5e-5 间调节) |
| batch_size | 单步梯度更新的样本批大小,受显存上限约束 | 16 / 32(显存不足时调小并配合梯度累积) |
| num_train_epochs | 遍历微调训练集的总轮数,常配合早停防过拟合 | 3-5(实测验证损失回升时 patience=2 及时早停) |
| max_length | 单条序列最大词元长度,超长截断、不足补零并生成注意力掩码 | 512(实测截断填充后有效掩码严格对齐真实长度) |
运行静态与动态一词多义消歧、四类预训练损失、少样本迁移对比与 INT8 量化实验
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
预训练阶段在海量无标注语料中通过共现分布将同义词映射到相邻的语义子空间;即便某些近义词未出现在小规模标注集中,微调分类头仍能借助共享子空间实现泛化,而从零词袋模型对未见词权重恒为零。