大模型原理与训练 / 系统课时
训练模型并观察损失曲线
训练模型并观察损失曲线
本节把一个微型 GPT 真正跑进训练循环:准备批次、计算下一词元交叉熵、反向传播并更新参数,同时定期评估训练集与验证集。最终你会得到损失曲线和一个可被生成脚本加载的 tiny_gpt.pt 权重文件。
学习目标
- 写出包含批次采样、前向、反向、优化和评估的完整训练循环。
- 根据训练损失与验证损失的相对走势判断欠拟合、收敛和过拟合。
- 保存模型参数、结构配置与字符表,使权重能够独立恢复并用于生成。
把训练目标固定下来
微型 GPT 的训练目标仍然是根据当前位置之前的词元预测下一个词元。输入序列 x 与目标序列 y 只相差一个位置,模型在每个位置输出整个词表的 logits,再用交叉熵衡量正确下一个词元的概率是否足够高。
训练损失用于驱动梯度更新,验证损失只用于观察泛化,因此验证阶段必须关闭梯度并切换到评估模式。小语料很容易被模型记住,所以只看训练损失下降并不能证明模型真的学到了可迁移的模式。
训练循环如何工作
一次更新会依次经历批次采样、前向计算、交叉熵、反向传播、梯度裁剪和 AdamW 更新;每隔若干步再走一条不更新参数的评估分支。把训练与评估分开,才能知道损失下降究竟来自真正的模式学习,还是单纯记忆训练语料。

运行最小训练脚本
下面使用字符级词表和 nn.TransformerEncoder 搭一个极小因果语言模型。语料故意很小,目的是看清训练机制而不是追求文本质量。环境需已安装 PyTorch 与 Matplotlib。
from pathlib import Path
import matplotlib.pyplot as plt
import torch
import torch.nn.functional as F
from torch import nn
torch.manual_seed(7)
text = (
"to be or not to be that is the question "
"whether tis nobler in the mind to suffer "
"the slings and arrows of outrageous fortune "
) * 80
chars = sorted(set(text))
stoi = {ch: i for i, ch in enumerate(chars)}
itos = {i: ch for ch, i in stoi.items()}
data = torch.tensor([stoi[ch] for ch in text], dtype=torch.long)
split = int(len(data) * 0.9)
train_data = data[:split]
val_data = data[split:]
config = {
"vocab_size": len(chars),
"block_size": 32,
"d_model": 64,
"n_head": 4,
"n_layer": 2,
"dropout": 0.1,
}
batch_size = 32
device = "cuda" if torch.cuda.is_available() else "cpu"
def get_batch(source):
max_start = len(source) - config["block_size"] - 1
starts = torch.randint(0, max_start, (batch_size,))
x = torch.stack([source[i:i + config["block_size"]] for i in starts])
y = torch.stack([source[i + 1:i + config["block_size"] + 1] for i in starts])
return x.to(device), y.to(device)
class TinyGPT(nn.Module):
def __init__(self, cfg):
super().__init__()
self.token_embedding = nn.Embedding(cfg["vocab_size"], cfg["d_model"])
self.position_embedding = nn.Embedding(cfg["block_size"], cfg["d_model"])
layer = nn.TransformerEncoderLayer(
d_model=cfg["d_model"],
nhead=cfg["n_head"],
dim_feedforward=4 * cfg["d_model"],
dropout=cfg["dropout"],
batch_first=True,
norm_first=True,
activation="gelu",
)
self.blocks = nn.TransformerEncoder(layer, num_layers=cfg["n_layer"])
self.norm = nn.LayerNorm(cfg["d_model"])
self.lm_head = nn.Linear(cfg["d_model"], cfg["vocab_size"])
def forward(self, idx, targets=None):
_, t = idx.shape
pos = torch.arange(t, device=idx.device)
x = self.token_embedding(idx) + self.position_embedding(pos)
# 上三角 -inf 掩码阻止当前位置读取未来词元。
mask = torch.triu(
torch.full((t, t), float("-inf"), device=idx.device),
diagonal=1,
)
x = self.blocks(x, mask=mask)
logits = self.lm_head(self.norm(x))
loss = None
if targets is not None:
loss = F.cross_entropy(
logits.reshape(-1, logits.size(-1)),
targets.reshape(-1),
)
return logits, loss
model = TinyGPT(config).to(device)
optimizer = torch.optim.AdamW(
model.parameters(),
lr=3e-3,
weight_decay=0.01,
)
@torch.no_grad()
def estimate_loss(source, batches=20):
model.eval()
losses = []
for _ in range(batches):
x, y = get_batch(source)
_, loss = model(x, y)
losses.append(loss.item())
model.train()
return sum(losses) / len(losses)
history = []
for step in range(401):
if step % 100 == 0:
train_loss = estimate_loss(train_data)
val_loss = estimate_loss(val_data)
history.append((step, train_loss, val_loss))
print(
f"step={step:3d} "
f"train_loss={train_loss:.4f} "
f"val_loss={val_loss:.4f}"
)
x, y = get_batch(train_data)
_, loss = model(x, y)
optimizer.zero_grad(set_to_none=True)
loss.backward()
# 梯度裁剪降低小模型在较大学习率下偶发梯度爆炸的风险。
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
steps = [row[0] for row in history]
train_losses = [row[1] for row in history]
val_losses = [row[2] for row in history]
plt.plot(steps, train_losses, label="train")
plt.plot(steps, val_losses, label="validation")
plt.xlabel("step")
plt.ylabel("loss")
plt.legend()
plt.tight_layout()
plt.savefig("loss_curve.png", dpi=160)
plt.close()
checkpoint = {
"model_state": model.state_dict(),
"config": config,
"stoi": stoi,
"itos": itos,
}
path = Path("tiny_gpt.pt")
torch.save(checkpoint, path)
print("saved: loss_curve.png")
print(f"saved: {path}")预期输出
step= 0 train_loss=<TRAIN_LOSS> val_loss=<VAL_LOSS>
step=100 train_loss=<TRAIN_LOSS> val_loss=<VAL_LOSS>
step=200 train_loss=<TRAIN_LOSS> val_loss=<VAL_LOSS>
step=300 train_loss=<TRAIN_LOSS> val_loss=<VAL_LOSS>
step=400 train_loss=<TRAIN_LOSS> val_loss=<VAL_LOSS>
saved: loss_curve.png
saved: tiny_gpt.pt<TRAIN_LOSS> 与 <VAL_LOSS> 会随设备、PyTorch 版本和随机采样略有变化;关键不是某个固定数值,而是连续评估点的趋势。脚本同时保存曲线图片和包含参数、配置、字符到 ID 映射的检查点。
读懂损失曲线
理想的起步阶段通常是两条曲线一起下降,说明模型既在拟合训练数据,也在提升未参与更新的数据上的预测能力。如果训练损失持续下降而验证损失开始上升,说明模型正在记忆小语料,此时继续训练只会扩大过拟合。
如果两条曲线几乎不降,先检查学习率、因果掩码、目标是否真的右移一位,以及参数是否参与优化。若损失突然变成 nan,优先降低学习率并检查输入中是否出现非法 ID;本例的梯度裁剪只能降低风险,不能修复错误的数据或模型结构。
对于这个极小语料,最终生成质量仍会很有限。真正有价值的验收标准是:训练和验证损失能被稳定记录、曲线走势可解释、tiny_gpt.pt 能重新加载,并且后续生成阶段使用的词表与训练时完全一致。