训练循环全流程:前向、损失、梯度清零、反向、参数更新
Agent辅助工程检查
前置要求
第35日 N1 的九项梯度手算。
学习目标
解释 forward、loss、zero_grad、backward、step 五步契约,区分全批次梯度和单样本随机更新。
操作指引
先预测再运行。每个 epoch 在样本循环前清空参数梯度,每个样本新建前向计算图、计算平方 loss 并 backward 累加梯度;全部样本之后 step 一次。zero_grad 只要在本批首次反传前即可,下面将其放在 epoch 开头。四样本使用活动36-02的同一初始参数和数据,初始平均损失为2.106。
for epoch in range(EPOCHS):
for p in model.parameters():
p.grad = 0.0 # 1. zero stale gradients
total = 0.0
for (x, y) in dataset:
out = model(x) # 2. forward
loss = (out - y) ** 2 # 3. loss
loss.backward() # 4. backward (accumulates batch grads)
total += loss.data
for p in model.parameters():
p.data -= lr * p.grad # 5. step along -gradient
log(epoch, total / len(dataset))
自主演练与记录
1. 首样本 b_o 梯度4.2511,η=0.05,预测随机更新的方向与大小。2. 四样本累加梯度为3.2111,预测全批次更新。3. 预测40个epoch后均值损失。4. 指出 zero_grad 的位置及删除它的后果。
正梯度对应减小参数。全批次只在样本循环之前清零一次;在每个样本之前清零会丢弃之前样本的贡献,只有每个样本随后独立step时才符合随机更新。
随机一步 Δb_o=-0.05×4.2511=-0.2126,从0.3到0.0874。全批次 Δb_o=-0.05×3.2111=-0.1606,到0.1394。η=0.05的40个epoch中平均损失从2.106到约0.13,这是一次玩具实验而非一般保证。参数必须在每批反传前 zero_grad;省略后旧叶子梯度污染本批结果。
写对五步次序、两种更新的方向与大小,并解释需要 zero_grad 的累加约定。
权威源资源与权利证明
PyTorch Documentation: Autograd Mechanics
对应章节 / 时间戳: How autograd encodes the history
验证版本与日期: PyTorch 2.5 Documentation (Verified: 2026-10-30)
Official reference for computational graph construction, backward pass execution, and in-place mutation pitfalls.
Basic understanding of computational graphs and tensors.
The training loop mechanics and zero_grad requirements are illustrated with runnable Python code.
对比候选资源与选型分析 (2)
Alternative tape-based execution; PyTorch dynamic graph semantics are standard in modern LLM research.
Functional transformations (grad, vjp); PyTorch object-based graph is closer to the beginner micrograd model.
Neural Networks and Deep Learning: How the backpropagation algorithm works
对应章节 / 时间戳: Section: Learning with gradient descent
验证版本与日期: Online book (Verified: 2026-10-30)
Clear four-equation derivation of backpropagation with scalar and matrix notation.
Matrix multiplication and the multivariable chain rule from Days 19-24.
All four backprop equations and derivations are self-contained within the lesson text.
对比候选资源与选型分析 (2)
Comprehensive graduate reference, but heavier tensor notation than needed for first MLP derivations.
Modular computational graph view; used as secondary source on Days 35-36.