EECS498 · Transformer IV · 12

What You Actually Trained

你当年训练的不是一个会“一次吐出答案”的 arithmetic oracle,而是一个条件自回归生成模型:给定题目和正确答案前缀,预测下一个答案 token。

95–115 分钟WI22 A5Shift · Mask · Loss · Gradient

30-second recall

30 秒回忆

Notebook 在 5,000 条 arithmetic pairs 上训练 encoder–decoder;保存记录包括 tiny-set overfit 1.0 和 validation accuracy 约 0.8213。

  1. target shift 与 causal mask 为什么两者都需要?
  2. training 为什么能并行所有 target positions?
  3. 一个 token 的 loss 如何更新 encoder embedding?

Before We Start

target=BOS POSITIVE 0 4 EOS,decoder input 是?

谁不被 optimizer 更新?

Inference 时能否一次并行生成所有未知未来 tokens?

Question: BOS NEGATIVE 30 subtract NEGATIVE 34 EOS
Target answer: BOS POSITIVE 0 4 EOS

Problem · 怎样把一条答案变成许多监督信号?

我们需要学习:

P(answer_t | question, answer_<t)

答案长度 5 并不意味着只有一个训练 label。右移一位后,每个相邻 pair 都提供一个 next-token prediction:

decoder input:      BOS      POSITIVE      0        4
prediction target: POSITIVE     0          4       EOS

position 0: P(POSITIVE | question, BOS)
position 1: P(0 | question, BOS POSITIVE)
position 2: P(4 | question, BOS POSITIVE 0)
position 3: P(EOS | question, BOS POSITIVE 0 4)
Mental model

Teacher forcing 把已知正确 prefix 送进 decoder;shift 定义每个位置的 label;causal mask 保证该位置无法偷看更右侧 target。

Shift、mask、teacher forcing 不是同义词

Shift把输入 position t 与 label position t+1 对齐
Causal mask阻断 hidden computation 对未来 target positions 的访问
Teacher forcingtraining 时 prefix 来自 ground truth,而不是模型自己的 samples
只有 shift,没有 mask?

虽然当前位置输入是前一个 token,多层 self-attention 仍可读取右边已经放入 batch 的 ground-truth tokens,发生 label leakage。

只有 mask,没有 shift?

如果位置 t 同时输入 token t 又以 token t 为 target,模型可以从 residual path 直接复制当前 token;任务不是 next-token prediction。

为什么 training 能并行,而 inference 不能?

Training 已知完整 ground-truth answer,可一次构造所有 shifted inputs。triangular mask 让第 t 行只使用合法 prefix,因此四个 positions 可在同一个 tensor forward 中计算。

training:  known [BOS, POSITIVE, 0, 4] → 4 position logits in one forward
inference: known [BOS] → sample POSITIVE
           known [BOS, POSITIVE] → sample 0
           known [BOS, POSITIVE, 0] → sample 4
           known [BOS, POSITIVE, 0, 4] → sample EOS

Inference 的未来 prefix 取决于尚未算出的 token,因此 across time 自回归;每一步内部仍能并行 heads、features 和已有 positions。teacher forcing 的训练条件与模型自身 samples 的推理条件不同,这也引出 exposure bias。

Worked Backward · 追踪 token “4” 的错误

在第三个 prediction position,正确 label 是 4。设模型概率:

P(3)=0.55
P(4)=0.20   ← correct
remaining vocab total=0.25

token loss = -log P(4) = -log(0.20) ≈ 1.609

cross entropy 对 logits 的 gradient 是 p - one_hot(label):class 4 的 logit 得到负方向 gradient(gradient descent 会提高它),错误 class 3 得到正方向 gradient(会降低它)。接下来 chain rule 沿整个使用路径传播:

  1. Vocab projection:哪些 hidden features 应支持 token 4?
  2. Decoder representation:当前 answer state 应怎样改变?
  3. Decoder MLP / self-attention:prefix 应提取哪些 features?
  4. Cross-attention:query、source addresses 与 payload 如何影响该 state?
  5. Encoder blocks:question memory 怎样编码 operands/signs?
  6. Embedding rows:本例访问过的 token rows 收到 gradient。
loss scalar
↓ ∂L/∂logits                  [N,Ka-1,V]
vocab projection
↓ ∂L/∂decoder hidden          [N,Ka-1,M]
decoder blocks / QKV / MLP
↓ cross-attention paths
encoder contextual states    [N,Kq,M]
↓ encoder blocks
question embeddings + answer embeddings
↓
selected rows of E            [V,M]

“End-to-end”不是说所有对象都可训练;它表示所有可微分 parameters 通过 loss 连接在同一计算图中。

谁训练,谁不训练?

对象gradient?原因
toy tokenizer / token_dict否离散 Python rule,不是 tensor Parameter
embedding table是lookup 输出参与后续 loss
WQ/WK/WV/WO是决定 routing 与 payload
MLP / LayerNorm parameters是改变 hidden representations
vocab projection是hidden → logits
mask否固定约束,不是 learned weight

Your Code · target slicing 正是 objective

Your code · 2023

win22/A5/transformers.py · Transformer.forward()

View source →
q_emb = self.emb_layer(ques_b)
a_emb = self.emb_layer(ans_b)
q_emb_inp = q_emb + ques_pos
a_emb_inp = a_emb[:, :-1] + ans_pos[:, :-1]

dec_out = self.decoder(a_emb_inp, enc_out)
pred = self.proj_to_vocab(dec_out)

a_emb[:, :-1] 删除最后一个 target token,因为它没有后继 label;loss 则应与 ans_b[:,1:] 对齐。pred [N,Ka-1,V] 在每个 position 给整个 vocabulary 的 logits。

Inline check. answer shape [32,5]、V=16,shift 后 logits shape?

Historical experiment evidence

Notebook 保存了 tiny dataset overfit 到 accuracy 1.0 的检查,以及完整训练约 0.8213 validation accuracy。tiny overfit 的教学意义不是“模型泛化很好”,而是验证 pipeline 至少能让 loss 驱动参数拟合少量 examples;完整 validation 才开始反映泛化。

Misconception diagnosis

Teacher forcing 不是把 label 直接交给同一位置。正确 token t 作为输入,目标是 t+1;causal mask 又保证 position t 的 hidden state 不能从右侧偷看 t+1。

Deep Dive · padding loss 与 causal mask 是两层不同约束

Causal mask 控制 hidden state 可以读取哪些 positions;loss mask 控制哪些 logits 计入 objective。padding position 即使不该计入 loss,也最好不要作为 attention source;反之,一个合法 context token 可不计 loss,却仍作为条件被后续 positions 使用。

End-of-Lesson Deep Checks

为什么 training 可以同时产生四个 answer logits,却没有泄漏?

所有 ground-truth prefix positions 已知,matrix operations 可并行;causal mask 保证每一行只依赖它应有的 prefix。

loss 能更新 question embedding,即使 label 都在 answer side 吗?

能。answer logits 依赖 cross-attention,cross-attention 依赖 encoder states,encoder states 依赖 question embeddings。

tokenizer 为什么不能自动从 cross entropy 收到 gradient?

它执行离散切分/字典 lookup 规则,不是计算图中的连续 Parameter。现代 tokenizer 往往也先独立训练,再固定用于 LM training。

若 P(correct) 从 .20 升到 .40,token CE 怎样变?

从约 1.609 降到约 0.916;提高正确 token probability 降低 loss。

Transfer Questions

  1. 答案长度各不相同,batch 中 padding 后,causal mask、padding attention mask、loss mask 各屏蔽什么?
  2. 若 inference 第一个 token 预测错,后续条件发生什么变化?这与 teacher forcing 有何差异?
  3. 若共享 input embedding 与 vocab projection weights,token 4 的 loss 会通过哪两种角色影响同一矩阵?

闭卷解释

  1. 为什么 target shift 与 causal mask 两者都要有?
  2. 为什么 training 可并行而 generation across time 不可?
  3. 从错误 token 的 loss 讲到 question embedding 的 gradient。
  4. 精确区分 tokenizer、embedding 与 vocab projection。

Then I implemented: answer slicing、causal decoder、vocab projection、cross entropy training.

Now I understand: 每个答案位置都在做条件 next-token prediction;一个 scalar loss 通过完整 encoder–decoder 计算图更新所有参与预测的 continuous parameters。

Connection · QA 是不是另一种 objective?

下一课把 encoder–decoder 的 P(answer|question) 改写成 decoder-only chat sequence,说明 instruction/QA training 仍是同一组条件 next-token factors。

Based on your implementation