CS336.wiki
CS336 中文实验手册/训练与优化
反馈与讨论
ASSIGNMENT 01 / 4.1–4.2

交叉熵与 SGD

2026 春季 · v26.0.3原文 p. 28–31对照 PDF ↗

4 训练 Transformer 语言模型#

现在已经有数据预处理所需的分词器,以及 Transformer 模型。还需要构建训练支持:

  • 损失: 交叉熵。
  • 优化器: 用 AdamW 最小化损失。
  • 训练循环: 数据加载、检查点保存与训练管理。

4.1 交叉熵损失#

对长度为 m+1m+1 的序列,模型为各位置 i=1,…,mi=1,\ldots,m 定义分布 pθ(xi+1∣x1:i)p_\theta(x_{i+1}\mid x_{1:i})。训练集 DD 由这类序列组成,标准交叉熵,也就是负对数似然损失,为:

ℓ(θ;D)=1∣D∣m∑x∈D∑i=1m−log⁡pθ(xi+1∣x1:i)(16) \ell(\theta;D)=\frac{1}{|D|m} \sum_{x\in D}\sum_{i=1}^{m}-\log p_\theta(x_{i+1}\mid x_{1:i}) \tag{16}

一次 Transformer 前向传播可以同时计算所有位置的预测。对每个位置,模型产生 oi∈Rvocab_sizeo_i\in\mathbb{R}^{\mathrm{vocab\_size}} 的 logits:

p(xi+1∣x1:i)=softmax⁡(oi)[xi+1]=exp⁡(oi[xi+1])∑a=1vocab_sizeexp⁡(oi[a])(17) p(x_{i+1}\mid x_{1:i})= \operatorname{softmax}(o_i)[x_{i+1}] =\frac{\exp(o_i[x_{i+1}])} {\sum_{a=1}^{\mathrm{vocab\_size}}\exp(o_i[a])} \tag{17}

这里 oi[k]o_i[k] 表示向量的第 kk 项。交叉熵通常直接以 logits 向量与目标 token 定义;这对应真实 token 上的 Dirac delta 分布与预测 softmax 分布之间的交叉熵。

和 softmax 一样,实现交叉熵时需要谨慎处理数值问题。

练习 cross_entropy1 分

实现交叉熵

交付物: 编写函数,接收预测 logits oio_i 与目标 xi+1x_{i+1},计算:

ℓi=−log⁡softmax⁡(oi)[xi+1] \ell_i=-\log\operatorname{softmax}(o_i)[x_{i+1}]

要求:

  • 减去最大元素,确保数值稳定。
  • 尽可能消去 log 与 exp。
  • 支持额外的批次维,返回批次平均损失。和第 3.2 节一样,批次维始终位于词表维之前。

实现 adapters.run_cross_entropy,运行 uv run pytest -k test_cross_entropy。

困惑度#

交叉熵足以训练模型,评估时还要报告困惑度。对于长度为 mm、各位置交叉熵为 ℓ1,…,ℓm\ell_1,\ldots,\ell_m 的序列:

perplexity⁡=exp⁡(1m∑i=1mℓi)(18) \operatorname{perplexity}= \exp\left(\frac{1}{m}\sum_{i=1}^{m}\ell_i\right) \tag{18}

4.2 SGD 优化器#

最简单的基于梯度的优化器是随机梯度下降(SGD)。从随机初始化的参数 θ0\theta_0 出发,在每一步 t=0,…,T−1t=0,\ldots,T-1:

θt+1←θt−αt∇L(θt;Bt)(19) \theta_{t+1}\leftarrow\theta_t-\alpha_t\nabla L(\theta_t;B_t) \tag{19}

BtB_t 是从数据集 DD 随机抽取的批次,学习率 αt\alpha_t 和批次大小 ∣Bt∣|B_t| 都是超参数。

4.2.1 在 PyTorch 中实现 SGD#

优化器通过继承 torch.optim.Optimizer 实现,需要两个方法:

方法 职责
init 接收要优化的参数或参数组,以及学习率等超参数;把参数和以字典表示的默认超参数传给父类构造函数,供后续更新使用。参数组可用于让模型不同部分采用不同超参数。
step 在反向传播后执行一次参数更新。遍历各参数张量,利用存在的 p.grad 原地修改参数对应的 p.data。

原文通过带学习率衰减的 SGD 演示 API 的细节:

θt+1=θt−αt+1∇L(θt;Bt)(20) \theta_{t+1}=\theta_t-\frac{\alpha}{\sqrt{t+1}}\nabla L(\theta_t;B_t) \tag{20}
查看指导书提供的 SGD 示例代码
指导书原文
from collections.abc import Callable, Iterable
from typing import Optional
import torch
import math

class SGD(torch.optim.Optimizer):
    def __init__(self, params, lr=1e-3):
        if lr < 0:
            raise ValueError(f"Invalid learning rate: {lr}")
        defaults = {"lr": lr}
        super().__init__(params, defaults)

    def step(self, closure: Optional[Callable] = None):
        loss = None if closure is None else closure()
        for group in self.param_groups:
            lr = group["lr"] # Get the learning rate.
            for p in group["params"]:
                if p.grad is None:
                    continue

                state = self.state[p] # Get state associated with p.
                t = state.get("t", 0) # Get iteration number from the state, or 0.
                grad = p.grad.data # Get the gradient of loss with respect to p.
                p.data -= lr / math.sqrt(t + 1) * grad # Update weight tensor in-place.
                state["t"] = t + 1 # Increment iteration number.

        return loss

在示例中,父类根据传入参数及默认超参数组织参数组;如果只有一个 nn.Parameter 集合,就创建一个使用默认值的组。step 逐组、逐参数执行公式 20。

每个参数关联的状态保存迭代次数:读取次数、完成更新、再递增。API 还允许传入可调用的 closure,在更新前重新计算损失。这里并不需要该功能,但示例保留它以符合接口。

原文还给出一个最小训练循环:创建参数与优化器,反复清空梯度、计算标量损失、执行反向传播,再调用优化器。这是典型训练结构;语言模型训练时,参数来自 model.parameters(),损失则在抽样数据批次上计算,基本流程相同。

查看指导书提供的最小训练循环
指导书原文
weights = torch.nn.Parameter(5 * torch.randn((10, 10)))
opt = SGD([weights], lr=1)

for t in range(100):
    opt.zero_grad() # Reset the gradients for all learnable parameters.
    loss = (weights**2).mean() # Compute a scalar loss value.
    print(loss.cpu().item())
    loss.backward() # Run backward pass, which computes gradients.
    opt.step() # Run optimizer step.
练习 learning_rate_tuning1 分

调整学习率

学习率是最影响训练的超参数之一。把上述 SGD 示例的学习率分别改为 1e1、1e2、1e3,每次只运行 10 次迭代。各学习率下损失如何变化?下降更快、更慢,还是发散,即训练中不断增加?

交付物: 用一至两句话描述观察到的现象。

一起把这一章读得更好

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

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

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

4 Training a Transformer LM
We now have the steps to preprocess the data (via tokenizer) and the model (Transformer). What
remains is to build all of the code to support training. This consists of the following:
• Loss: we need to define the loss function (cross-entropy).
• Optimizer: we need to define the optimizer to minimize this loss (AdamW).
• Training loop: we need all the supporting infrastructure that loads data, saves checkpoints, and
  manages training.

4.1 Cross-entropy loss
Recall that the Transformer language model defines a distribution 𝑝𝜃 (𝑥𝑖+1 | 𝑥1:𝑖 ) for each sequence 𝑥 of
length 𝑚 + 1 and 𝑖 = 1, …, 𝑚. Given a training set 𝐷 consisting of sequences of length 𝑚 + 1, we define
the standard cross-entropy (negative log-likelihood) loss function:
                                                           𝑚
                                                  1
                                    ℓ(𝜃; 𝐷) =         ∑ ∑ − log 𝑝𝜃 (𝑥𝑖+1 | 𝑥1:𝑖 ).                                       (16)
                                                |𝐷| 𝑚 𝑥∈𝐷 𝑖=1

(Note that a single forward pass in the Transformer yields 𝑝𝜃 (𝑥𝑖+1 | 𝑥1:𝑖 ) for all 𝑖 = 1, …, 𝑚.)
In particular, the Transformer computes logits 𝑜𝑖 ∈ ℝvocab_size for each position 𝑖, which results in:6

                                                                         exp(𝑜𝑖 [𝑥𝑖+1 ])
                            𝑝(𝑥𝑖+1 | 𝑥1:𝑖 ) = softmax(𝑜𝑖 )[𝑥𝑖+1 ] =     vocab_size
                                                                                               .                         (17)
                                                                       ∑𝑎=1        exp(𝑜𝑖 [𝑎])

The cross-entropy loss is generally defined with respect to the vector of logits 𝑜𝑖 ∈ ℝvocab_size and target
𝑥𝑖+1 .7

  6
   Note that 𝑜𝑖 [𝑘] refers to value at index 𝑘 of the vector 𝑜𝑖 .
  7
   This corresponds to the cross-entropy between the Dirac delta distribution over 𝑥𝑖+1 and the predicted softmax(𝑜𝑖 )
distribution.

Implementing the cross-entropy loss requires some care with numerical issues, just like in the case of
softmax.


 Problem (cross_entropy): Implement cross-entropy (1 point)


   Deliverable: Write a function to compute the cross-entropy loss, which takes in predicted logits
   (𝑜𝑖 ) and targets (𝑥𝑖+1 ) and computes the cross-entropy ℓ𝑖 = − log softmax(𝑜𝑖 )[𝑥𝑖+1 ]. Your function
   should handle the following:
   • Subtract the largest element for numerical stability.
   • Cancel out log and exp whenever possible.
   • Handle any additional batch dimensions and return the average across the batch. As with
     Section 3.2, we assume batch-like dimensions always come first, before the vocabulary size
     dimension.
   Implement [adapters.run_cross_entropy] , then run uv run pytest -k test_cross_entropy to
   test your implementation.


Perplexity
Cross-entropy suffices for training, but when we evaluate the model, we also want to report perplexity.
For a sequence of length 𝑚 where we suffer cross-entropy losses ℓ1 , …, ℓ𝑚 :

                                                           1 𝑚
                                       perplexity = exp(     ∑ ℓ ).                                         (18)
                                                           𝑚 𝑖=1 𝑖


4.2 The SGD Optimizer
Now that we have a loss function, we will begin our exploration of optimizers. The simplest gradient-
based optimizer is Stochastic Gradient Descent (SGD). We start with randomly initialized parameters 𝜃0 .
Then for each step 𝑡 = 0, …, 𝑇 − 1, we perform the following update:
                                        𝜃𝑡+1 ← 𝜃𝑡 − 𝛼𝑡 ∇𝐿(𝜃𝑡 ; 𝐵𝑡 ),                                        (19)

where 𝐵𝑡 is a random batch of data sampled from the dataset 𝐷, and the learning rate 𝛼𝑡 and batch size
|𝐵𝑡 | are hyperparameters.

4.2.1 Implementing SGD in PyTorch
To implement our optimizers, we will subclass the PyTorch torch.optim.Optimizer class. An Optimizer
subclass must implement two methods:
def __init__(self, params, ...) should initialize your optimizer. Here, params will be a collection of
   parameters to be optimized (or parameter groups, in case the user wants to use different
   hyperparameters, such as learning rates, for different parts of the model). Make sure to pass params to
   the __init__ method of the base class, which will store these parameters for use in step. You can take
   additional arguments depending on the optimizer (e.g., the learning rate is a common one), and pass
   them to the base class constructor as a dictionary, where keys are the names (strings) you choose for
   these parameters.
def step(self) should make one update of the parameters. During the training loop, this will be called
   after the backward pass, so you have access to the gradients on the last batch. This method should
   iterate through each parameter tensor p and modify them in place, i.e. setting p.data, which holds the

   tensor associated with that parameter based on the gradient p.grad (if it exists), the tensor
   representing the gradient of the loss with respect to that parameter.
The PyTorch optimizer API has a few subtleties, so it’s easier to explain it with an example. To make our
example richer, we’ll implement a slight variation of SGD where the learning rate decays over training,
starting with an initial learning rate 𝛼 and taking successively smaller steps over time:
                                                        𝛼
                                       𝜃𝑡+1 = 𝜃𝑡 − √       ∇𝐿(𝜃𝑡 ; 𝐵𝑡 )                                (20)
                                                       𝑡+1

Let’s see how this version of SGD would be implemented as a PyTorch Optimizer:
from collections.abc import Callable, Iterable
from typing import Optional
import torch
import math

class SGD(torch.optim.Optimizer):
    def __init__(self, params, lr=1e-3):
        if lr < 0:
            raise ValueError(f"Invalid learning rate: {lr}")
        defaults = {"lr": lr}
        super().__init__(params, defaults)

    def step(self, closure: Optional[Callable] = None):
        loss = None if closure is None else closure()
        for group in self.param_groups:
            lr = group["lr"] # Get the learning rate.
            for p in group["params"]:
                if p.grad is None:
                    continue

                 state = self.state[p] # Get state associated with p.
                 t = state.get("t", 0) # Get iteration number from the state, or 0.
                 grad = p.grad.data # Get the gradient of loss with respect to p.
                 p.data -= lr / math.sqrt(t + 1) * grad # Update weight tensor in-place.
                 state["t"] = t + 1 # Increment iteration number.

        return loss

In __init__, we pass the parameters, as well as default hyperparameters, to the base class constructor
(the parameters might come in groups, each with different hyperparameters). In case the parameters are
just a single collection of torch.nn.Parameter objects, the base constructor will create a single group and
assign it the default hyperparameters. Then, in step, we iterate over each parameter group, then over
each parameter in that group, and apply Equation 20. Here, we keep the iteration number as a state
associated with each parameter: we first read this value, use it in the gradient update, and then update it.
The API specifies that the user might pass in a callable closure to re-compute the loss before the
optimizer step. We won’t need this for the optimizers we’ll use, but we add it to comply with the API.
To see this working, we can use the following minimal example of a training loop:
weights = torch.nn.Parameter(5 * torch.randn((10, 10)))
opt = SGD([weights], lr=1)

for t in range(100):
    opt.zero_grad() # Reset the gradients for all learnable parameters.
    loss = (weights**2).mean() # Compute a scalar loss value.
    print(loss.cpu().item())

    loss.backward() # Run backward pass, which computes gradients.
    opt.step() # Run optimizer step.

This is the typical structure of a training loop: in each iteration, we will compute the loss and run a step
of the optimizer. When training language models, our learnable parameters will come from the model (in
PyTorch, m.parameters() gives us this collection). The loss will be computed over a sampled batch of
data, but the basic structure of the training loop will be the same.


 Problem (learning_rate_tuning): Tuning the learning rate (1 point)


   As we will see, one of the hyperparameters that affects training the most is the learning rate.
   Let’s see that in practice in our toy example. Run the SGD example above with three other values
   for the learning rate: 1e1, 1e2, and 1e3, for just 10 training iterations. What happens with the loss
   for each of these learning rates? Does it decay faster, slower, or does it diverge (i.e., increase over
   the course of training)?
   Deliverable: A one-to-two sentence response with the behaviors you observed.

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

正在加载本章讨论…

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

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