EECS498 · Transformer V · 13

From Your Toy Transformer to Modern LLMs

Question/Answer training 没有神秘的新 objective。把 question 放进 context,把 answer 放进后续 positions,仍然是在最大化每个 answer token 的 conditional next-token probability。

90–110 分钟Bridge to CS336Encoder–Decoder ↔ Decoder-only

30-second recall

30 秒回忆

你当年的模型有 encoder、decoder、cross-attention 与 16-token toy vocab。GPT/Llama 通常 decoder-only,但 token→attention→MLP→logits 的核心链仍在。

  1. 没有 encoder 时,question information 放在哪里?
  2. SFT 为什么常把 question token loss 设为 0?
  3. QA 如何分解成 next-token factors?

Before We Start

Decoder-only QA 中,answer token 的条件包含什么?

SFT 常见 answer-only loss mask 的作用?

EECS498 与 GPT 最大的结构差别之一?

同一 arithmetic pair:BOS NEGATIVE 30 subtract NEGATIVE 34 EOS → BOS POSITIVE 0 4 EOS,现在改写成一条 user/assistant causal sequence。

核心等式 · QA 仍是 conditional next-token prediction

给 question Q 与 answer tokens A=(a₁,…,aT):

P(A | Q) = ∏ₜ P(aₜ | Q, a₁, …, aₜ₋₁)

右边每一项正是 next-token probability。所谓 instruction model 并不需要一个“理解整道题后一次输出答案”的特殊 loss;它通过许多局部的 next-token cross-entropies学习整个 conditional distribution。

Mental model

QA 的 Q 是 prefix condition,A 是被逐 token factorize 的 target。架构可以改变条件进入模型的路径,objective 仍是 next-token prediction。

两种架构怎样表达同一个条件关系?

EECS498 encoder–decoder

Question → Encoder memory
Answer prefix → Decoder queries
cross-attention connects them

P(aₜ | encoder(Q), a<t)

Decoder-only chat model

<user> Question
<assistant> Answer

one causal sequence
P(aₜ | Q tokens, role tokens, a<t)

Decoder-only 模型不需要 cross-attention,因为 question tokens 已经位于 answer tokens 左侧。causal self-attention 允许 answer position 直接读取整段 prompt;同一个 block 同时承担 prefix integration 与 answer generation。

Worked Example · 把 arithmetic QA 序列化

<user>
BOS NEGATIVE 30 subtract NEGATIVE 34 EOS
<assistant>
BOS POSITIVE 0 4 EOS

causal positions:
... question ... <assistant> BOS → predict POSITIVE
... question ... <assistant> BOS POSITIVE → predict 0
... question ... <assistant> BOS POSITIVE 0 → predict 4
... question ... <assistant> BOS POSITIVE 0 4 → predict EOS

role/separator tokens 不是装饰。它们让同一 sequence 中“谁说的话”“哪里开始回答”成为可学习边界。现代 chat template 更复杂,但本质仍是把结构编码进 token sequence。

Context mask 与 loss mask 不要混淆

tokens:    <user> question ... <assistant> answer ...
attention: causal — answer 可读左侧 question
loss mask:    0       0 ...       0        1 1 1 ...

question tokens: context, often no supervised loss
answer tokens:   context for later answer + prediction targets
  1. 完整 sequence 进入 causal Transformer,question hidden states 正常计算。
  2. answer positions 用 attention 读取 question 与 earlier answer states。
  3. vocab head 对所有 positions 可产生 logits。
  4. loss mask 只汇总 assistant target positions 的 cross entropy。
  5. 这些 answer losses 仍通过 attention path 更新承载 question 的 parameters/embeddings。
如果 question positions 的 loss 也设为 1?

仍是合法 language modeling,但 objective 还要求模型拟合 user prompt 的 token distribution。SFT 中常屏蔽 prompt loss,是为了把有限监督重点放在“如何回答”;它不是数学上唯一选择。

如果去掉 role/separator tokens?

模型仍看到字符串,但“用户输入结束、assistant 输出开始”的边界变得含糊;相同文本在不同角色下难以区分。

Modern decoder-only 的 representation flow

token IDs[N,K]
embedding + position[N,K,M]
causal self-attention[N,K,M]
MLP / residual blocks[N,K,M]
vocab logits[N,K,V]

每一层仍重复上一课的两个核心动作:attention 跨 positions 动态读取;MLP 在每个 position 内变换 features。规模、tokenizer、normalization、position method 与工程实现显著进化,但 tensor 的角色链没有断裂。

Then vs Now · 哪些相同,哪些真的不同?

DimensionEECS498 WI22 modelModern GPT/Llama family
ArchitectureEncoder + decoder + cross-attention通常 decoder-only
Tokenizer人工 16-token vocab,digitsbyte/subword tokenizer,大词表
Positionabsolute sinusoidal-style常见 RoPE 等
Objectiveconditional answer next-tokenpretraining next-token;SFT conditional next-token
Scale5k arithmetic pairs大规模、多域语料与后训练
Core mechanismembedding, QKV attention, MLP, logits仍是这些核心模块的深层堆叠
Misconception diagnosis

“Decoder-only 没有 encoder,所以它不能理解 question”是错误的。Question tokens 的 causal hidden states 位于同一 sequence 前部;answer queries 可直接读取它们。它缺少的是独立 encoder/cross-attention 接口,不是条件信息。

Your Code · 现代模型仍认得这段骨架

Your code · 2023

win22/A5/transformers.py · SelfAttention

View source →
query = self.q(query)
key = self.k(key)
value = self.v(value)
y, weights = scaled_dot_product_no_loop_batch(
    query, key, value, mask
)

现代实现会融合 projections、使用 optimized kernels、KV cache、GQA 等,但逻辑仍是:固定 learned projections 产生本次输入的 Q/K/V,动态构造 routing,再混合 values。

Training logits 与实际 generation

模型输出的是 vocabulary logits,不是直接输出字符串。Generation loop 重复:

current token IDs
→ forward
→ take last-position logits [V]
→ sampling / argmax
→ append chosen ID
→ stop at EOS or limit

temperature、top-k、top-p 改变从 logits 选择 token 的策略,不改变模型所训练的 conditional probabilities。KV cache 保存过去 positions 的 K/V,避免每步重复计算;它优化推理成本,不改变 causal dependence。

Deep Dive · Pretraining、SFT、preference optimization 的位置

Pretraining 用海量 causal sequences 学一般 next-token distribution;SFT 用高质量 instruction/response sequences塑造条件行为;preference optimization 再利用偏好信号改变回答分布。它们的数据与 loss 形式可能不同,但本课要保留的主干是:最终生成仍逐 token,hidden state 仍由 embedding、attention、MLP 建立。

End-of-Lesson Deep Checks

为什么 P(A|Q) 的 product 表明 QA 没有新 objective?

每个 factor 都是给定 Q 与 earlier answer 的 next-token probability;cross entropy 正是在这些 factors 上训练。

Loss mask(question)=0 后,question embeddings 还会收到 gradient 吗?

会。answer loss 依赖 answer attention 对 question states 的读取,因此有间接 gradient path。

Encoder–decoder 与 decoder-only 的条件信息路径分别是什么?

前者经 encoder memory + cross-attention;后者经同一 causal sequence 中较早的 question positions。

KV cache 为什么不让所有未来 tokens 并行生成?

它只复用已生成 prefix 的 K/V;未来 token identity 仍依赖前一步 sample,尚不可知。

Transfer Questions

  1. 若 chat sequence 包含 system、user、assistant 三段,answer position 可读哪些 tokens?哪些 positions 应计 loss 由什么训练选择决定?
  2. 一个 decoder-only translation model 把 source language 放在 prefix、target 放后面,它与 encoder–decoder translation 的主要信息路径差别是什么?
  3. 如果 vocabulary 从 16 增至 100k,哪些 tensor shape 改变,attention matrix shape 是否一定改变?

闭卷解释

  1. 从 P(A|Q) 解释 QA 为什么仍是 next-token prediction。
  2. 为什么 loss mask 不会把 question 从 context 中删除?
  3. 当年 encoder–decoder 与 GPT decoder-only 的信息路径差异。
  4. 列出从 token IDs 到 next token 的完整 representation chain。

Then I implemented: toy vocab、encoder memory、decoder queries、conditional answer logits.

Now I understand: 现代 chat model 改用一条 causal sequence 表达条件,但核心仍是 token IDs → contextual states → vocab logits → conditional next token。

Connection · 这条主线结束在哪里?

它不结束在某个 API。只要能追踪 token、position、routing、feature transformation、logits 和 loss,你就能把当年的实现映射到今天更大、更快的模型,而不把二者误说成完全相同。

Based on your implementation