← PyTorch From First Principles

训练:学习链哪环断了?

诊断能跑但学不会的模型:沿 TASK → OBJECTIVE → DEPENDENCY → GRADIENT → OPTIMIZER OWNERSHIP → PARAMETER UPDATE → CAPABILITY 走,用固定 batch、精确参数同一性、受控 SGD、小 batch 过拟合找到学习第一个缺席的后果。

这里有一段普通的迁移学习代码。小模型、冻结特征提取器、优化器、新任务的新分类 head。

model = TinyClassifier()

for p in model.features.parameters():
    p.requires_grad_(False)

optimizer = torch.optim.AdamW(model.parameters(), lr=1e-2, weight_decay=0.0)

model.head = nn.Linear(32, 2)          # adaptation, performed later

在平衡、完全对齐、完全可学的二分类任务上训两百步:

step=   0 loss=0.683606 acc=0.7144
step=  50 loss=0.683606 acc=0.7144
step= 100 loss=0.683606 acc=0.7144
step= 150 loss=0.683606 acc=0.7144
step= 200 loss=0.683606 acc=0.7144

不是近似不变。两百次小数六位相同。

没抛。看正常调试收集的证据:

loss                      0.683606
loss.requires_grad        True
loss.grad_fn              NllLossBackward0
head.weight  grad is None=False finite=True norm=1.555253e-01
head.bias    grad is None=False finite=True norm=4.327927e-03
optimizer.step() returned without raising

损失有限。有 grad_fn。backward() 在 head 上填了有限非零梯度。optimizer.step() 跑了。程序员随手拿的每个检查都报告健康,模型完全静止:

features.0.weight    delta=0.000000e+00
features.0.bias      delta=0.000000e+00
features.2.weight    delta=0.000000e+00
features.2.bias      delta=0.000000e+00
head.weight          delta=0.000000e+00
head.bias            delta=0.000000e+00

一检查说出为什么,不是关于梯度的检查:

features.0.weight    requires_grad=False in_optimizer=True
features.0.bias      requires_grad=False in_optimizer=True
features.2.weight    requires_grad=False in_optimizer=True
features.2.bias      requires_grad=False in_optimizer=True
head.weight          requires_grad=True  in_optimizer=False
head.bias            requires_grad=True  in_optimizer=False

优化器早建一行。它握着四个冻结特征张量(无梯度,跳过)与属于旧 head 的两参数对象(不再参与前向)。新 head 注册在模型上,named_parameters() 列它,state_dict() 存它,autograd 到达它,优化器里没有。所以 optimizer.step() 忠实更新了空。

两句话造成全部伤害,都是人们不自觉说的话:

loss.backward() 证明算了导数。它不证明收到导数的值会变。

optimizer.step() 证明优化器方法跑了。它不证明它拥有你想训的参数。

我们在哪

第 10 章给注意力很 specific、很有限的 certificate。它确立实现外部形状对、轴语义对、头重排对、掩码语义对、softmax 轴对、干预下因果 verified、与 PyTorch 自带参照一致、有限梯度到达每期待参数。

然后故意停了,把更难的情形交给本章:

forward runs
loss is finite
backward runs
gradients exist
optimizer.step() runs

and the model is still useless

开篇正是这个 state。损失永远 log(num_classes) 的模型、精度不出多数基线的模型、垃圾上训得漂亮的模型、第三步变 NaN 的模型,都是。

第 3 章给过一部分机器:哪些参数到损失有通路。第 5 章给过另一部分:哪套结构真正拥有张量对象。第 7 章给过第三部分:模型看到的表示是不是想要的意思。本章让它们成一次调查,因为训练系统不是 work 或不 work 的一个算子。

学习第一个没出现的后果是什么?

环境

本章每数、表、跟踪都来自跑出的代码,种子固定,环境:

PyTorch      2.13.0
Python       3.12.3
OS           Linux, CPU only

这里无 CUDA 设备,混合精度或设备相关数值不断言。归第 12 章,留那里。

技术:逐边界证明链

每章加一种调查法。第 2 章要第一个错的张量而不是第一个不合法的。第 3 章问梯度通路第一次消失处。第 5 章问哪套结构对归属不一致。第 7 章问样本在哪不再满足契约。第 8 章问推导与观测几何第一次分歧处。第 10 章问哪个注意力不变式先挂。

第 11 章加:

拿固定 batch 从任务契约跟踪到参数移动。第一个期待后果没出现处停。

这 work 因为学习不是事件。它是因果链,每箭头都蕴含一 batch 上可测的证据:

sample + target
      ↓        does y still describe x?
forward computation
      ↓        are the outputs in the form the objective expects?
objective / loss
      ↓        is this scalar the loss we intended?
autograd dependency
      ↓        does that loss depend on the parameters we mean to train?
gradient on intended parameters
      ↓        did those parameters receive finite derivatives?
optimizer ownership
      ↓        does the optimizer hold those exact objects?
parameter update
      ↓        did those exact objects move?
changed model behavior
      ↓        can repeated controlled steps fit a tiny fixed problem?
loss reduction on a controlled problem

开篇失败归属之前每边界满足,死在那。detach 隐层走到梯度。打乱目标关系第一边界就挂,其余全满足。三失败 headline 症状相同——损失不动 useful——同样反射改学习率。

学习率不在那张表。它在本章后面出现,每边界有证据后才出现,因为坏任务契约上调优化器是浪费一周最常见的路。

重要的转变是从:

“My model isn’t learning. What hyperparameter should I change?”

到:

“Which link in the learning chain have I actually proved?”

受控问题

无基线调试是多步骤的猜,本章建一小系统整章用。下面每个故意失败与它恰差一处。

import torch
import torch.nn as nn
import torch.nn.functional as F

RULE_W = torch.tensor([1.0, 0.75])

def known_rule(x):
    return ((x @ RULE_W) > 0).long()

def make_data(n=2048, seed=0):
    g = torch.Generator().manual_seed(seed)
    x = torch.randn(n, 2, generator=g)
    return x, known_rule(x)

class TinyClassifier(nn.Module):
    def __init__(self, hidden=32, num_classes=2):
        super().__init__()
        self.features = nn.Sequential(
            nn.Linear(2, hidden), nn.ReLU(),
            nn.Linear(hidden, hidden), nn.ReLU(),
        )
        self.head = nn.Linear(hidden, num_classes)

    def forward(self, x):
        return self.head(self.features(x))

def build(seed=42, **kw):
    torch.manual_seed(seed)
    return TinyClassifier(**kw)

任务是写下的规则线性可分:x0 + 0.75*x1 > 0 时类别 1。单属性让本章可能。因为规则已知,目标对齐精确可查而不是目测。因为问题容易,学不会 unambiguous 而不是耐心问题。整个 CPU 一秒内跑完,下面每断言读者终端可重推。

模型故意切 features 与 head,因为开篇 bug 在真实代码里正发生在这种结构。

健康参照

train class counts: [1039, 1009]
majority baseline : 0.50732421875
chance loss ln(2) : 0.6931471824645996
val class counts  : [258, 254] val majority 0.50390625
model = build(42)
opt = torch.optim.AdamW(model.parameters(), lr=1e-2, weight_decay=0.0)

for step in range(301):
    opt.zero_grad(set_to_none=True)
    loss = F.cross_entropy(model(x), y)
    loss.backward()
    opt.step()
 step  train loss  train acc  val loss  val acc
    0      0.6933     0.4976    0.6938   0.4922
   50      0.0158     0.9990    0.0121   0.9961
  100      0.0079     0.9995    0.0083   0.9961
  150      0.0045     0.9995    0.0075   0.9961
  200      0.0028     0.9995    0.0060   0.9961
  250      0.0019     1.0000    0.0049   0.9980
  300      0.0014     1.0000    0.0042   0.9980

三数值得留,后面比较没它们 meaningless。初始损失 0.6933,靠近 ln(2):两类等概率的交叉熵损失。任意没训的分类器不保证输出均匀概率;这里接近说明这个特定初始化从该参照附近开始。多数基线 0.5073,数据集上“永远预测大类”做到这个。健康跑三百全 batch 步到 0.0014 与训练精度完美。

末数最重要。坏变体 plateau 在 0.68 时,有意思的事实不是 0.68 是大数。而是这个 exact 模型、exact 数据、exact 优化器到过 0.0014。

基线注一句,因为常被 over-read。多数基线告诉你模型什么都没学会有用时指标什么样。它不告诉你模型为什么坐那,模型能 beat 它而什么都没学——开篇失败坐 0.7144 精度,远超 0.5073,纯因随机投影加随机线性 head 恰好与线性规则相关。基线是症状阈值,不是诊断。

边界 A:目标还描述输入吗?

第 7 章确立预处理是模型定义的一部分,表示能完全合法完全错。也确立方法:说出契约再检查,不管优化成不成。本章复用方法不重教五变换类别。

分类 batch 的契约有结构部分与语义部分。

def task_report(x, y, num_classes, rule=None):
    print(f"  x            shape={tuple(x.shape)} dtype={x.dtype} "
          f"finite={torch.isfinite(x).all().item()}")
    print(f"               range=[{x.min().item():+.3f}, {x.max().item():+.3f}] "
          f"mean={x.mean().item():+.4f} std={x.std().item():.4f}")
    print(f"  y            shape={tuple(y.shape)} dtype={y.dtype} "
          f"min={y.min().item()} max={y.max().item()}")
    counts = torch.bincount(y, minlength=num_classes)
    print(f"  class counts {counts.tolist()}  majority baseline "
          f"{(counts.max() / counts.sum()).item():.4f}")
    print(f"  aligned rows x.shape[0]==y.shape[0] {x.shape[0] == y.shape[0]}")
    if rule is not None:
        print(f"  known-rule agreement {(rule(x) == y).float().mean().item():.4f}")

现在用真实代码弄坏对齐的方式毁掉它——一数组置换另一不置换:

perm = torch.randperm(len(x), generator=g)
x_bad = x[perm]
y_bad = y                 # forgot to permute
HEALTHY
  x            shape=(2048, 2) dtype=torch.float32 finite=True
               range=[-4.094, +4.101] mean=-0.0096 std=0.9934
  y            shape=(2048,) dtype=torch.int64 min=0 max=1
  class counts [1039, 1009]  majority baseline 0.5073
  aligned rows x.shape[0]==y.shape[0] True
  known-rule agreement 1.0000

SHUFFLED INPUTS, LABELS LEFT ALONE
  x            shape=(2048, 2) dtype=torch.float32 finite=True
               range=[-4.094, +4.101] mean=-0.0096 std=0.9934
  y            shape=(2048,) dtype=torch.int64 min=0 max=1
  class counts [1039, 1009]  majority baseline 0.5073
  aligned rows x.shape[0]==y.shape[0] True
  known-rule agreement 0.5000

报告的结构统计全不变。形状、dtype、范围、类别数、行数揭不了置换,因为没删值删样本;显示的均值标准差也不变。变的是配对,只有一行看得见:与已知规则一致掉到 0.5000,这个平衡二分类上就是瞎猜。

训它,看健康机制拿坏问题干什么:

all trainable params owned: True
step-0 total grad norm 1.6257e-02  all finite True  min delta 1.414e-02 max delta 2.985e-01
step=   0 loss=0.6936 train acc=0.4976
step= 100 loss=0.6625 train acc=0.5918
step= 200 loss=0.6501 train acc=0.6045
step= 300 loss=0.6410 train acc=0.6167
held-out acc on the real task: 0.568359375

损失在降。训练精度在涨。梯度有限,优化器全拥有,每参数动。这是机械健康的训练系统在拟合任意输入标签配对。三百步只到 0.6167 训练精度,实验还没确立 2048 随机配对全记住;它确立这里更重要的:优化进展能与坏任务关系共存。真实任务上留出精度 0.568,基线 0.504 上一点点。

这就是任务契约放第一的原因:

健康的训练机制能优化坏的学习问题,还能看起来在进步。

真实数据集很少带 known_rule。但大多数带便宜可查的东西:能预测的类别分布、并排看的几个样本、标签须满足的不变量、答案已知的子集。第 7 章的论证原样适用——故意建的探针是唯一看见这个类别的仪器,张量 metadata 都看不见。

错位的镜像是泄漏:含答案的特征。同边界挂,同纪律抓,通常产出可疑好的结果而不是学不会的模型,不是本章的主题。

边界 B:这个标量是你想要的目标吗?

损失是函数,函数是代码,代码能跑得完美而错。最便宜的检查是手给一样本复现它。

logits = model(x[:1])
target = y[:1]

loss = F.cross_entropy(logits, target)
manual = -F.log_softmax(logits, dim=-1)[0, target.item()]
logits             [[0.091391 0.048356]]
target             0
F.cross_entropy    0.67186153
-log_softmax[t]    0.67186153
allclose           True

再 batch 版,归约也钉住:

batch F.cross_entropy        0.69213694
mean of per-example manual   0.69213694
reduction is 'mean'          True

十二行把“我用交叉熵”变成“我知道这个函数产出什么数、为什么”。不一致,找到边界。一致,排除整类 confusion,代价一次前向。

第 7 章关于目标的 nuance 值得带走不压平。F.cross_entropy 接受两种目标表示,都合法:

index-target loss    0.69213694
prob-target loss     0.69213694
smoothed prob target 0.69224751
label_smoothing=0.1  0.69224751

类别下标目标与 one-hot 概率目标这里数 exact 相同,手建 0.95/0.05 软目标精确复现 label_smoothing=0.1,两类下 smoothing 0.1 就是这个意思。所以“交叉熵要整数类别下标”不对。通用的是另一边:

交叉熵里模型的贡献必须是 logits。目标可以是下标或逐类概率。

锚失败:交叉熵前 softmax

probs = logits.softmax(dim=-1)
loss = F.cross_entropy(probs, y)

人人都犯过一次的错。跑,有限标量,有 grad_fn。梯度流动,优化器全拥有,参数动。同样初始化与正确版对比跑:

logits (correct)
   step      loss   grad norm  train acc
      0    0.6933  3.0339e-01     0.4976
      1    0.6467  3.0642e-01     0.9395
     50    0.0158  1.2085e-02     0.9990
    100    0.0079  5.2352e-03     0.9995
    200    0.0028  1.8874e-03     0.9995
    300    0.0014  4.1497e-03     1.0000

pre-softmaxed
   step      loss   grad norm  train acc
      0    0.6932  1.5088e-01     0.4976
      1    0.6695  1.5858e-01     0.9390
     50    0.3220  5.8824e-03     0.9995
    100    0.3178  3.1225e-03     0.9995
    200    0.3149  1.8243e-03     0.9995
    300    0.3141  1.0929e-03     1.0000

仔细读,天真故事错了。坏版学了。训练精度 100%。没做的是损失降到 0.3141 下,永远不会,因为那是它实际优化的目标的 floor:

perfect probs [1,0], target 0 -> 0.31326165795326233
-log(e^1/(e^1+e^0)) =           0.31326165795326233

交叉熵对交到手的东西施 log-softmax。给 [0, 1] 里的概率,最优输入是 one-hot 向量,正确类 log-softmax 是 -log(e / (e + 1)),约 0.3133。损失逼近它停住。看这个跑的程序员看到损失 plateau 在可疑 specific 的数,开始调学习率,正确观察是目标有它已到位的 floor。

有限、可微、下降的损失不是它是你想要的损失的证据。

注意它对梯度做了什么:pre-softmax 跑 step 0 梯度范数约半,因为 softmax 在损失看到前把模型输出范围压了。两目标,同样模型、同样初始化、同样数据、不同梯度,无错。

边界 C:损失实际依赖哪些参数?

常用检查是:

print("loss.requires_grad:", loss.requires_grad)
print("loss.grad_fn:", loss.grad_fn)

留着,精确说它确立什么。路径上任一单个张量要梯度,loss.requires_grad 就 True。第 3 章 concrete 过:健康的 grad_fn 的损失证明有东西连着,关于什么连着什么都没证明。

模型里改一行:

class DetachedClassifier(TinyClassifier):
    def forward(self, x):
        h = self.features(x)
        h = h.detach()          # the one changed line
        return self.head(h)
loss                 0.693254
loss.requires_grad   True
loss.grad_fn         NllLossBackward0

parameter            req_grad          grad  in_opt        delta
features.0.weight    True              None    True   0.0000e+00
features.0.bias      True              None    True   0.0000e+00
features.2.weight    True              None    True   0.0000e+00
features.2.bias      True              None    True   0.0000e+00
head.weight          True        1.5752e-01    True   7.8739e-02
head.bias            True        5.3857e-03    True   1.4142e-02

两图检查都过。六参数四 requires_grad=True、在优化器里、收不到任何梯度。这是第 3 章的问题,模型尺度问:

哪个意图参数先对这个损失没通路?

危险而不是 merely 坏的是这个:

step=   0 loss=0.6845 acc=0.5649
step= 100 loss=0.3047 acc=0.9438
step= 200 loss=0.2122 acc=0.9590
step= 300 loss=0.1676 acc=0.9702

模型还到 97%。固定随机投影上的线性 head 对这个任务够,失败不宣告自己是失败。它宣告自己是比该好略差的模型——0.1676 对参照跑的 0.0014——这种 gap 归到超参数从不调查。特征提取器不是死 weight:每前向都参与,提供 head 用的固定表示。死的是它的学习通路。四可训练参数张量穿过模型但永远不能 adapt,可见症状可能只是 disappointing 的数。

这是部分图断裂,不是“autograd 坏了”,区分就是全部诊断。detach 下游一切完好,这正是改下游任何东西没用的原因。

None 不是零,零不是 None

两 state 打印看起来像,意思完全不同。

这里是用受控办法产出后者。一层预激活推远负,ReLU 输出恒零:

model = build(42)
with torch.no_grad():
    model.features[0].bias.fill_(-100.0)
features.0 preactivation max : -96.8088
post-ReLU zero fraction      : 1.0

parameter                  grad         norm       max|g|
features.0.weight        tensor   0.0000e+00   0.0000e+00
features.0.bias          tensor   0.0000e+00   0.0000e+00
features.2.weight        tensor   0.0000e+00   0.0000e+00
features.2.bias          tensor   1.4861e-02   7.9112e-03
head.weight              tensor   1.5895e-02   4.5727e-03
head.bias                tensor   3.6695e-02   2.5947e-02

六参数每都有梯度张量。三张量精确零。机制局部可读:ReLU 输入负处导数零,回不到 features.0;features.2.weight 导数正比输入,输入全零所以零。features.2.bias 不受影响,偏置导数不依赖层输入。模型还能变——只经偏置——这产出慢、confusing、部分的学,而不是干净停。

与 detach 模型并排:

detached model  features.0.weight.grad is None: True
dead-relu model features.0.weight.grad is None: False

同样 headline 症状,不同边界,不同修复。

两件事别从这个结论。第一,零梯度不意味着“死 ReLU”——那是几种机制之一。第二,更重要,别给梯度大小贴绝对数值阈值。没有结构无关的“健康梯度范数”,数依赖损失尺度、参数形状、深度、初始化、batch。诊断的是比较:范数随步怎么变、层间差、与已知好跑比、非有限值第一次出现在哪。

边界 D:梯度证据

有用的梯度报告不是统计墙。它区分每参数四 state,state 在模型里出现的位置就是诊断:

missing        grad is None
zero           grad tensor exists, every element is zero
finite/nonzero grad tensor exists and carries signal
non-finite     grad tensor contains NaN or Inf

总梯度范数值得算,一行而不是一节:

total = torch.stack([p.grad.norm() for p in model.parameters()
                     if p.grad is not None]).norm()

健康参照 step 0 是 3.4720e-01。这个数自己 meaningless。同样模型 pre-softmax 损失下读 1.7188e-01,或一步从 3.47e-01 到 5.94e+05,或输入附近层读 0.0、输出附近层读 1.6e-02 时,它成证据。

仪器本身的规则一条,本章剩下依赖它:

观察与干预是不同算子。诊断 pass 不得裁剪梯度、改模型模式、重建优化器、step scheduler、改正则。

clip_grad_norm_ 尤其不属于调试步,因为它改被测的东西。deliberate 用时知道它返回什么:

signature: (parameters, max_norm, norm_type=2.0, error_if_nonfinite=False, foreach=None)
total grad norm before clipping : 0.347198
value returned by the function  : 0.347198
total grad norm after clipping  : 0.100000
returned value is the PRE-clip norm: True

返回值是裁剪前范数。记它真有用;以为它描述优化器接着吃的梯度记它,不是。“裁剪让 NaN 没了”是 workaround,不是诊断。

边界 E:优化器拥有那些精确对象吗?

第 5 章确立机制:优化器是构造时捕获的张量对象列表,成员按对象同一性——不按名字、不按形状、不按值。本章把它变成双向审计,因为两结构有两种不一致的办法,通常只查一种。

def optimizer_param_ids(optimizer):
    return {id(p) for g in optimizer.param_groups for p in g["params"]}

def ownership_audit(model, optimizer):
    """Two-way membership by object identity, in both directions."""
    opt_ids = optimizer_param_ids(optimizer)
    model_ids = {id(p) for p in model.parameters()}

    missing = [n for n, p in model.named_parameters()
               if p.requires_grad and id(p) not in opt_ids]
    stale = [p for g in optimizer.param_groups for p in g["params"]
             if id(p) not in model_ids]
    return missing, stale

missing 是致命方向:优化器永远碰不到的可训练参数。stale 是诊断方向:优化器仍握着模型到不了的张量。开篇失败上 missing 是 [head.weight, head.bias] 而 stale 两条。合一起强烈提示优化器构造后动过模型:模型有新可训练对象而优化器仍拥有到不了的旧对象。对象同一性确立 mismatch;head 样形状是 supporting 上下文,不是唯一签名。

值得跑的 subtlety

优化器的 zero_grad 清它拥有的参数的梯度。新 head 不是其中之一,训练循环里它的梯度从不清:

iteration   head.weight.grad norm   features.0.weight.grad
        1                0.155525   None
        2                0.311051   None
        3                0.466576   None
        4                0.622101   None
        5                0.777627   None

ratio to first iteration: 5.000010504061109

精确线性累积。参数从不动,梯度每轮相同,五次反向往没人读的缓冲存了五倍首梯度。还有:

optimizer.zero_grad(set_to_none=True) then inspect:
  head.weight.grad is None : False

第 1 章确立 PyTorch 往 .grad 累积、得有东西清。第 5 章确立 optimizer.zero_grad() 就是那个东西,只能清给它的。这里两事实合成整跑悄悄长梯度缓冲、从不用参数。

参照,这个版本 zero_grad 默认 set_to_none=True:

(self, set_to_none: bool = True) -> None
after default zero_grad, grad is None: True
after set_to_none=False, grad: tensor([[0., 0.], [0., 0.]])

默认对上一节重要:默认 zero_grad 后,没收到梯度的 owned 参数 .grad is None,不是零张量。所以“None”能是“清了没再填”也能是“到损失没通路”,区分是何时看的问题。

修复

改一处——手术后构造优化器:

model.head = nn.Linear(32, 2)

optimizer = torch.optim.AdamW(
    [p for p in model.parameters() if p.requires_grad],
    lr=1e-2, weight_decay=0.0,
)
features.0.weight    requires_grad=False in_optimizer=False
features.0.bias      requires_grad=False in_optimizer=False
features.2.weight    requires_grad=False in_optimizer=False
features.2.bias      requires_grad=False in_optimizer=False
head.weight          requires_grad=True  in_optimizer=True
head.bias            requires_grad=True  in_optimizer=True

features.0.weight    delta=0.000000e+00
features.0.bias      delta=0.000000e+00
features.2.weight    delta=0.000000e+00
features.2.bias      delta=0.000000e+00
head.weight          delta=7.873873e-02
head.bias            delta=1.414209e-02

step=   0 loss=0.675015 acc=0.7344
step=  50 loss=0.406795 acc=0.9297
step= 100 loss=0.302602 acc=0.9463
step= 150 loss=0.246815 acc=0.9570
step= 200 loss=0.210920 acc=0.9609
val acc 0.97265625

冻结特征 delta=0 是对的——那是声明的意图。head 动,损失降,留出精度 0.973。这就是静止模型与 work 的线性探针的区别。

构造里变了两样,只一样必要。优化器挪到手术后是修复。按 requires_grad 过滤是 separate、deliberate 的收紧:冻结张量交给优化器也 work,因为 .grad is None 的参数跳过。但那时优化器成员不再意味着“这是我想训的参数”。优化器内容与声明可训练集对齐,后面归属报告好读。

边界 F:那些对象真动了吗?

梯度是关于导数的断言。参数 delta 是关于模型的断言。不同测量,要紧的是第二个:

before = {n: p.detach().clone() for n, p in model.named_parameters()}
optimizer.step()
deltas = {n: (p.detach() - before[n]).norm().item()
          for n, p in model.named_parameters()}

参数能有完全健康的梯度而 delta 精确零,如果它不在优化器里、组学习率为零、优化器因自己原因跳过它。delta 是证据。

但动了不自动是你以为的更新。有 state 的优化器让当前梯度与当前步的关系间接:动量把 earlier 梯度带过来,Adam/AdamW 维护 running moment 估计,AdamW 的解耦 weight decay 贡献与梯度无关的项。所以两问题分开:

DID THE PARAMETER MOVE?
    measurable under the real optimizer, on any step

DID THIS GRADIENT PRODUCE EXACTLY THE UPDATE I EXPECT?
    needs a controlled optimizer

第 1 章,模型尺度

第 1 章训练建成一行:

w_new = w - lr * grad

那是一标量参数与手写循环。值得证明同样方程仍描述真实神经网络上真实 torch.optim 步,因为见过一次成立就不把优化器当 oracle。

实验须受控,用模型的拷贝与新鲜朴素 SGD,关掉每更新修饰:

probe = copy.deepcopy(model)
lr = 0.1
sgd = torch.optim.SGD(probe.parameters(), lr=lr,
                      momentum=0.0, weight_decay=0.0)

for p in probe.parameters():
    p.grad = None
F.cross_entropy(probe(xb), yb).backward()

before = {n: p.detach().clone() for n, p in probe.named_parameters()}
grads = {n: p.grad.detach().clone() for n, p in probe.named_parameters()}
sgd.step()
parameter             max|observed - (-lr*g)|    ||delta||     lr*||g||
features.0.weight                   2.724e-08   7.7473e-03   7.7473e-03
features.0.bias                     2.725e-08   2.6625e-03   2.6625e-03
features.2.weight                   7.422e-09   2.7025e-02   2.7025e-02
features.2.bias                     6.636e-09   5.4703e-03   5.4703e-03
head.weight                         7.218e-09   1.7827e-02   1.7827e-02
head.bias                           2.794e-09   7.7633e-03   7.7633e-03
allclose over every parameter: True

w_new = w - lr * grad,逐元,六张量 1218 参数,浮点 tolerance。第 1 章的标量循环不只是玩具算术:这些 deliberate 受限 SGD 设置下,它正是这个优化器做的事。

同样测量 AdamW 下,同样 state,第一步:

features.0.weight    ||delta||=7.9999e-01  lr*||g||=7.7473e-03   ratio=103.260
features.0.bias      ||delta||=5.6562e-01  lr*||g||=2.6625e-03   ratio=212.441
features.2.weight    ||delta||=2.9306e+00  lr*||g||=2.7025e-02   ratio=108.439
features.2.bias      ||delta||=5.5677e-01  lr*||g||=5.4703e-03   ratio=101.782
head.weight          ||delta||=7.8740e-01  lr*||g||=1.7827e-02   ratio=44.170
head.bias            ||delta||=1.4142e-01  lr*||g||=7.7633e-03   ratio=18.217

lr * ||grad|| 的 18 到 212 倍,每张量不同比。不是 bug;自适应优化器正为这个,它正是上面等式须附条件陈述的原因:

Δθ = -lr · grad 是受控朴素 SGD 实验的属性,不是通用优化器不变量。别硬把 AdamW 塞进去——新鲜 SGD 复现一步。

重读第 7 章开篇也值得记住:同样表示 bug SGD 下 catastrophic、Adam 下几乎 invisible。自适应更新归一化改变梯度对参数做的事,改变 bug 从外面看的样子。

一台仪器:学习台账

第 7 章有阶段报告。第 8 章有形状台账。第 9 章有特征空间检查器。第 10 章有注意力台账。本章的仪器在一固定 batch 上走学习链,说出第一边界证据与意图训练系统矛盾处。

设计约束是上面论证的,加一重要警告:这不是只读报告。它调 backward() 与 optimizer.step(),改梯度、参数值、优化器 state。拷贝/检查点上跑,或把这步当 deliberate 牺牲探针打算保留。探针里不裁剪、不 step scheduler、不改模式、不改正则。backward() 前清每模型参数 .grad 让梯度行描述这个 batch,预存梯度先报告,accidental carry-over 可见。

下面默认 expected 集是每 requires_grad=True 的参数。稠密受控模型对。条件、稀疏、混合专家模型里可训练参数某 batch 合法不参与;那时 expected 集须来自模型的执行契约而不是单 requires_grad。

def learning_ledger(model, optimizer, x, y, num_classes,
                    rule=None, loss_fn=F.cross_entropy):
    """One controlled, state-mutating probe over one fixed batch.

    Calls backward() and optimizer.step(), so it changes gradients, model
    parameters and optimizer state. It performs no clipping, scheduler step,
    mode change or regularization edit. Gradients are cleared to None before
    backward so the reported derivatives belong to this batch.
    """
    rows, first = [], None

    def row(section, label, text, ok=None, detail=None):
        nonlocal first
        rows.append([section, label, text, ok, detail])
        if ok is False and first is None:
            first = f"{section}/{label}"

    named = dict(model.named_parameters())
    expected = [n for n, p in named.items() if p.requires_grad]

    # TASK ------------------------------------------------------------
    row("TASK", "rows", f"x {x.shape[0]} / y {y.shape[0]}",
        x.shape[0] == y.shape[0])
    row("TASK", "types", f"x {x.dtype} / y {y.dtype}", y.dtype == torch.long)
    row("TASK", "finite", f"x finite {torch.isfinite(x).all().item()}",
        bool(torch.isfinite(x).all()))
    counts = torch.bincount(y, minlength=num_classes)
    row("TASK", "classes",
        f"counts {counts.tolist()}  majority baseline "
        f"{(counts.max() / counts.sum()).item():.3f}",
        bool(y.min() >= 0 and y.max() < num_classes))
    if rule is not None:
        agreement = (rule(x) == y).float().mean().item()
        row("TASK", "known rule", f"agreement {agreement:.3f}", agreement > 0.99)

    # FORWARD ---------------------------------------------------------
    row("FORWARD", "mode", f"model.training = {model.training}")
    logits = model(x)
    finite = bool(torch.isfinite(logits).all())
    row("FORWARD", "logits",
        f"{tuple(logits.shape)} {logits.dtype}  finite {finite}",
        finite and logits.shape[0] == x.shape[0])
    out = logits.detach()
    row("FORWARD", "scale", f"mean {out.mean():+.4f}  std {out.std():.4f}  "
                            f"max|.| {out.abs().max():.4f}")

    # LOSS ------------------------------------------------------------
    loss = loss_fn(logits, y)
    row("LOSS", "value", f"{loss.item():.6f}", bool(torch.isfinite(loss)))
    if loss_fn is F.cross_entropy and y.dtype == torch.long:
        manual = -F.log_softmax(logits[:1], dim=-1)[0, y[0]]
        one = F.cross_entropy(logits[:1], y[:1])
        row("LOSS", "one example",
            f"manual {manual.item():.6f} vs reported {one.item():.6f}",
            bool(torch.allclose(manual, one, atol=1e-6)))
    row("LOSS", "graph",
        f"requires_grad {loss.requires_grad}  grad_fn "
        f"{type(loss.grad_fn).__name__ if loss.grad_fn else None}",
        loss.requires_grad and loss.grad_fn is not None)

    # GRADIENT --------------------------------------------------------
    carried = [n for n in expected if named[n].grad is not None]
    row("GRADIENT", "pre-existing",
        f"{len(carried)}/{len(expected)} already held a gradient before backward",
        not carried)
    for p in model.parameters():
        p.grad = None
    loss.backward()

    absent = [n for n in expected if named[n].grad is None]
    live = [n for n in expected if named[n].grad is not None]
    nonfinite = [n for n in live if not torch.isfinite(named[n].grad).all()]
    zero = [n for n in live if not (named[n].grad != 0).any()]

    row("GRADIENT", "expected", f"{len(expected)} trainable parameters")
    row("GRADIENT", "present", f"{len(live)}/{len(expected)}", not absent,
        None if not absent else "None: " + ", ".join(absent))
    row("GRADIENT", "finite", f"{len(live) - len(nonfinite)}/{len(live)}",
        not nonfinite,
        None if not nonfinite else "non-finite: " + ", ".join(nonfinite))
    row("GRADIENT", "nonzero", f"{len(live) - len(zero)}/{len(live)}", None,
        None if not zero else "exactly zero: " + ", ".join(zero))
    if live:
        total = torch.stack([named[n].grad.norm() for n in live]).norm().item()
        row("GRADIENT", "total norm", f"{total:.4e}")

    # OPTIMIZER -------------------------------------------------------
    missing, stale = ownership_audit(model, optimizer)
    groups = "  ".join(
        f"[{i}] lr {g['lr']:g} wd {g.get('weight_decay', 0):g} n {len(g['params'])}"
        for i, g in enumerate(optimizer.param_groups))
    row("OPTIMIZER", "groups", f"{type(optimizer).__name__}  {groups}")
    row("OPTIMIZER", "owned",
        f"{len(expected) - len(missing)}/{len(expected)} trainable model parameters",
        not missing, None if not missing else "missing: " + ", ".join(missing))
    row("OPTIMIZER", "stale",
        f"{len(stale)} optimizer tensors no longer reachable from the model",
        not stale)

    # UPDATE ----------------------------------------------------------
    before = {n: p.detach().clone() for n, p in named.items()}
    optimizer.step()
    deltas = {n: (named[n].detach() - before[n]).norm().item() for n in expected}
    still = [n for n, d in deltas.items() if d == 0.0]
    row("UPDATE", "moved",
        f"{len(deltas) - len(still)}/{len(deltas)} expected parameters",
        not still, None if not still else "unchanged: " + ", ".join(still))
    if deltas:
        row("UPDATE", "delta range",
            f"{min(deltas.values()):.3e} .. {max(deltas.values()):.3e}")

    width = max(len(t) for _, _, t, _, _ in rows)
    print(f"LEARNING LEDGER   {type(model).__name__}   {type(optimizer).__name__}"
          f"   batch {tuple(x.shape)}")
    previous = None
    for section, label, text, ok, detail in rows:
        head = "" if section == previous else section
        previous = section
        mark = ""
        if ok is False:
            mark = ("  <-- FIRST DIVERGENCE" if f"{section}/{label}" == first
                    else "  fail")
        print(f"  {head:10s}{label:14s}{text:{width}s}{mark}")
        if detail:
            print(f"  {'':10s}{'':14s}{detail}")
    print(f"  first divergence: {first or 'none'}")
    return {"first_divergence": first, "loss": loss.item(), "deltas": deltas}

健康参照上:

LEARNING LEDGER   TinyClassifier   AdamW   batch (256, 2)
  TASK      rows          x 256 / y 256
            types         x torch.float32 / y torch.int64
            finite        x finite True
            classes       counts [115, 141]  majority baseline 0.551
            known rule    agreement 1.000
  FORWARD   mode          model.training = True
            logits        (256, 2) torch.float32  finite True
            scale         mean +0.1037  std 0.0457  max|.| 0.3531
  LOSS      value         0.694159
            one example   manual 0.671861 vs reported 0.671861
            graph         requires_grad True  grad_fn NllLossBackward0
  GRADIENT  pre-existing  0/6 already held a gradient before backward
            expected      6 trainable parameters
            present       6/6
            finite        6/6
            nonzero       6/6
            total norm    3.4720e-01
  OPTIMIZER groups        AdamW  [0] lr 0.01 wd 0 n 6
            owned         6/6 trainable model parameters
            stale         0 optimizer tensors no longer reachable from the model
  UPDATE    moved         6/6 expected parameters
            delta range   1.414e-02 .. 2.931e-01
  first divergence: none

二十二行,一 batch,从任务契约到参数移动的每边界的断言。这就是动超参数前“训练步机械 sound”该有的意思。

四坏系统,一台仪器

下面每系统与健康参照恰差一处,同样函数同样 batch 跑。后面 listing 删到不同的行;略去的每行与上面健康跑相同。

陈旧优化器成员

  TASK      rows          x 256 / y 256
            types         x torch.float32 / y torch.int64
            finite        x finite True
            classes       counts [115, 141]  majority baseline 0.551
            known rule    agreement 1.000
  FORWARD   mode          model.training = True
            logits        (256, 2) torch.float32  finite True
            scale         mean -0.0539  std 0.0429  max|.| 0.1612
  LOSS      value         0.685485
            one example   manual 0.675722 vs reported 0.675722
            graph         requires_grad True  grad_fn NllLossBackward0
  GRADIENT  pre-existing  0/2 already held a gradient before backward
            expected      2 trainable parameters
            present       2/2
            finite        2/2
            nonzero       2/2
            total norm    1.9480e-01
  OPTIMIZER groups        AdamW  [0] lr 0.01 wd 0 n 6
            owned         0/2 trainable model parameters          <-- FIRST DIVERGENCE
                          missing: head.weight, head.bias
            stale         2 optimizer tensors no longer reachable from the model  fail
  UPDATE    moved         0/2 expected parameters                   fail
                          unchanged: head.weight, head.bias
            delta range   0.000e+00 .. 0.000e+00
  first divergence: OPTIMIZER/owned

OPTIMIZER 之上每行报告健康,包括大多数人停看的梯度节。两行值得细读。expected 2 trainable parameters 是台账把冻结当真:requires_grad=False 是声明的意图,冻结参数不计入期待移动。而 groups ... n 6 对 owned 0/2 两数就是整个 bug——优化器握六张量,想训的两一个不在。

UPDATE 行真但下游。它是归属失败的后果,不是独立发现,正是第 8、10 章确立的纪律:先修第一次分歧,再跑。

detach 隐表示

TASK、FORWARD、LOSS 每行与健康跑相同,listing 从不再相同处开始:

  GRADIENT  pre-existing  0/6 already held a gradient before backward
            expected      6 trainable parameters
            present       2/6                                      <-- FIRST DIVERGENCE
                          None: features.0.weight, features.0.bias,
                                features.2.weight, features.2.bias
            finite        2/2
            nonzero       2/2
            total norm    1.9444e-01
  OPTIMIZER groups        AdamW  [0] lr 0.01 wd 0 n 6
            owned         6/6 trainable model parameters
            stale         0 optimizer tensors no longer reachable from the model
  UPDATE    moved         2/6 expected parameters                   fail
                          unchanged: features.0.weight, features.0.bias,
                                     features.2.weight, features.2.bias
  first divergence: GRADIENT/present

优化器节干净。归属完美。失败早一边界,UPDATE 行同样四名字、完全不同原因:不是“优化器没握它们”,是“它们没梯度可 step”。

两失败 UPDATE 行几乎相同,修复相反。这就是按链顺序走而不是从症状开始的论证。

毁掉的目标对齐

  TASK      rows          x 256 / y 256
            types         x torch.float32 / y torch.int64
            finite        x finite True
            classes       counts [115, 141]  majority baseline 0.551
            known rule    agreement 0.434                          <-- FIRST DIVERGENCE
  FORWARD   mode          model.training = True
            logits        (256, 2) torch.float32  finite True
  LOSS      value         0.695320
            one example   manual 0.685739 vs reported 0.685739
            graph         requires_grad True  grad_fn NllLossBackward0
  GRADIENT  present       6/6
            finite        6/6
            nonzero       6/6
            total norm    1.1394e-01
  OPTIMIZER owned         6/6 trainable model parameters
            stale         0 optimizer tensors no longer reachable from the model
  UPDATE    moved         6/6 expected parameters
            delta range   1.414e-02 .. 2.960e-01
  first divergence: TASK/known rule

台账里其余每行报告健康,在一坏行下。台账从 FORWARD 开始——调试通常从模型开始,因为模型有意思——它报告优化 nonsense 的完美训练系统。

台账看不见的失败

pre-softmax 目标跑它:

  LOSS      value         0.693597
            graph         requires_grad True  grad_fn NllLossBackward0
  GRADIENT  present       6/6
            finite        6/6
            nonzero       6/6
            total norm    1.7188e-01
  OPTIMIZER owned         6/6 trainable model parameters
  UPDATE    moved         6/6 expected parameters
  first divergence: none

first divergence: none,模型永远 plateau 在 0.3141。这不是待 patch 的缺陷;是仪器诚实说出 reach。注意它没做什么:one example 行缺席,因为损失函数不是 F.cross_entropy,台账拒绝验证它不知道的公式。它报告能量度的,对量度不了的不 claim。

第 10 章对注意力台账到 Level 1 到 3、到不了 Level 4 说过同样的话。这里的边界是:

台账证明机器完好。你才能说它优化的目标是不是你想要的。

失败矩阵

下面每行都是跑出的实验,不是期待:

Failure Task Loss Gradient Optimizer Delta Tiny batch
stale replaced head pass pass pass, 2/2 finite fail, 0/2 owned fail, 0/2 moved flat at 0.68758
detached hidden state pass pass fail, 2/6 present pass fail, 2/6 moved 0.149 vs 0.002
shuffled target relation fail, 0.434 pass pass pass pass memorizes
softmax before CE pass floor at 0.3133 pass pass pass stops at 0.3136
lr = 1e4 pass pass at step 0 pass at step 0 pass moved, wrong scale diverges to NaN

五里四有台账自己点名的第一次分歧。学习率是例外,值得精确说:step 0 台账每行过,包括 UPDATE/moved,因为参数动了。错的是相对参数的移动大小,delta range 行记录不 judge。那个失败要下面 escalation 仪器,台账在要发明阈值处报告证据而不是 verdict 正为这个。

边界 G:小固定 batch 装得下吗?

上面每边界一 batch 干净后,还剩一问题,唯一把它们一起测的:

这个模型、这个目标、这条更新路,在这些 exact 样本上把损失降得了吗?

测试不是“训了看”。是受控环境,学习该 trivial 容易,失败才 informative:

def tiny_batch_capability(model, x_small, y_small, optimizer=None,
                          steps=500, lr=0.5):
    """Controlled capability test on a fixed batch.

    optimizer=None copies the model and builds fresh plain SGD over its
    trainable parameters, answering 'can this MODEL fit these examples under
    this simplified optimizer?'. Passing an optimizer uses and mutates the
    supplied model/optimizer, answering 'can this TRAINING SYSTEM fit these
    examples?'. The caller is responsible for any model-level regularization
    such as dropout and for any augmentation applied before this function.
    """
    was_training = model.training
    if optimizer is None:
        model = copy.deepcopy(model)
        optimizer = torch.optim.SGD(
            [p for p in model.parameters() if p.requires_grad],
            lr=lr, momentum=0.0, weight_decay=0.0)
    model.train()
    initial = None
    for step in range(steps + 1):
        logits = model(x_small)
        loss = F.cross_entropy(logits, y_small)
        if step == 0:
            initial = loss.item()
        optimizer.zero_grad(set_to_none=True)
        loss.backward()
        optimizer.step()
    model.eval()
    with torch.no_grad():
        logits = model(x_small)
        final = F.cross_entropy(logits, y_small).item()
        acc = (logits.argmax(-1) == y_small).float().mean().item()
    model.train(was_training)
    return initial, final, acc

optimizer 参数不是方便。是要点:

system                         optimizer      initial     final  accuracy
healthy                        as built       0.69209   0.00227    1.0000
healthy                        fresh SGD      0.69209   0.00227    1.0000
frozen feats + new head        as built       0.68758   0.68758    0.7188
frozen feats + new head        fresh SGD      0.68758   0.14840    0.9688
detached representation        as built       0.69209   0.14906    0.9688
healthy, RANDOM labels         fresh SGD      0.69527   0.00080    1.0000

开篇系统两行看。真优化器损失一动不动:0.68758 到 0.68758。新鲜优化器降到 0.148,32 样本对 31。模型一直 capable。不 capable 的是训练系统。 悄悄重建优化器的小 batch 测试修了它本该检测的 bug,报告一切 fine。

所以人们常写的测试版——新模型、新优化器、小 batch——回答的是容量问题。是真问题,不是手头特定训练跑学不会时的问题。

小 batch 测试证明什么

过了它,真训练系统下支持所有:

the representation reaches the model
the objective can be reduced on these examples
the graph delivers useful gradients
the optimizer can change the model
the model has enough capacity to fit this batch under this setup

现在看表末行,这就是它不能成 ritual 的原因。标签换硬币:

random labels agreement with known rule: 0.4375

  step      loss  accuracy
     0   0.69527    0.3750
    25   0.51209    0.7500
   100   0.40176    0.7812
   500   0.11932    1.0000
  2000   0.00080    1.0000

32 样本标签毫无意义,完美记住。小 batch 测试高分通过,数据毫无可学结构。

小 batch 测试通过证明这个模型、目标、更新路装得下这几个特定样本。它不证明样本编码了你想要的任务。

这正是它坐链末而不是链首的原因。任务契约排除那个,只有它下游什么都排除不了。

挂了它也不指认病因:

it does not tell you whether the problem is capacity, the objective,
the graph, ownership, the update scale or the regularization

它说本地系统仍有错,泛化还不是问题。链上它是定位。

正则是 forensics 的 confounder

小 batch 测试挂了,第一动作不是改模型。是去掉 deliberate 加的因果路。这里是 32 样本模型完美记住的完整菜谱:dropout 0.5、weight decay 0.1、输入噪声 0.5、label smoothing 0.1。

 step     0  train loss  0.74043   eval loss  0.69209  eval acc 0.5000
 step   100  train loss  0.41364   eval loss  0.26129  eval acc 0.9375
 step   500  train loss  0.37314   eval loss  0.25478  eval acc 0.9688
 step  1000  train loss  0.45278   eval loss  0.26875  eval acc 0.9688
 step  2000  train loss  0.40803   eval loss  0.24468  eval acc 0.9688

32 样本两千步,到不了 0.24 下。没坏。逐个去掉 confounder:

 no input noise
  step  2000  train loss  0.25678   eval loss  0.07379  eval acc 1.0000
 no noise, no smoothing
  step  2000  train loss  0.08353   eval loss  0.01601  eval acc 1.0000
 + weight_decay 0
  step  2000  train loss  0.02566   eval loss  0.00067  eval acc 1.0000
 + dropout 0
  step  2000  train loss  0.00000   eval loss  0.00000  eval acc 1.0000

每都是去掉 exactly 一处 variation 的干预,每处都动数。这些机制没一个坏。每条在参数与损失间加因果路,forensics 时多余路全是 confounder。

建 obviously 该学的最小训练系统。再一次加回一机制。

简化时模式搞对,精确说它干什么。model.train() 与 model.eval() 置模块层级的训练模式 flag。dropout、batch norm 之类读 self.training 的模块可能改行为。这些调用不开关 autograd:

train mode, two identical calls agree: False
eval  mode, two identical calls agree: True

in eval mode:
  loss.requires_grad True
  loss.grad_fn       NllLossBackward0
  gradients present  4 / 4

in train mode inside torch.no_grad():
  loss.requires_grad False
  loss.grad_fn       None

eval() 不关 autograd;eval 模式反向填每梯度。torch.no_grad() 不关 dropout。解不同问题,互不代替。

Escalation:每边界都过时看什么

到此全便宜——一 batch、一步。全干净而小 batch 测试还挂,下台仪器贵,按此顺序拿。

激活统计

前向 hook 观测模块边界。实在局限值得说:nn.Linear 上的 hook 看到该模块输出,看不到 forward 方法里 inline 写的任意张量算子,函数式模型对它们大半 invisible。

def activation_report(model, x, types=(nn.Linear, nn.ReLU)):
    rows, handles = [], []

    def make(name):
        def hook(module, inputs, output):
            if not torch.is_tensor(output):
                return
            o = output.detach()
            rows.append((name, type(module).__name__, tuple(o.shape),
                         bool(torch.isfinite(o).all()),
                         o.mean().item(), o.std().item(),
                         o.min().item(), o.max().item(),
                         (o == 0).float().mean().item(),
                         o.std(dim=0).mean().item()))
        return hook

    for name, module in model.named_modules():
        if isinstance(module, types):
            handles.append(module.register_forward_hook(make(name)))
    try:
        with torch.no_grad():
            model(x)
    finally:
        for h in handles:
            h.remove()
    return rows

返回行不打印;下面格式是 separate concern。try/finally 不是装饰。hook 忘摘后面每次前向都跑,包括真训练循环里的。

HEALTHY (untrained)
  module      type    shape      fin        mean      std      min      max  zero%  batch std
  features.0  Linear  (256, 32)  True     -0.019    0.725   -2.675    3.478   0.0%     0.5386
  features.1  ReLU    (256, 32)  True      0.280    0.430    0.000    3.478  51.8%     0.3051
  features.2  Linear  (256, 32)  True     -0.059    0.313   -2.263    1.246   0.0%     0.2134
  features.3  ReLU    (256, 32)  True      0.090    0.137    0.000    1.246  52.9%     0.0930
  head        Linear  (256, 2)   True      0.104    0.046    0.022    0.353   0.0%     0.0449

HEALTHY (after 300 steps of the reference run)
  module      type    shape      fin        mean      std      min      max  zero%  batch std
  features.0  Linear  (256, 32)  True      0.141    1.097   -6.173    5.953   0.0%     0.9362
  features.1  ReLU    (256, 32)  True      0.498    0.700    0.000    5.953  44.5%     0.5866
  features.2  Linear  (256, 32)  True      0.395    5.769  -56.815   46.287   0.0%     4.8293
  features.3  ReLU    (256, 32)  True      2.152    3.823    0.000   46.287  53.8%     3.0047
  head        Linear  (256, 2)   True      0.098   54.267 -211.192  208.711   0.0%    53.3090

DEAD FIRST LAYER (features.0.bias = -100)
  module      type    shape      fin        mean      std      min      max  zero%  batch std
  features.0  Linear  (256, 32)  True    -99.986    0.571 -102.768  -96.809   0.0%     0.5386
  features.1  ReLU    (256, 32)  True      0.000    0.000    0.000    0.000 100.0%     0.0000
  features.3  ReLU    (256, 32)  True      0.044    0.063    0.000    0.176  53.1%     0.0000
  head        Linear  (256, 2)   True      0.102    0.067    0.035    0.168   0.0%     0.0000

zero% 列是陷阱,这张表就是证明。ReLU 设计产出零:健康模型读 51.8% 与 52.9%,成功训三百步后读 44.5% 与 53.8%。死模型里 features.3 读 53.1%——完全正常——网两层前已塌。“死 ReLU 百分比”阈值没用。

认出失败的是末列:跨 batch 的标准差,问层输出依不依赖进的是哪个样本。features.1 起读 0.0000。logits 256 样本字面相同,这是构造上不能判别的模型,比任何零比例都强的陈述。

更新尺度,不是梯度尺度

离谱学习率值得跑,因为跟踪与人们讲的故事矛盾:

step         loss    grad norm   param norm   delta norm logits finite
   0   6.9416e-01   3.4720e-01   5.3009e+00   3.4720e+03          True
   1   9.7960e+07   5.9419e+05   3.4720e+03   5.9419e+09          True
   2   1.2313e+26   5.3972e+17   5.9419e+09          inf          True
   3          nan          nan          inf          nan         False

step 0 梯度范数 3.47e-01——健康参照同样值,因为同样模型同样 batch。梯度没大。大的是 lr * grad:范数 5.3 的参数张量收到范数 3472 的更新。步骤 1、2 的爆炸是第一次更新的后果,不是病因。

“梯度炸了”与“更新毁了参数”是不同诊断。梯度范数、参数范数、delta 范数分三列报告,因为第一步分开它们,后面每步分不开。

第一个非有限边界

别调终 NaN。找第一个变非有限的张量。上面 run 继续,看损失第一次报 nan 的步:

parameters entering step 3:
  features.0.weight    finite=True  max|.|=7.6892e+20
  features.0.bias      finite=True  max|.|=1.2599e+21
  features.2.weight    finite=True  max|.|=2.0724e+21
  features.2.bias      finite=True  max|.|=7.5346e+12
  head.weight          finite=True  max|.|=8.0718e+20
  head.bias            finite=True  max|.|=1.5646e+03

  input          finite=True  inf=    0 max|.|=4.1015e+00
  features.0     finite=True  inf=    0 max|.|=4.3012e+21
  features.1     finite=True  inf=    0 max|.|=2.2211e+21
  features.2     finite=False inf=  783 max|.|=inf
  features.3     finite=True  inf=    0 max|.|=4.8522e+34
  head           finite=False inf=  208 max|.|=inf
  first non-finite stage: features.2

每参数有限。第一个非有限值出现在前向里 features.2,量级 2e21 的矩阵碰量级 2e21 的激活,上溢 float32。

再看 features.3。又有限了。783 个 inf 全负,ReLU(-inf) 是 0——ReLU 把证据吞了,两阶段后 logits 里再现。只在损失上放检查,报告的 NaN 在第一次上溢下游三阶段,离造成它的更新下游三步。症状与病因间六边界,决定看第一个而不是最后一个后每都便宜看。

def assert_finite(name, t):
    if not torch.isfinite(t).all():
        raise RuntimeError(f"{name} first became non-finite")

前向问题这种显式分阶段检查通常够。非有限值第一次出现在 backward() 而不是 forward(),第 3 章有 torch.autograd.detect_anomaly(),把失败反向算子与产出它的前向算子关联。是真开销的调试工具;别开着不关。

学习率与优化器实际握着什么

现在——任务、目标、依赖、梯度、归属、移动全有证据后——学习率对比说得上话。规则是每候选同样模型 state、同样 batch、同样步数开始:

base = build(42)
state = copy.deepcopy(base.state_dict())

for lr in [1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1.0, 10.0]:
    m = TinyClassifier()
    m.load_state_dict(state)
    ...
        lr   loss @0  loss @100  acc @100  total delta
     1e-05    0.6942     0.6940    0.4883   3.4794e-04
     1e-04    0.6942     0.6930    0.5156   3.4668e-03
     1e-03    0.6942     0.6825    0.7812   3.4065e-02
     1e-02    0.6942     0.5925    0.7227   3.1063e-01
     1e-01    0.6942     0.0949    1.0000   2.1698e+00
     1e+00    0.6942     0.0162    1.0000   4.3333e+00
     1e+01    0.6942     1.4909    0.5039   2.2257e+02

每行 loss @0 相同是受控对比的证据。不同随机初始化比,叫学习率实验,表长得一模一样,meaningless。第 14 章拥有两跑可比的一般问题;这里要求窄——同样 state、同样数据、同样步数。

total delta 列是可解释的。lr=1e-5 百步全模型动 3.5e-04。这不是卡住的训练跑;是慢到看不见的训练跑,两者回应不同。

最后,别从配置文件读学习率,别 assumed param_groups[0] 代表优化器:

group 0: lr=0.0001 weight_decay=0 params=4
group 1: lr=0.1 weight_decay=0.01 params=2
after step 0: lrs = [1e-05, 0.010000000000000002]
after step 1: lrs = [1.0000000000000002e-06, 0.0010000000000000002]
after step 2: lrs = [1.0000000000000002e-07, 0.00010000000000000003]

两组学习率差千倍、weight decay 不同,StepLR 每 batch 而不是每 epoch step 一次,三步把特征学习率从 1e-4 干到 1e-7。第一次 scheduler 步后 param_groups[0]["lr"] 正确报告组 0 的 1e-05。错的是把它当优化器的学习率:它关于同时 0.01 的 head 组什么都没说。

逐组检查优化器的当前 state。不是记得配置的学习率。

损失、精度与什么算学会

还有个测量陷阱,因为它 regularly 把人带错路。参照模型朴素 SGD 下看四十步:

step      loss  accuracy  mean margin
   0   0.69416    0.4766     -0.00160
   5   0.68821    0.7266      0.01023
  10   0.68253    0.7773      0.02178
  20   0.67173    0.7109      0.04443
  30   0.66136    0.6836      0.06704
  40   0.65142    0.6680      0.08948

损失单调降。正确与错误 logit 间平均间隔单调涨。精度先涨再降,0.7773 到 0.6680。没坏。精度是 argmax 的阶跃函数,样本过决策边界才变,训练早期模型平均置信涨、几个样本反向走,完全可能。

损失与精度回答不同问题。精度平不是模型平的证据,几步精度降不是坏了的证据。损失与任务恰当的指标一起读。

单步同样 caution。别断言每 optimizer.step() 必须降当前 batch 损失——随机或自适应优化器没 bug 也能走出不降的步。单步不变量是受控更新下的参数移动;有用损失下降是多步能力断言。分开。

本章止于哪

两边界故意关着。

全精度训对、混合精度才挂,说明本章的活干完了:同样受控问题 float32 学会,把混合精度执行路交给第 12 章,它拥有 autocast、梯度缩放与它们和性能的交互。这个环境无 CUDA 设备,这里不断言它们。

模型学会、新跑比旧跑差,是不同问题不同方法。第 11 章用固定种子、固定 batch、冻结初始 state,因为复现不了的失败调查不了。两完整训练跑可比推不出,第 14 章拥有它:跑间 variation、配置环境变了什么、验证差是回归还是普通跑间 variation。

失败 intermittent,先存证据而不是凭记忆复现:

if not torch.isfinite(loss):
    torch.save({"x": x_batch.detach().cpu(), "y": y_batch.detach().cpu(),
                "model": model.state_dict(),
                "optimizer": optimizer.state_dict(), "step": step},
               "failing_batch.pt")
    raise RuntimeError("non-finite loss")

存下的 batch 把稀有失败变成确定性测试用例,本章每技术适用的 state。

在学不会的模型上用 AI

问助手“模型为什么不学”,得到 plausible 清单,因为问题 invite 的就是清单。上面每项都是某处真失败的真病因。没有一项是关于你系统的证据。

下面 prompt work 因为它拒绝修复、要定位。故意长:结构就是价值。

My PyTorch model runs but does not learn.

Do not rewrite the model and do not suggest hyperparameters yet.

I will provide evidence from one fixed batch.

Build a learning-chain table with these boundaries:

1. TASK
   - what does one input represent?
   - what does its target mean?
   - what evidence says they are still aligned?

2. OBJECTIVE
   - logits shape and range
   - exact loss function and target representation
   - manual one-example verification

3. DEPENDENCY
   - loss.requires_grad and grad_fn
   - the full list of parameters I expect to be trainable

4. GRADIENT
   - for each expected parameter:
     grad None / exactly zero / finite / non-finite, and grad norm

5. OPTIMIZER OWNERSHIP
   - trainable model parameter ids
   - optimizer parameter ids
   - model parameters missing from the optimizer
   - optimizer parameters no longer in the model

6. UPDATE
   - parameter norm before
   - parameter delta after one step
   - the current learning rate for EVERY parameter group

7. CAPABILITY
   - tiny fixed-batch initial loss
   - loss after controlled repeated steps with the REAL optimizer
   - final tiny-batch accuracy

Identify the FIRST boundary whose evidence contradicts the intended
training system.

For that boundary:
- give me the two or three most plausible mechanisms;
- propose the smallest experiment that distinguishes them;
- say which measurement should change if the diagnosis is correct;
- say which measurement must stay unchanged.

Do not propose architecture changes, learning-rate tuning, gradient
clipping, mixed precision, more data or another optimizer until every
earlier boundary has passed.

三句赚回位置。要第一边界而不是清单,不让 plausible 下游修复用在上游病因——本章四台账跑里两 UPDATE 行几乎同文、病因完全不同。要什么须不变, proposed 实验可证伪而不只是 confirmatory。real 优化器的小 batch 测试堵住新鲜优化器悄悄修了正在调查的 bug 的 loophole。

末段留着。给症状的助手伸手够链尾干预,因为训练数据里讨论最多的就是那些。学习率、优化器选择、裁剪、结构全在六边界下游,六边界便宜查、更可能坏。

让 AI 先定位第一个缺席的后果,再让它修训练。

学习链调试序列

 1. Freeze one known batch and a known initial state. Make the failure
    repeatable before trying to explain it.

 2. Prove the TASK. Does each target still describe its input? Use a probe
    you built on purpose; no tensor statistic can see this.

 3. Prove the OBJECTIVE. Are the model's outputs in the form this loss
    expects? Reproduce the loss by hand for one example.

 4. Prove the DEPENDENCY. Which of the parameters you intend to train does
    this loss actually reach? loss.grad_fn is not that evidence.

 5. Prove the GRADIENT. Are the expected gradients present and finite?
    Distinguish None from exactly zero from non-finite, and note where in
    the model each occurs.

 6. Prove OWNERSHIP. Does the optimizer hold those exact parameter objects?
    Check both directions: missing from the optimizer, and stale in it.

 7. Prove the UPDATE. Snapshot, step, measure deltas. Read the current
    learning rate and weight decay for every parameter group.

 8. If the update semantics are still unclear, reproduce one step on a copy
    with fresh SGD (momentum 0, weight decay 0) and verify d(theta) = -lr * grad.

 9. Prove CAPABILITY. Strip augmentation, dropout, weight decay, smoothing
    and schedulers, then overfit a tiny fixed batch — with the REAL
    optimizer, not a fresh one.

10. If that still fails, escalate: per-layer activation statistics including
    across-batch variation, gradient versus update scale, and the first
    non-finite stage.

11. Only once the controlled system learns should you reintroduce
    regularization, augmentation, schedulers, mixed precision and the full
    dataset — one at a time.

12. Change one thing. Rerun from the first boundary that change could affect.

步骤 2 到 4 抓住梯度检查抓不住的。步骤 5 到 7 抓住开篇失败。步骤 9 抓住之前什么都抓不住的,证明的比人们以为的少。

你现在应该能回答什么

这里有会被递到手里的台账式总结。是构造场景,不是本章实验。先自己走一遍再往下读。

loss 0.6931 at step 0, 0.6929 at step 500
accuracy 0.507 throughout
all 14 parameters: requires_grad True, grad present, grad finite
total grad norm 4.1e-06
optimizer: AdamW, 1 group, lr 3e-4, 14 params, 0 missing, 0 stale
all 14 parameters: nonzero delta after one step
tiny batch (32 examples, real optimizer, 2000 steps): 0.6931 -> 0.6902

第一无支撑的边界是哪? A 到 F 没有。任务、目标、依赖、梯度、归属、更新全报告与健康系统一致的证据。第一无支撑的是 capability:模型装不下 32 样本。调查从那里继续,上面一切便宜排除。

4.1e-06 是小梯度范数吗? 按陈述答不了,这就是陷阱。没有结构无关的尺度。对比成证据:与已知好跑的同样测量比、与别的层范数比、与它随步的轨迹比。

损失坐 0.6931、精度 0.507,说明什么? 说明模型在平衡二分类上输出近均匀预测,因为 ln(2) = 0.6931、多数基线 0.507。这是症状的精确描述,关于病因什么都没说。卡住的优化器、坏图、错位目标关系、小三量级的学习率都经过这个 exact state。

每参数 delta 非零,证明优化器 work 对吗? 不。证明对象动了。本章测量里 AdamW 下 delta 是 lr * ||grad|| 的 18 到 212 倍,解耦 weight decay 贡献与梯度无关的移动。检查特定梯度产出特定更新,用拷贝与新鲜朴素 SGD。

重建优化器小 batch 测试过了,系统修好了吗? 没有——你换了被测系统。开篇失败正是这样藏的:真优化器 0.68758 不动,新鲜优化器 0.148。两数之 gap 就是诊断。

训练损失降验证损失不降,是本章的问题吗? 不是。这里每边界关于机制 work 不 work,它 work。训练/验证 gap 是泛化问题,是两测量可比吗的问题,归第 7、14 章。

损失 plateau 在 0.3133 附近、精度 100%,发生什么? 本章两类实验里交叉熵前 pre-softmax 正产出这个极限 floor,强烈提示检查目标边界。不熟悉系统里不是唯一指纹:先验证传给损失的张量到底是什么再点名病因。

step 40 损失出现 NaN,看哪? 不是 step 40 的损失。逐阶段跟踪前向找第一个非有限的张量,再看进这步的参数是否已巨大,再看前一步更新尺度。本章例子病因与 NaN 间三阶段三步——中间还有 ReLU 把 inf 零掉,非有限值 briefly 消失再回来。

“没学”与“学得太慢”分开的单证据是什么? 没有通用单测量。参数移动分开静止模型与变化的模型,受控损失轨迹说移动有用否。本章 lr=1e-5 跑里模型百步动 3.5e-04,每机械边界过,损失只动一点点;合一起支持“学得太慢”。零 delta 定位另一类失败,但非零移动本身不证明有用学习。

练习

  1. 有梯度无更新。 复现开篇:冻结特征提取器,构造优化器,再换 head。证明新 head 在 named_parameters() 里、要梯度、收到有限梯度、不在优化器里、参数 delta 精确零。再测它 .grad 五轮行为并解释 optimizer.zero_grad() 为什么没清它。只修优化器构造。
  2. 第 1 章,模型尺度。 一固定 batch 上,模型拷贝与新鲜 SGD(lr, momentum=0, weight_decay=0) 验证每参数 Δθ = -lr · grad 到浮点 tolerance。再 momentum=0.9、AdamW 各重复,记每参数 ||Δθ|| 对 lr·||grad|| 比。解释等式为什么两种变化下都不该活。
  3. detach 一边。 两层间插 detach()。认出第一梯度变 None 的参数,确认 loss.requires_grad 与 loss.grad_fn 全程健康。再与参照跑比终损失,论证这个失败为什么比完全停住难注意。
  4. 零不是 None。 建受控死 ReLU 情形。每参数记 .grad 是 None、精确零张量、非零,逐个从局部导数解释。再解释死区里一偏置为什么仍收到梯度。
  5. 毁掉对齐。 输入置换标签不置换。证明形状、dtype、范围、均值、标准差、类别数全不变,只有已知规则探针挂,完整训练系统机械健康。报告真实任务上留出精度并与 trivial 基线比。
  6. 错目标,对机制。 同样初始化对比 logits 上交叉熵与已 softmax 概率上交叉熵。报告损失轨迹、step-0 梯度范数、终训练精度。C 类解析推导坏目标 floor,C = 2 与 C = 10 数值验证。
  7. 两小 batch 测试。 坏系统上能力测试跑两次:真优化器一次、新鲜优化器一次。解释两答案不同、每回答哪个问题。再 randint 标签跑,报告记住要多少步。
  8. 一次简化一机制。 dropout、weight decay、label smoothing、输入噪声加身、32 样本装不下的模型拿来。同样初始 state 每次去掉一机制跑,记终损失。认出 gap 大头是哪一机制,说出它说明什么、不说明什么。
  9. 没见过的模型上一 batch forensics。 小模型跑学习台账。改任何东西前认出第一无支撑 link。再故意引入第二靠后失败,重跑,确认台账仍报告 earlier 那个。

下一步:学会了,机器用好了吗?

学习不再是发生或不发生的东西。它是可观测后果的链,每 link 一 batch 上留证据:

TASK        the target still describes the input        known-rule probe
OBJECTIVE   the scalar is the loss we intended          one-example derivation
DEPENDENCY  the loss reaches the intended parameters    grad present, not None
GRADIENT    those parameters received real derivatives  None / zero / finite
OWNERSHIP   the optimizer holds those exact objects     two-way id() audit
UPDATE      those exact objects moved                   snapshot and delta
CAPABILITY  repeated controlled steps fit a tiny batch  real optimizer, no regularization

五故意失败 stress 链的不同部位,但不是同一仪器都发现得了。陈旧 head 归属之前全满足,从不动。detach 层到梯度边界,四期待梯度消失,固定特征表示仍支撑部分学习。打乱目标任务边界挂,然后 competently 优化 nonsense。pre-softmax 目标过通用机械台账,因为可微标量是不是意图目标的判定要目标-specific 检查。离谱学习率也过单步机械台账;失败出现在更新尺度,稍后才非有限值。这个分工就是要点:链告诉你要什么证据,不是通用检查器 certify 每 link。

没有一个抛异常。

学习是可观测后果的链。正确目标产出意图损失;损失到达意图参数;参数收到有限梯度;优化器拥有那些精确对象;步移动它们;重复受控步改变模型行为。找到第一个失败的后果,在那里调。

现在能确立已知样本意思与其目标说的一致,意图目标依赖意图参数,梯度到达它们,优化器拥有那些精确对象,那些对象动了。受控拷贝朴素 SGD 上还能验证更新方程本身。最后重复受控步确立训练系统装得下小 batch。

这些都没说机器用得好不好。训练循环能完全正确而浪费大半 GPU。能装进内存而半数时间等同步。编译后比编译前慢。本章仪器全都注意不到,因为它们全度量对的事发生否,没一度量花了多少。

下一章从证明学会的模型开始,问完全不同的问题:时间去哪了,内存去哪了,设备为什么等?guiding 思想和本章一样简单一样容易跳过:

先测量,再优化,再测量。