仍然以翻译为例:encoder 可以同时读整句原文,decoder 生成下一个词时,却不能偷看尚未写出的译文。原始 Transformer 用不同的 attention 和 mask 处理这两种条件。沿着一句话走过 encoder、decoder,再回来看每个 block,结构就不只是几排重复的方框了。原版 Transformer 用 attention 在位置之间搬信息、用 FFN 在每个位置内部做变换;encoder 和 decoder 的区别,主要在 mask 和 attention 从哪里读。

逐概念双语 · CONCEPT-BY-CONCEPT

默认先读中文。每张卡片点右上角 English ↻,就能在原位置查看同一概念的等价英文;不需要回到页首,也不会丢掉阅读位置。

先交换位置信息,再逐位置变换

先忘掉那张塞满箭头的大框图。Transformer 一层其实只反复做两件事:attention 去别的位置拿信息,FFN 留在当前位置加工信息。 原版仍然是 encoder–decoder,但 recurrence 被彻底拿掉了。

Move information, then transform it

Forget the arrow-heavy architecture diagram for a moment. A Transformer layer repeats two operations: attention reads information from other positions; the FFN transforms that information at the current position. The original architecture is still an encoder–decoder, but recurrence is removed completely.

一层只有两类计算

  1. Attention mixing:不同 token 之间交换信息。
  2. Channel mixing / FFN:每个 token 独立变换自己的通道。

外面再套 residual connection 与 normalization。堆很多层,本质上还是反复“出去找信息 → 回来加工信息”。这样记,比背整张结构图轻松很多。

A layer has only two jobs
  1. Attention mixing exchanges information across token positions.
  2. Channel mixing / FFN transforms each token's channels independently.

Residual connections and normalization wrap those two operations. Stacking layers means repeating “go out and read → come back and transform.” This mental model is more useful than memorizing the full block diagram.

三处 attention 在问不同的问题

位置 Query Key / Value mask 作用
encoder self-attention source source padding 双向理解输入
decoder self-attention target prefix target prefix causal + padding 只能看已经生成的 token
decoder cross-attention decoder state encoder states source padding 从输入中取当前所需证据

scaled dot-product attention:

$$\text{Attention}(Q,K,V)=\text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}+M\right)V$$

$M$ 是 mask:允许的位置加 0,禁止的位置加 $-\infty$。

别把 padding 和 padding mask 混成一步。比如两条输入长度为 3 和 5,collator 可以先把它们补到 5;mask 再标记第一条最后两个位置不可作为 key 读取,不负责添加 token,也不必把所有输入都补到模型最大长度。

对有效的 query 行,decoder self-attention 同时要求“key 不是 padding”且“key 不在未来”。按行是 query、列是 key 的约定,禁止的是严格上三角,对角线仍能读取:当前输入用来预测下一个 token,不会因此偷看答案。Cross-attention 则可以读取整句 source,无须按译文位置把 source 截成前缀。这里说的是原版结构;packed 样本、局部 attention 等还会增加别的可见性约束。Transformer §3.2.3

The three attention sites ask different questions
Site Query Key / value Mask Role
encoder self-attention source source padding bidirectional source understanding
decoder self-attention target prefix target prefix causal + padding prevent future access
decoder cross-attention decoder state encoder states source padding retrieve source evidence

All three use the same scaled dot-product formula:

$$\text{Attention}(Q,K,V)=\text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}+M\right)V.$$

The mask $M$ adds 0 at allowed positions and $-\infty$ at forbidden positions.

Padding and a padding mask are different operations. For input lengths 3 and 5, a collator can pad both to 5; the mask then excludes the first input's two placeholder keys. The mask does not add tokens, and the batch need not use the model's maximum length.

For valid decoder self-attention queries, a key must be both non-padding and not in the future. With query rows and key columns, the strictly upper triangle is blocked; the diagonal stays visible because the current input predicts the next token. Cross-attention can read the full source sentence, not just a source prefix matching the translation position. These are the original architecture's rules; packing and local attention can impose further restrictions. Transformer §3.2.3

这个 query 到底能读哪些位置?

把 I like tea 翻译成 ich mag Tee。Decoder 的输入是 [BOS]、ich、mag,对应的目标是 ich、mag、Tee。

Attention 位置与 query 可以读取的 key
Encoder 的 like I、like、tea
Decoder 自注意力(self-attention)的 ich [BOS]、ich
Cross-attention 的 ich source 中的 I、like、tea

输入为 ich 时,下一个目标是 mag:看自己没问题,偷看右边的 mag 才会泄漏答案。Cross-attention 读的是已经给出的原文。三种模式都不读 padding key。开启 JavaScript 可以切换矩阵、选择 query 行;格子表示能不能读,不是模型学到的权重。

为什么这套做法突然可以做大

  • 训练并行:所有位置的 $Q/K/V$ 可以一次算出;
  • 路径更短:未被 mask 隔开的两个位置,可以在一层 attention 中直接传递信息;
  • 结构统一:self-attention 与 cross-attention 只是张量来源不同。

代价是 self-attention 的分数矩阵大小为 $T\times T$,标准实现的时间和显存随序列长度近似二次增长。

Why the architecture scales
  • Parallel training: Q, K, and V for every position are computed at once.
  • Short paths: positions allowed by the mask can communicate through one attention layer.
  • One reusable structure: self-attention and cross-attention differ mainly in where Q, K, and V come from.

The cost is a $T\times T$ self-attention score matrix, so standard attention grows approximately quadratically in time and memory with sequence length.

缺失的信息:Attention 本身不知道顺序

不加位置编码(positional encoding)、也不加顺序相关 mask 的 self-attention 是置换等变的:输入换序,输出跟着换序。原版把固定 sinusoidal position encoding 加到缩放后的 token embedding;这里把缩放吸收进 E:

$$z_t = E[x_t] + PE_t$$

这个结论适用于上述无顺序约束的 attention,不是说 causal decoder 也完全不知道前后。Causal mask 已经限制了可见方向,位置编码再提供更明确的位置信号。

The missing information: attention does not know order

Without positional information or an order-dependent mask, self-attention is permutation-equivariant: reordering inputs reorders outputs. The original Transformer adds fixed sinusoidal positions to scaled token embeddings, with the scale absorbed into E here:

$$z_t=E[x_t]+PE_t.$$

This describes attention without order constraints, not a causal decoder with no sense of earlier and later. The causal mask already restricts visibility; positional encoding supplies more explicit position information.

从 token ID 到下一个 token:完整走一遍

用英译中的小例子,把 2017 原版 Transformer 的整条前向路径串起来。下文的 512 维、8 个头、2048 维 FFN 指论文的 base 配置,不是所有原版配置。先只看 shape,再看每个模块的职责。

1. Source 怎样进入 encoder

英文句子先经过 tokenizer:

[I, love, you] -> [21, 135, 48]

token ID 只是词表(vocabulary)里的整数索引,本身没有距离或大小意义。embedding 层用这些 ID 从矩阵 $E$ 中查出向量。若 source 长度为 $S=3$,原版 $d_{\text{model}}=512$:

$$X_{\text{emb}}\in\mathbb{R}^{S\times d_{\text{model}}} =\mathbb{R}^{3\times512}.$$

原论文实际把 embedding 乘以 $\sqrt{d_{\text{model}}}$,再加固定的正弦位置编码:

$$X=\sqrt{d_{\text{model}}}\,X_{\text{emb}}+PE,$$

$$PE(pos,2i)=\sin\!\left(\frac{pos}{10000^{2i/d_{\text{model}}}}\right),\qquad PE(pos,2i+1)=\cos\!\left(\frac{pos}{10000^{2i/d_{\text{model}}}}\right).$$

不必死记常数;要记住 $PE$ 与 embedding 相加而不是拼接,所以 shape 仍是 $(S,512)$。每个位置得到一组独特但有规律的相位,模型才能区分 I love you 和 token 顺序被调换的句子。相加后还会应用 dropout。

1. How the source enters the encoder

Tokenization first maps text to vocabulary indices:

[I, love, you] -> [21, 135, 48]

An ID is only an index. Looking it up in the embedding matrix gives

$$X_{\text{emb}}\in\mathbb{R}^{S\times d_{\text{model}}}.$$

For $S=3$ and the original $d_{\text{model}}=512$, its shape is $(3,512)$. The paper scales embeddings and adds fixed sinusoidal positions:

$$X=\sqrt{d_{\text{model}}}\,X_{\text{emb}}+PE,$$

$$PE(pos,2i)=\sin\!\left(\frac{pos}{10000^{2i/d_{\text{model}}}}\right),\qquad PE(pos,2i+1)=\cos\!\left(\frac{pos}{10000^{2i/d_{\text{model}}}}\right).$$

$PE$ is added, not concatenated, so the shape remains $(S,512)$. It gives attention the order signal needed to distinguish a sequence from a permutation of the same tokens. Dropout follows the embedding-plus-position sum.

Attention 的维度与边界条件

对单个 attention head,更一般的 shape 是:

$$Q\in\mathbb R^{L_q\times d_k},\qquad K\in\mathbb R^{L_{kv}\times d_k},\qquad V\in\mathbb R^{L_{kv}\times d_v}.$$

于是

$$QK^\top\in\mathbb R^{L_q\times L_{kv}},\qquad \operatorname{softmax}(QK^\top)V\in\mathbb R^{L_q\times d_v}.$$

这里有两个真正的 shape 约束:Q 与 K 的最后一维都必须是 $d_k$,才能计算点积(inner product); K 与 V 的序列长度都必须是 $L_{kv}$,因为每个 key 都要对应一份被读取的 value。 $d_v$ 不必等于 $d_k$,输出通道数由 $d_v$ 决定。原版每个头取 $d_k=d_v=64$ 是设计选择,不是 attention 的数学要求。

score 除以 $\sqrt{d_k}$,用的是 Q/K 的匹配维度,与 $d_v$ 无关;方差(variance)推导和“饱和取决于分数差”的例子见多头注意力。

$W_Q,W_K,W_V$ 的单个坐标没有固定的人类语义,但三套投影承担不同角色:Q 表达“我要找什么”,K 表达“我怎样被匹配”,V 表达“匹配后传递什么内容”。因此

$$QK^\top=\text{addressing / routing},\qquad V=\text{retrieved content}.$$

分开的 $W_Q,W_K$ 让“$i$ 查询 $j$”和“$j$ 查询 $i$”可以有不同分数,分开的 $W_V$ 把“怎样找到信息”和“找到后读取什么”解耦;强制 $Q=K$ 会怎样,见多头注意力的面试常见问题。

Attention dimensions and edge cases

For one attention head, the general shapes are

$$Q\in\mathbb R^{L_q\times d_k},\qquad K\in\mathbb R^{L_{kv}\times d_k},\qquad V\in\mathbb R^{L_{kv}\times d_v}.$$

Therefore

$$QK^\top\in\mathbb R^{L_q\times L_{kv}},\qquad \operatorname{softmax}(QK^\top)V\in\mathbb R^{L_q\times d_v}.$$

There are two actual shape constraints. Q and K need the same final dimension $d_k$ for their dot product. K and V need the same sequence length $L_{kv}$ because every key indexes one value. The value width $d_v$ need not equal $d_k$; it determines the output width. Setting both to 64 in the original model was a design choice, not a mathematical requirement of attention.

The score is divided by $\sqrt{d_k}$, the Q/K matching width, not $d_v$; the variance derivation and the example showing that saturation depends on score differences are in multi-head attention.

The individual coordinates of $W_Q,W_K,W_V$ have no fixed human meaning, but their computational roles differ: Q represents what to look for, K how an item can be matched, and V what content should be transmitted after a match. In short,

$$QK^\top=\text{addressing / routing},\qquad V=\text{retrieved content}.$$

Separate $W_Q,W_K$ let “i queries j” and “j queries i” score differently, and a separate $W_V$ decouples how information is located from what is read; what forcing $Q=K$ does is covered in the multi-head attention interview questions.

2. 一个 encoder layer 算什么

原版堆叠 6 个相同结构的 encoder layer。每层都是:

X -> multi-head self-attention -> Add & Norm -> FFN -> Add & Norm

Self-attention 的 $Q/K/V$ 都来自当前 source states,因此称为 self-attention:

$$Q=XW_Q,\qquad K=XW_K,\qquad V=XW_V.$$

原版有 $h=8$ 个头,所以每个头

$$d_k=d_v=\frac{512}{8}=64.$$

对一个头,上一节的注意力公式依次完成四件事:

$$S=QK^\top,\qquad \widetilde S=\frac{S}{\sqrt{d_k}},\qquad A=\operatorname{softmax}_{\text{key}}(\widetilde S),\qquad O=AV.$$

$S_{ij}$ 是 source 位置 $i$ 的 query 与位置 $j$ 的 key 的匹配分数;softmax 沿每一行的 key 维计算。比如某层某个头在更新 love 时,可能得到

$$A_{\text{love}}=[0.4,\ 0.1,\ 0.5],$$

于是

$$o_{\text{love}}=0.4v_I+0.1v_{\text{love}}+0.5v_{\text{you}}.$$

这是这一层、这一个头里的读取权重,不要把它直接解释成模型总体上有 40% 的“语义关注”。8 个头各有自己的投影,最后拼接并经过输出投影:

$$\operatorname{MHA}(X)= \operatorname{Concat}(\operatorname{head}_1,\ldots,\operatorname{head}_8)W^O.$$

原版是 post-norm。每个 sublayer 的输出先做 dropout,再和输入走残差相加,最后 LayerNorm:

$$H=\operatorname{LN}\big(X+\operatorname{Dropout}(\operatorname{MHA}(X))\big).$$

随后每个 token 独立通过同一组 FFN 参数:

$$\operatorname{FFN}(h)=\operatorname{ReLU}(hW_1+b_1)W_2+b_2,$$

$$512\rightarrow2048\rightarrow512.$$

Attention 负责 token 之间交换信息;FFN 不跨 token,只加工每个位置已经收集到的通道信息。第二个 Add & Norm 是

$$Y=\operatorname{LN}\big(H+\operatorname{Dropout}(\operatorname{FFN}(H))\big).$$

重复 6 层后得到 encoder memory:

$$C=\operatorname{Encoder}(X)\in\mathbb{R}^{S\times512}.$$

2. What one encoder layer computes

The original model stacks six identical encoder layers:

X -> multi-head self-attention -> Add & Norm -> FFN -> Add & Norm

In self-attention, Q, K, and V are all computed from the current source states:

$$Q=XW_Q,\qquad K=XW_K,\qquad V=XW_V.$$

With $h=8$ heads and $d_{\text{model}}=512$, each head has

$$d_k=d_v=512/8=64.$$

For one head, attention performs

$$S=QK^\top,\qquad \widetilde S=\frac{S}{\sqrt{d_k}},\qquad A=\operatorname{softmax}_{\text{key}}(\widetilde S),\qquad O=AV.$$

$S_{ij}$ scores the query at source position $i$ against the key at position $j$; softmax runs along each row's key dimension. For example, one head at one layer might give the love query $A_{\text{love}}=[0.4,0.1,0.5]$, producing

$$o_{\text{love}}=0.4v_I+0.1v_{\text{love}}+0.5v_{\text{you}}.$$

These are local read weights for one head, not a literal statement that the whole model semantically pays “40% attention.” The eight heads are concatenated and projected:

$$\operatorname{MHA}(X)= \operatorname{Concat}(\operatorname{head}_1,\ldots,\operatorname{head}_8)W^O.$$

The original is post-norm. Each sublayer output is dropped out, added to the residual stream, and then normalized:

$$H=\operatorname{LN}\big(X+ \operatorname{Dropout}(\operatorname{MHA}(X))\big).$$

The same FFN is then applied independently at every position:

$$\operatorname{FFN}(h)=\operatorname{ReLU}(hW_1+b_1)W_2+b_2,$$

$$512\rightarrow2048\rightarrow512.$$

Attention exchanges information across tokens; the FFN transforms the channels of each token without exchanging information across positions. The second residual is

$$Y=\operatorname{LN}\big(H+ \operatorname{Dropout}(\operatorname{FFN}(H))\big).$$

After six layers, the encoder produces memory

$$C=\operatorname{Encoder}(X)\in\mathbb{R}^{S\times512}.$$

3. Target 为什么要右移

若正确译文是

target labels: [我, 爱, 你, <EOS>]
decoder input: [<BOS>, 我, 爱, 你]

二者错开一位,位置 $t$ 才能学习“根据此前 token 预测第 $t$ 个 token”。训练时整条正确 target 已知,可以一次并行输入;causal mask 负责阻止偷看未来。

Decoder 输入同样经过 embedding、位置编码和 dropout。source embedding、target embedding 和输出投影在结构上可以分开;不过原论文使用联合词表,并共享两套 embedding 与 pre-softmax 投影的权重,同时对 embedding 乘 $\sqrt{d_{\text{model}}}$。所以“翻译任务必然使用三套不同权重”不是原版 Transformer 的事实。

3. Why the target is shifted

For the target sequence

labels:        [我, 爱, 你, <EOS>]
decoder input: [<BOS>, 我, 爱, 你]

the one-position shift teaches each position to predict its next token from the prefix. During training, the full target is available in parallel; the causal mask prevents future leakage.

Decoder inputs also receive embeddings, positions, and dropout. Source embedding, target embedding, and output projection can be separate. The original paper, however, used a shared vocabulary and tied both embedding matrices to the pre-softmax projection, while multiplying embedding values by $\sqrt{d_{\text{model}}}$. Separate weights are therefore not an invariant of the original Transformer.

4. 一个 decoder layer 为什么有三段

原版也堆 6 个 decoder layer;每层比 encoder 多一个 cross-attention:

target states
  -> masked self-attention -> Add & Norm
  -> cross-attention       -> Add & Norm
  -> FFN                   -> Add & Norm

第一段是 target 上的 self-attention,但 score 会加 causal mask。4 个位置的允许区域是下三角:

$$ \begin{bmatrix} s_{11}&-\infty&-\infty&-\infty\\ s_{21}&s_{22}&-\infty&-\infty\\ s_{31}&s_{32}&s_{33}&-\infty\\ s_{41}&s_{42}&s_{43}&s_{44} \end{bmatrix}. $$

因为 $e^{-\infty}=0$,softmax 后被遮住的位置权重严格为 0;第 $i$ 个位置只能读取第 1 到 $i$ 个 target position。把 target 一侧的输入(embedding、位置编码和 dropout 之后)记为 $Y\in\mathbb{R}^{T\times512}$,它不是第 2 步里 encoder 层输出的 $Y$。第一个子层得到

$$H_1=\operatorname{LN}\big(Y+ \operatorname{Dropout}(\operatorname{MaskedMHA}(Y))\big).$$

第二段 cross-attention 才让 decoder 接触英文 source:

$$Q=H_1W_Q,\qquad K=CW_K,\qquad V=CW_V.$$

也就是 Q 来自 decoder,K/V 来自 encoder memory。若 target 长度是 $T$、 source 长度是 $S$,attention weight 的 shape 是 $(T,S)$,不必是方阵。比如准备生成“爱”时,decoder state 可以用 query 去读取 encoder 中与 love 相关的 value:

$$H_2=\operatorname{LN}\big(H_1+ \operatorname{Dropout}(\operatorname{CrossAttention}(H_1,C))\big).$$

第三段是和 encoder 相同的逐位置 FFN:

$$H_3=\operatorname{LN}\big(H_2+ \operatorname{Dropout}(\operatorname{FFN}(H_2))\big).$$

6 层之后得到

$$D\in\mathbb{R}^{T\times512}.$$

4. Why one decoder layer has three sublayers

The decoder also has six layers, each with three sublayers:

target states
  -> masked self-attention -> Add & Norm
  -> cross-attention       -> Add & Norm
  -> FFN                   -> Add & Norm

The first sublayer is target self-attention with a causal mask. For four positions, the allowed score region is lower triangular:

$$ \begin{bmatrix} s_{11}&-\infty&-\infty&-\infty\\ s_{21}&s_{22}&-\infty&-\infty\\ s_{31}&s_{32}&s_{33}&-\infty\\ s_{41}&s_{42}&s_{43}&s_{44} \end{bmatrix}. $$

Since $e^{-\infty}=0$, masked positions receive zero probability after softmax. Position $i$ can read only positions $1$ through $i$. Writing $Y\in\mathbb{R}^{T\times512}$ for the target-side input after embedding, positions, and dropout (not the encoder-layer $Y$ from step 2), the first sublayer is

$$H_1=\operatorname{LN}\big(Y+ \operatorname{Dropout}(\operatorname{MaskedMHA}(Y))\big).$$

Cross-attention is where target states first read the source:

$$Q=H_1W_Q,\qquad K=CW_K,\qquad V=CW_V.$$

Thus Q comes from the decoder, while K and V come from encoder memory. With target length $T$ and source length $S$, its attention matrix is $(T,S)$ and need not be square. A decoder state preparing to generate 爱 can retrieve the source value aligned with love:

$$H_2=\operatorname{LN}\big(H_1+ \operatorname{Dropout}(\operatorname{CrossAttention}(H_1,C))\big).$$

The position-wise FFN completes the layer:

$$H_3=\operatorname{LN}\big(H_2+ \operatorname{Dropout}(\operatorname{FFN}(H_2))\big).$$

After six decoder layers,

$$D\in\mathbb{R}^{T\times512}.$$

5. 从 decoder state 变成词表概率

每个位置的 512 维向量投影到目标词表。若词表大小 $V=30{,}000$:

$$Z=DW_{\text{vocab}}+b,\qquad W_{\text{vocab}}\in\mathbb{R}^{512\times30{,}000},$$

所以 $Z\in\mathbb{R}^{T\times30{,}000}$。每行是该位置对所有 token 的 logits, softmax 才把它变成条件概率:

$$p(y_t\mid y_{<t},x)=\operatorname{softmax}(Z_t).$$

训练时用 cross-entropy,原论文还采用了 $\epsilon_{ls}=0.1$ 的 label smoothing,而不是纯 one-hot 目标;推理时则用 greedy、beam search 或 sampling 选出一个 token,再把它接回 decoder 继续生成。Softmax 本身只给概率,并不规定必须选 argmax。

整条路径可以压成一行:

$$ \text{source IDs}\rightarrow C\rightarrow \underbrace{p(y_1\mid x),\ p(y_2\mid y_1,x),\ldots}_{ \text{masked self-attention 读前缀,cross-attention 读 source}} $$

5. From decoder states to vocabulary probabilities

Each 512-dimensional decoder state is projected to the target vocabulary. For $V=30{,}000$:

$$Z=DW_{\text{vocab}}+b,\qquad W_{\text{vocab}}\in\mathbb{R}^{512\times30{,}000},$$

so $Z\in\mathbb{R}^{T\times30{,}000}$. Each row contains logits; softmax turns them into a conditional distribution:

$$p(y_t\mid y_{<t},x)=\operatorname{softmax}(Z_t).$$

Training uses cross-entropy; the original paper also applies label smoothing with $\epsilon_{ls}=0.1$ rather than a purely one-hot target. Inference uses greedy decoding, beam search, or sampling to select a token, feeds it back into the decoder, and continues. Softmax provides probabilities; it does not itself require argmax.

The whole path is

$$ \text{source IDs}\rightarrow C\rightarrow \underbrace{p(y_1\mid x),\ p(y_2\mid y_1,x),\ldots}_{ \text{masked self-attention reads the prefix; cross-attention reads the source}}. $$

不要混淆:2017 原版不是现代 Decoder-only

2017 vanilla 现代 decoder-only
主体 encoder + decoder decoder stack only
norm post-norm LayerNorm 多为 pre-norm RMSNorm
position sinusoidal 多为 RoPE
attention MHA 常见 GQA / MQA;也有 MLA,或部分层换成线性注意力 / 循环状态
FFN ReLU 常见 SwiGLU
预测条件 source + target prefix → 下一个 target token 同一 token stream 的 prefix → 下一个 token

原版最适合学习三处 attention 的职责;现代版本最适合理解今天语言模型(language model, LM)的训练与推理。

进阶:为什么训练能并行,生成仍不能并行

训练时真实目标序列已知,可以把它整体右移后一次喂给 decoder,causal mask 保证位置 $t$ 看不到未来。生成时第 $t+1$ 个输入正是第 $t$ 个预测,尚未产生,因此只能逐步解码。

Do not conflate the 2017 architecture with a modern decoder-only LLM
2017 vanilla Modern decoder-only
Body encoder + decoder decoder stack only
Normalization post-norm LayerNorm usually pre-norm RMSNorm
Position sinusoidal encoding usually RoPE
Attention MHA often GQA / MQA; also MLA, or linear attention / recurrent state in some layers
FFN ReLU often SwiGLU
Prediction context source + target prefix → next target token prefix of one token stream → next token

The original architecture is the cleanest place to learn the roles of its three attention sites. Modern decoder-only models are the right reference for today's LLM training and inference.

Training remains parallel because the complete target sequence is known and shifted into the decoder at once; the causal mask blocks future information. Generation is still sequential because token $t+1$ cannot be used before token $t$ has been predicted.

动手验证:运行完整示例

自检

画完结构图后,再问自己:
  1. encoder self-attention、decoder self-attention 和 cross-attention 的 Q/K/V 分别来自哪里?
  2. 为什么 Q/K 的最后一维必须相同,而 $d_v$ 可以不同?
  3. 为什么除以 $\sqrt{d_k}$?不缩放时 softmax 和梯度会怎样?
  4. 若强制 $Q=K$,原始 score 矩阵有什么性质,表达能力受到什么限制?
  5. 为什么 Transformer 训练可以并行,生成却仍然逐 token?
  6. 如果拿掉位置编码,模型具体失去了什么信息?

继续阅读

接下来可以分两条走:BERT 把 encoder 用于双向预训练(pre-training)和文本理解;Decoder-only 则将条件生成、对话与代码写成 token stream 上的自回归预测。不必按模型年代全部读完,先选你关心的任务。本文的原版配置与权重共享约定依据 Attention Is All You Need。

快速学习:2017 Transformer 从输入到下一个 token

Encoder、Decoder 与现代 Decoder-only 的分界

快速记忆:Encoder 是 self-attention + FFN;Decoder 把 self-attention 换成 masked self-attention,再多一段 cross-attention;每段外面都有 residual 与 norm。

面试回答

Source tokens 经 embedding 与 position encoding 后进入 encoder;decoder 用右移后的 target 做 masked self-attention,再通过 cross-attention 读取 encoder states,最后由 linear vocabulary head 与 softmax 预测下一个 token。训练能并行所有 target positions,生成仍需自回归。

深挖:为什么 target 右移和 causal mask 两个都需要?

右移决定每个位置的输入是前一个真实 token;causal mask 决定该位置不能在 self-attention 中读取更右侧标签。只右移不 mask,从第一层 self-attention 起,位置 $t$ 就能读到右边一格的输入,而那正是它要预测的 token;只 mask 不右移,则当前位置直接拿到它要预测的 token embedding。

本页术语 7
自注意力 self-attention
序列自己查询自己,让每个位置看见其他位置
位置编码 positional encoding
把「第几个 token」的信息注入表示
词表 vocabulary
模型能输出的所有 token 的集合
点积 inner product
两个向量对应分量相乘再求和,双塔的打分方式
方差 variance
估计量的波动幅度;重要性加权最容易在这里爆炸
语言模型 language model, LM
对文本序列建模,用上下文预测或生成后续内容
预训练 pre-training
先用大量数据学习通用表示和能力,再适配具体任务