CS336.wiki
CS336 中文实验手册/Transformer 架构
反馈与讨论
ASSIGNMENT 01 / 3.1

模型架构概览

2026 春季 · v26.0.3原文 p. 13–14对照 PDF ↗

3 Transformer 语言模型架构#

语言模型接收一批整数 token ID 序列,输入张量形状为 (batch_size, sequence_length),并返回各位置覆盖整个词表的 logits,形状为 (batch_size, sequence_length, vocab_size)。训练或推理时再对最后一维应用 softmax,得到下一 token 的概率分布。每个位置预测的是该 token 之后的下一个 token。

训练时,利用 logits 计算真实下一 token 与预测分布之间的交叉熵。推理生成时,先取最后一个时间步的 logits 并应用 softmax,再选出下一个 token,例如取最大概率项或从分布采样,然后把生成的 token 接到输入序列后面,重复此过程。

这一部分将从零构建 Transformer 语言模型。先介绍整体结构,再逐步说明各组件。

3.1 Transformer 语言模型#

给定 token ID 序列,先通过输入嵌入把 ID 变成稠密向量,经过 num_layers 个 Transformer 块,再用一个可学习线性投影,即“输出嵌入”或“LM head”,得到下一 token 的预测 logits。

指导书图 1 与图 2:完整 Transformer 语言模型,以及预归一化 Transformer 块

图 1、图 2:保留原指导书的模型结构图。左图从下向上依次为输入、token 嵌入、多个 Transformer 块、归一化、输出线性层与 softmax;右图展示预归一化块的两个子层及残差连接。

Token 嵌入#

第一步把一批 token ID 转换成包含 token 身份信息的向量序列,对应图 1 的红色模块。嵌入层将 (batch_size, sequence_length) 的整数张量,变为 (batch_size, sequence_length, d_model) 的向量张量。

预归一化 Transformer 块#

嵌入之后,激活值依次经过多个结构相同的神经网络层。标准的仅解码器 Transformer 包含 num_layers 个这样的层,通常称为 Transformer “块”。

每个块的输入和输出都是 (batch_size, sequence_length, d_model)。它通过自注意力聚合序列信息,再通过前馈层进行非线性变换。

经过全部块后,把最终激活转成词表上的分布。本作业采用第 3.4 节详述的 pre-norm(预归一化) 结构;最后一个 Transformer 块之后还需要额外的层归一化,保证输出具有适当尺度。随后用标准的可学习线性变换得到下一 token 的预测 logits,参见 Radford 等人 [7] 的公式 2。

一起把这一章读得更好

发现翻译、公式或排版错误?欢迎反馈。概念疑问和学习心得,也可以在本章讨论中交流。

直接选中正文,点击旁边的「反馈这处错误」,即可在页内填写并提交,无需登录。
English original 展开本章英文原文 PDF 文本提取

下列文本提取自本地原版 PDF。图表和公式的准确布局请对照 PDF。

3 Transformer Language Model Architecture
A language model takes as input a batched sequence of integer token IDs (i.e., torch.Tensor of shape
(batch_size, sequence_length)), and returns a (batched) normalized probability distribution over the
vocabulary (i.e., a PyTorch Tensor of shape (batch_size, sequence_length, vocab_size)), where the
predicted distribution is over the next word for each input token. When training the language model, we
use these next-word predictions to calculate the cross-entropy loss between the actual next word and the
predicted next word. When generating text from the language model during inference, we take the
predicted next-word distribution from the final time step (i.e., the last item in the sequence) to generate
the next token in the sequence (e.g., by taking the token with the highest probability, sampling from the
distribution, etc.), add the generated token to the input sequence, and repeat.
In this part of the assignment, you will build this Transformer language model from scratch. We will
begin with a high-level description of the model before progressively detailing the individual components.

3.1 Transformer LM
Given a sequence of token IDs, the Transformer language model uses an input embedding to convert
token IDs to dense vectors, passes the embedded tokens through num_layers Transformer blocks, and then
applies a learned linear projection (the “output embedding” or “LM head”) to produce the predicted
next-token logits. See Figure 1 for a schematic representation.

                  Output                                             Output tensor with shape
               Probabilities                                   (batch_size, seq_len, d_model)


                 Softmax
                                                                            Add

                  Linear
             (Output Embedding)
                                                                                        Position-Wise
                                                                                        Feed-Forward
                   Norm

                                                                                           Norm
             Transformer Block
                                        num_layers
                    ...                 Transformer                         Add
                                        Blocks

             Transformer Block                                                        Causal Multi-Head
                                                                                        Self-Attention
                                                                                          w/ RoPE


                  Token                                                                    Norm
                Embedding



                                                                      Input tensor with shape
                  Inputs                                       (batch_size, seq_len, d_model)

Figure 1: An overview of our Transformer language            Figure 2: A pre-norm Transformer block.
                      model.

Token Embeddings
In the very first step, the Transformer embeds the (batched) sequence of token IDs into a sequence of
vectors containing information on the token identity (red blocks in Figure 1).
More specifically, given a sequence of token IDs, the Transformer language model uses a token embedding
layer to produce a sequence of vectors. Each embedding layer takes in a tensor of integers of shape
(batch_size, sequence_length) and produces a sequence of vectors of shape (batch_size,
sequence_length, d_model).

Pre-norm Transformer Block
After embedding, the activations are processed by several identically structured neural net layers. A
standard decoder-only Transformer language model consists of num_layers identical layers (commonly
called Transformer “blocks”). Each Transformer block takes in an input of shape (batch_size,
sequence_length, d_model) and returns an output of shape (batch_size, sequence_length, d_model).
Each block aggregates information across the sequence (via self-attention) and non-linearly transforms it
(via the feed-forward layers).
After num_layers Transformer blocks, we will take the final activations and turn them into a distribution
over the vocabulary.
We will implement the “pre-norm” Transformer block (detailed in Section 3.4), which additionally
requires the use of layer normalization (detailed below) after the final Transformer block to ensure its
outputs are properly scaled.
After this normalization, we will use a standard learned linear transformation to convert the output of
the Transformer blocks into predicted next-token logits (see, e.g., A. Radford et al. [7] equation 2).

关于这一章的疑问、理解与心得,都可以在这里交流。阅读无需登录;发表评论或回复时使用 GitHub 账号。

正在加载本章讨论…

欢迎交流概念与阅读疑问,请勿发布作业完整实现或题目答案。

输入中文、英文术语或题号,例如 RoPE、检查点、train_bpe。