36 / 90

第 36 日:训练循环、学习率与工程故障陈列室

构建并执行完整的神经网络训练循环(前向、损失、zero_grad、反向传播、参数更新),比较不同学习率对收敛轨迹的真实影响,诊断常见工程故障,并通过独立掌握度考核。

模型、预训练与微调 (LoRA) 480 分钟专注学习(8 小时)
01 120 分钟

训练循环全流程:前向、损失、梯度清零、反向、参数更新

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 的位置及删除它的后果。

独立掌握标准

写对五步次序、两种更新的方向与大小,并解释需要 zero_grad 的累加约定。

权威源资源与权利证明

linking Modified BSD

PyTorch Documentation: Autograd Mechanics

作者 / 机构: PyTorch Contributors | 原始出处链接 ↗

对应章节 / 时间戳: 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)
TensorFlow tf.GradientTape Documentation ↗ compared_alternative [Apache 2.0]

Alternative tape-based execution; PyTorch dynamic graph semantics are standard in modern LLM research.

JAX autodiff cookbook ↗ compared_alternative [Apache 2.0]

Functional transformations (grad, vjp); PyTorch object-based graph is closer to the beginner micrograd model.

linking CC BY-NC 3.0 noncommercial

Neural Networks and Deep Learning: How the backpropagation algorithm works

作者 / 机构: Michael Nielsen | 原始出处链接 ↗

对应章节 / 时间戳: 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)
Goodfellow et al. Deep Learning (Chapter 6) ↗ compared_alternative [All Rights Reserved (free to view online)]

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.

02 120 分钟

真实训练观察:微型数据集上的学习率效应对比

独立掌握检查

前置要求

活动36-01的训练循环与第34日 N1。

学习目标

独立运行同一 N1 四样本实验,比较η=0.05与η=5.0的40个epoch,在0/10/20/30/39记录均值损失。

操作指引

在仓库根目录执行以下命令。两次运行恢复相同九个初始权重与四个样本。每个epoch重新建立参数叶子,每个样本重建内部图;四个梯度累加后更新。日志记录更新前的均值损失;更新用梯度之和,不是均值,改变约定会改变有效学习率。

python3 - <<'EOF'
from projects.autograd.engine import Value
initial = [0.5, -0.25, 0.1, -0.5, 1.0, -0.2, 1.0, -2.0, 0.3]
data = [((2.0,-1.0),1.0), ((0.5,0.5),-1.0), ((-1.0,1.0),-1.0), ((1.0,1.0),1.0)]
for lr in (0.05, 5.0):
    params = initial[:]
    for epoch in range(40):
        W = [Value(v) for v in params]  # Fresh leaves start with zero gradients.
        total = 0.0
        for (x1, x2), y in data:
            a1 = (W[0]*x1 + W[1]*x2 + W[2]).tanh()
            a2 = (W[3]*x1 + W[4]*x2 + W[5]).tanh()
            loss = (a1*W[6] + a2*W[7] + W[8] - y)**2
            loss.backward()  # Fresh interior graph, shared batch parameter leaves.
            total += loss.data
        if epoch in (0, 10, 20, 30, 39):
            print(lr, epoch, total / len(data))
        params = [p.data - lr*p.grad for p in W]  # Sum-gradient update, not mean.
EOF

自主演练与记录

1. 报告η=0.05在epoch 0、10、20、30、39的损失。2. 报告η=5.0对应数值。3. 从局部曲率解释步长过大如何越过谷底并放大发散。4. 给出本次玩具实验不能支持的一条一般性结论。

独立掌握标准

两次运行重现同一损失表,解释复合过冲而不是归因于随机失败,并限定结论只适用于本实验。

权威源资源与权利证明

linking 3Blue1Brown copyright (all rights reserved); site FAQ permits only short clips under stated conditions No video, audio, transcript or frame redistribution permitted

What is backpropagation really doing? (Chapter 3, Deep Learning)

作者 / 机构: Grant Sanderson (3Blue1Brown) | 原始出处链接 ↗

对应章节 / 时间戳: The Intuition for Backpropagation

验证版本与日期: Online video and article (Verified: 2026-10-30)

入选理由:

Visual and geometric intuition for how nudging weights impacts the final cost function.

来源前置条件:

Basic derivative intuition from Days 16-18.

安全回退方案(离线弹性):

The lesson derives the network gradient equations step by step without requiring video playback.

对比候选资源与选型分析 (2)
StatQuest Neural Networks Part 3 ↗ compared_alternative [Proprietary]

Step-by-step arithmetic without calculus notation; 3Blue1Brown provides the calculus-visual link needed.

Khan Academy Multivariable Chain Rule ↗ compared_alternative [CC BY-NC-SA 3.0]

Pure math focus; 3Blue1Brown contextualizes the chain rule specifically for neural network graphs.

linking MIT

micrograd: A tiny scalar-valued autograd engine

作者 / 机构: Andrej Karpathy | 原始出处链接 ↗

对应章节 / 时间戳: micrograd/engine.py: class Value (_backward closures and backward() topological sort); README 'Example usage'

验证版本与日期: Git commit master (Verified: 2026-10-30)

入选理由:

Minimal, readable implementation of scalar autograd and MLP layers directly matched to our project.

来源前置条件:

Python object-oriented programming and operator overloading from Day 31.

安全回退方案(离线弹性):

The local projects/autograd engine is runnable offline and matches micrograd semantics.

对比候选资源与选型分析 (2)
PyTorch autograd C++ engine ↗ compared_alternative [Modified BSD]

Production scale, but too large and complex for tracing by hand in introductory lessons.

Autograd (HIPS) ↗ compared_alternative [MIT]

Vectorized autograd; micrograd's pure scalar model is pedagogical for hand backprop.

03 120 分钟

故障陈列室:饱和死区、遗漏 zero_grad 与静默形状截断

Agent辅助工程检查

前置要求

活动36-02的实际本地训练观察。

学习目标

测量并修复重复反传的旧梯度、tanh 饱和、zip 静默丢输入三种不同故障。

操作指引

故障A:执行下方同一计算图反传两次的命令,测量w11.grad。故障B:仅将b1设为8.0使z1=9.25,记录tanh导数及隐藏权重梯度。故障C:计算 sum(w*x for w,x in zip([0.5,-0.25], [2.0,-1.0,999.0])),指出额外输入如何被丢弃。

python3 - <<'EOF'
import sys; sys.path.insert(0, '.')
from projects.autograd.engine import Value
x1, x2 = Value(2.0), Value(-1.0)
W = [Value(v) for v in (0.5,-0.25,0.1, -0.5,1.0,-0.2, 1.0,-2.0,0.3)]
a1 = (x1*W[0]+x2*W[1]+W[2]).tanh(); a2 = (x1*W[3]+x2*W[4]+W[5]).tanh()
loss = (a1*W[6]+a2*W[7]+W[8]-1.0)**2
loss.backward(); print('after 1st:', W[0].grad)
loss.backward(); print('after 2nd:', W[0].grad)
EOF

自主演练与记录

每个故障都记录数值、机制与最小修复:1. 同图两次反传的w11.grad。2. b1=8.0时 tanh'(9.25) 与隐藏权重梯度。3. zip求和的z及丢弃的输入999.0。

独立掌握标准

复现三种测量,将症状、机制、最小修复逐一对应,且能解释只清叶子为何不能修复复用的图。

权威源资源与权利证明

linking MIT

CS231n: Backpropagation and Intuitions

作者 / 机构: Andrej Karpathy / Stanford University | 原始出处链接 ↗

对应章节 / 时间戳: Patterns in backward flow

验证版本与日期: Course notes (Verified: 2026-10-30)

入选理由:

Modular local-gradient interpretation (gate operations: add, multiply, max) and gradient flow intuition.

来源前置条件:

Multivariable calculus and basic Python.

安全回退方案(离线弹性):

Local gate definitions and circuit flow diagrams in the lesson provide full coverage.

对比候选资源与选型分析 (2)

Raw circuit view; CS231n notes are more structured with explicit gate derivations.

Fast.ai Practical Deep Learning for Coders ↗ compared_alternative [GPL-3.0]

Top-down approach; CS231n bottom-up modular view matches our first-principles curriculum.

linking CC BY-NC 3.0 noncommercial

Neural Networks and Deep Learning: How the backpropagation algorithm works

作者 / 机构: Michael Nielsen | 原始出处链接 ↗

对应章节 / 时间戳: Saturation and unstable gradients

验证版本与日期: 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)
Goodfellow et al. Deep Learning (Chapter 6) ↗ compared_alternative [All Rights Reserved (free to view online)]

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.

04 120 分钟

独立掌握度考核:诊断、修复与技术原理解释

独立掌握检查

前置要求

活动36-01至36-03。

学习目标

独立写出 MLP 训练循环、诊断一个植入的故障并修复,完成客观测验。

操作指引

不使用AI:默写 zero_grad→forward→loss→backward→step。某次运行每轮梯度不断累加且损失发散,写出症状、机制和修复;独立完成测验,为错点选择补救链接。

自主演练与记录

1. 写出五步循环,指出删除哪行造成旧梯度累加。2. 损失2.1→10^30时,在η过大、遗漏zero_grad、饱和中选择最可能的两个原因,并设计区分测量。3. 独立模式完成三题并达100%。

客观知识检测:训练循环与故障诊断

请回答以下题目检验掌握情况。提交前请诚实声明你的辅助条件。

声明辅助条件

说明:无 AI 辅助属于诚实声明条件,非平台监控或强制检测手段。

1.

在 N1 的多层计算图上,未清零就第二次调用 loss.backward(),使 $w_{11}.grad$ 在 $2.0068$ 之后变成 $4.0135$——恰好 $2$ 倍。为什么?

2.

在观测到的 $\eta = 5.0$ 运行中,平均损失在 40 个 epoch 内爆炸到超过 $10^{151}$。其机制是:

3.

哪一种防护可以阻止标量 Neuron 实现中 zip 的静默形状 bug?

作答应证与历史记录

    独立掌握标准

    独立正确写出循环、对应故障机制与修复,并在独立测验取得100%。

    权威源资源与权利证明

    linking Modified BSD

    PyTorch Documentation: Autograd Mechanics

    作者 / 机构: PyTorch Contributors | 原始出处链接 ↗

    对应章节 / 时间戳: 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)
    TensorFlow tf.GradientTape Documentation ↗ compared_alternative [Apache 2.0]

    Alternative tape-based execution; PyTorch dynamic graph semantics are standard in modern LLM research.

    JAX autodiff cookbook ↗ compared_alternative [Apache 2.0]

    Functional transformations (grad, vjp); PyTorch object-based graph is closer to the beginner micrograd model.

    linking MIT

    micrograd: A tiny scalar-valued autograd engine

    作者 / 机构: Andrej Karpathy | 原始出处链接 ↗

    对应章节 / 时间戳: micrograd/engine.py: class Value (_backward closures and backward() topological sort); README 'Example usage'

    验证版本与日期: 2022 (Verified: 2026-10-30)

    入选理由:

    Deepest bottom-up mechanical clarity for backpropagation engine and computational graph visualization.

    来源前置条件:

    High-school calculus (derivatives) and basic Python syntax

    安全回退方案(离线弹性):

    Authored mathematical derivations, interactive Pyodide engine, and local tests provide complete offline study without video streaming.

    对比候选资源与选型分析 (2)
    PyTorch Autograd Internals ↗ compared_alternative [Modified BSD]

    Normative production documentation, but micrograd's pure Python implementation provides far superior initial clarity.

    3Blue1Brown: What is Backpropagation? ↗ compared_alternative [3Blue1Brown copyright (all rights reserved); site FAQ permits only short clips under stated conditions]

    High visual quality, pairs cleanly as optional supplementary visual reference.