跳到内容

11.2 Causal、Masked 与 Denoising 预训练:自监督标签来自数据,不代表没有假设

硬盘里的 tokenizer 把语料变成 token IDs,阿花留下的训练日志却显示三条不同生产线:一条预测下一个 token,一条恢复被遮住的位置,一条把损坏的 span 还原成完整文本。

它们都不需要人工逐条标注,却不是“模型自己随便学”。Corruption、mask、factorization 和 data mixture 明确定义模型能看到什么、要预测什么。

本课目标

  • 推导 causal language modeling 的条件分解与 label shift;
  • 理解 masked LM 的 corruption 和双向上下文;
  • 区分 span-denoising/encoder–decoder objective;
  • 正确比较 encoder-only、decoder-only 与 encoder–decoder;
  • 把数据去重、污染、许可和 memorization 纳入预训练评估。

1. 自监督不是无监督的同义词

Self-supervised learning 从原始样本内部构造 target:下一个 token、被 mask token、旋转角度、缺失 span。无需人工 label,但 objective、data sampling 和 corruption 都是人为设计。

语言模型学的是训练分布与 loss 下的 conditional statistics。它可能获得可迁移表示和事实模式,也会继承偏见、错误、重复与隐私风险;“读完整个互联网所以理解全部语言”不是可验证结论。

2. Causal Language Modeling

对 token sequence $x_{1:T}$:

$$ p(x_{1:T})=\prod_{t=1}^{T}p(x_t\mid x_{<t}). $$

Negative log-likelihood:

$$ L_{CLM}=-\sum_{t=1}^{T}\log p_\theta(x_t\mid x_{<t}). $$

训练 inputs 与 labels 通常 shift:位置 $t$ 的 hidden state 预测下一个 token。Causal mask 防止读取未来。

python
import torch
from torch.nn import functional as F

# logits: [B, T, V],token_id: [B, T]
def causal_lm_loss(logits, token_id, padding_id):
    prediction = logits[:, :-1, :].contiguous()
    target = token_id[:, 1:].contiguous()
    return F.cross_entropy(
        prediction.view(-1, prediction.shape[-1]),
        target.view(-1),
        ignore_index=padding_id,
    )

真实 model classes 可能内部完成 shift,不能再手动 shift 两次。阅读具体 forward contract,并用人工短序列测试 position–target 对齐。

3. Teacher Forcing 与生成差异

训练时每个 position 的 context 来自真实 prefix,所以可并行计算所有 token loss。生成时 context 包含模型自己采样的 tokens,错误会改变后续分布。

低 teacher-forced perplexity 不保证长文本 coherence、事实性或任务遵循。Generation 还受 decoding、context construction 和 post-training 影响。

4. Masked Language Modeling

MLM 选择部分 positions 做 corruption,让 encoder 在左右上下文下恢复原 token:

$$ L_{MLM}=-\sum_{t\in M}\log p_\theta(x_t\mid \widetilde x). $$

原始 BERT 使用特定比例与 MASK/random/unchanged corruption 方案;其他 masked models 比例和策略可不同。不要把“随机 mask 15%”写成 MLM 定义。

MLM 允许 bidirectional context,适合 representation/classification/token labeling。因为预训练只在 selected positions 计 loss,corruption 分布与 downstream 未 mask 文本存在 mismatch;后续方法会调整 objective/data,不代表 MLM 本身无效。

5. NSP 是历史方案,不是二元结论

原始 BERT 还训练 Next Sentence Prediction,判断两段是否相邻。后续模型有的移除 NSP、有的替换为 sentence-order/contrastive objectives,也有任务可能利用跨句训练。

因此准确表述是:NSP 的收益依 data construction、model 和 downstream task 而异;不能简单写“已发现不重要”,也不能把它当所有 encoder pretraining 的必需组成。

6. Denoising / Span Corruption

Encoder–decoder denoising 先破坏输入,再让 decoder 自回归重建 target。例如删除/替换连续 spans,并用 sentinel tokens 标记缺口。

它同时训练:

  • encoder 读取 corrupted source;
  • decoder 根据 source 与已生成 target 恢复内容;
  • cross-attention 对齐 source–target。

适合 text-to-text transfer,但 generation loss、source/target length 和 corruption 策略决定训练成本。Denoising 不自动带来事实 grounding。

7. 三类常见架构不是任务绝对绑定

典型家族Attention 可见性常见 objective常见用途
Encoder-only双向/fullMLM、contrastive 等encoding、分类、检索
Decoder-onlycausalnext-token CLMgeneration、in-context task
Encoder–decodersource full + target causaldenoising/seq2seq条件生成、转换

这是常见组合,不是数学排他关系。Prefix LM、unified transformer、non-causal decoder 等会混合信息流。选 checkpoint 要看具体 architecture/config/objective,而不是只看品牌名。

8. Data Mixture 是隐形 Objective

总体 loss 是不同 sources/tokens 的加权和。Sampling weights 决定模型在哪类文本上收到多少 update:

$$ L=\sum_d\lambda_d\mathbb E_{x\sim D_d}[L(x)]. $$

Web、books、code、papers、conversation、不同语言的比例会影响能力与偏见。按 raw byte、document 或 token 采样得到的有效 mixture 不同。

记录 source provenance、timestamp、license、language/domain classifier、filter thresholds、dedup 与 mixture schedule。没有 data card 的“几十 TB”无法复现或审计。

9. 去重与 Benchmark Contamination

重复内容会:

  • 让高频文档获得过高权重;
  • 增加 memorization/privacy risk;
  • 让 validation/test 与 train 近重复,虚高指标;
  • 让版权内容被重复采样。

Exact hash 只去完全相同文本;near-dedup 需 shingling/MinHash/embedding 等,并选择 granularity/threshold。Code、模板、引用和翻译使边界复杂。

Benchmark decontamination 要在 tokenizer/normalized/raw 多种视角检查,并报告方法与漏检。只从文件名排除 benchmark 不够。

10. Perplexity 的比较边界

平均 token cross-entropy $H$ 对应:

$$ PPL=e^H. $$

它依赖 tokenization、evaluation text、context length、stride/boundary 和是否含 special/padding tokens。不同 vocabulary 下 token 单位不同,PPL 不能直接横比。

Fixed-window model 评估长文时,disjoint chunks 会丢上下文;sliding window 更接近真实 conditional context,但重复 compute。必须报告 protocol。

Perplexity 衡量 next-token likelihood,不等同事实性、安全、校准或任务 utility。

11. Memorization 与隐私

语言建模需要记住 patterns,特定序列也可能被 verbatim memorized。风险随重复、罕见性、模型容量和训练动态变化。

治理:

  • 训练前 secret/PII detection 与来源过滤;
  • dedup 与 deletion lineage;
  • canary/extraction/membership audits;
  • 输出侧 privacy/safety controls;
  • data subject/license process;
  • checkpoint access 与 incident response。

过滤不能保证完全删除;模型权重不是可逐行查询的数据库,删除请求可能需要 retraining/unlearning 策略和证据边界。

12. 预训练评估是多维的

  • held-out loss/perplexity(严格去污染);
  • downstream transfer/few-shot tasks;
  • factuality 与 temporal cutoff;
  • robustness、calibration、long-context;
  • language/domain coverage;
  • bias/toxicity/privacy/security;
  • compute、throughput、energy 与 failure rate。

测试集数量越多,选择也越可能适应 benchmark。保留真正 blind/private/未来评估,并报告 model/data selection 历史。

常见误区

  • 自监督没有标签也没有人工假设:target 自动构造,objective 仍由人定义。
  • BERT 就是 MLM+NSP 的永恒模板:具体 encoder objectives 多样。
  • GPT 训练和生成完全相同:训练看真实 prefix,生成看自身输出 prefix。
  • Perplexity 可跨 tokenizer 直接比较:token 单位和 protocol 不同。
  • 数据越多只会更好:质量、重复、许可、偏见和 mixture 同样关键。

练习

  1. 手工对齐 CLM inputs/logits/next-token labels,检查 off-by-one。
  2. 设计三种 MLM corruption,说明预训练—下游 mismatch。
  3. 给 span corruption 例子画 encoder/decoder masks。
  4. 比较相同文本在不同 tokenizer 下的 PPL 为什么不可直接横比。
  5. 为预训练 corpus 写 provenance、dedup 与 benchmark contamination 清单。

小结

Causal、masked 和 denoising objectives 从原始文本构造不同监督信号。信息可见性、corruption 与 data mixture 决定模型学到的 conditional task;低 loss 只是一个证据,还必须审计污染、记忆、迁移与安全。

下一课从基础 checkpoint 出发:是继续预训练、全参数微调,还是只训练低秩 adapter,要根据数据、算力、遗忘风险和部署方式选择。

Built with VitePress | Software Systems Atlas