下列文本提取自本地原版 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 查看记录 ↗