跳到内容

第 13 卷 / 第 11 章 / 第 2 课

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

Causal、masked 和 denoising 目标都从原始数据构造 target。Mask、corruption 与概率分解决定模型能看到什么、预测对什么才会降低 loss;省去逐条人工标注,也没有省去这些设计。

本课目标 ​

  • 推导 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 都是人为设计。 一些分类把自监督归入无监督学习;这里区分的是 target 的构造方式,不是宣称两类互斥。

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

2. Causal Language Modeling ​

对 token sequence x1:T:

p(x1:T)=∏t=1Tp(xt∣x<t).

Negative log-likelihood:

LCLM=−∑t=1Tlog⁡pθ(xt∣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 and attention_mask: [B, T].
def causal_lm_loss(logits, token_id, attention_mask):
    if logits.ndim != 3 or token_id.shape != logits.shape[:2]:
        raise ValueError("expected matching [B, T, V] and [B, T] shapes")
    if attention_mask.shape != token_id.shape or logits.shape[1] < 2:
        raise ValueError("matching mask and at least two positions required")
    if not torch.all((attention_mask == 0) | (attention_mask == 1)):
        raise ValueError("attention_mask must contain only 0 and 1")
    present = attention_mask.bool()
    valid = present[:, :-1] & present[:, 1:]
    if not valid.any():
        raise ValueError("no supervised next-token pairs")
    target = token_id[:, 1:].clone().masked_fill(~valid, -100)
    return F.cross_entropy(
        logits[:, :-1, :].reshape(-1, logits.shape[-1]),
        target.reshape(-1),
        ignore_index=-100,
    )

# ID 3 is both EOS and PAD; the position mask distinguishes them.
ids = torch.tensor([[1, 2, 3, 3], [0, 1, 2, 3]])
mask = torch.tensor([[1, 1, 1, 0], [0, 1, 1, 1]])
logits = torch.zeros(2, 4, 4, requires_grad=True)
loss = causal_lm_loss(logits, ids, mask)
loss.backward()
print(round(loss.item(), 4))  # 1.3863 = log(4)

Mask 只保留相邻的非 padding 预测对,因此共用 PAD ID 的有效 EOS 仍参与 loss。首个正文 token 需要前置 BOS 才能被监督;未放 BOS 就会略过它。函数面向连续序列,未包含 assistant-only 或文档隔离 packing 的额外 mask。模型类也可能内部 shift,使用前要核对,避免移位两次。

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:

LMLM=−∑t∈Mlog⁡pθ(xt∣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=∑dλdEx∼Dd[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=eH.

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

Disjoint windows 会丢上下文。Sliding windows 以重复 compute 换取更长上下文,但每个评估 target 只应计一次 loss,重复的 context 位置要屏蔽。普通自回归 PPL 也不能直接套到 MLM;pseudo-perplexity 使用的是另一种协议。见 Transformers 困惑度说明。

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