nn.Module:PyTorch 认为哪些属于你的模型?
揭开 nn.Module 如何组织已注册参数、缓冲、子模块、state_dict()、设备移动与优化器成员,当模型状态悄悄分歧时,对齐 Python 对象图、已注册树、autograd 图与优化器组。
这里有个第 4 章异或数据集的分类器,按大多数人写 PyTorch 的方式写。它能训。验证精度从瞎猜爬到 95.7%。它存了检查点,检查点加载无警告,然后重载的模型表现回到瞎猜。
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(0)
n = 2000
X = torch.randn(n, 2)
y = ((X[:, 0] > 0) ^ (X[:, 1] > 0)).long()
perm = torch.randperm(n)
X_train, y_train = X[perm[:1600]], y[perm[:1600]]
X_val, y_val = X[perm[1600:]], y[perm[1600:]]
class Encoder(nn.Module):
def __init__(self, width=16, depth=3):
super().__init__()
self.blocks = [nn.Linear(width, width) for _ in range(depth)]
def forward(self, x):
for block in self.blocks:
x = torch.relu(block(x))
return x
class Classifier(nn.Module):
def __init__(self, width=16, depth=3):
super().__init__()
self.stem = nn.Linear(2, width)
self.encoder = Encoder(width, depth)
self.head = nn.Linear(width, 2)
def forward(self, x):
x = torch.relu(self.stem(x))
x = self.encoder(x)
return self.head(x)
model = Classifier()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
for epoch in range(200):
logits = model(X_train)
loss = F.cross_entropy(logits, y_train)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if epoch % 50 == 0 or epoch == 199:
with torch.no_grad():
val_acc = (model(X_val).argmax(1) == y_val).float().mean()
print(f"epoch={epoch:3d} loss={loss.item():.4f} "
f"val_acc={val_acc.item():.3f}")
torch.save(model.state_dict(), "classifier.pt")
reloaded = Classifier()
print(reloaded.load_state_dict(torch.load("classifier.pt", weights_only=True)))
with torch.no_grad():
acc = (reloaded(X_val).argmax(1) == y_val).float().mean()
print(f"reloaded val_acc={acc.item():.3f}")
epoch= 0 loss=0.6964 val_acc=0.512
epoch= 50 loss=0.5930 val_acc=0.810
epoch=100 loss=0.3856 val_acc=0.873
epoch=150 loss=0.2550 val_acc=0.925
epoch=199 loss=0.1908 val_acc=0.957
<All keys matched successfully>
reloaded val_acc=0.512
最后两行合在一起读。PyTorch 报告检查点每个键与模型期待的每个键都匹配,拿回来的模型毫无价值。没抛,没警告。load_state_dict 满意到它的能力极限。
前三章的工具找不出这个。每个形状都对。dtype 设备都对。梯度到达网里每块权重,可以证明。损失单调下降,这是第 1 章教我们要的结果,验证精度跟着涨,这是第 1 章教我们加的检查。第 4 章六个诊断问题——表示、计算、目标、微分、更新、评估——这里都能问。大多数证据看起来健康。计算 work,目标 valid,梯度流动,评估提升。
失败只在换个问题时出现:参与这次计算的张量里,PyTorch 实际把哪些当属于这个模型的 state 管理?
一个数露馅:
print("parameter tensors:", len(list(model.parameters())))
print("parameter count: ", sum(p.numel() for p in model.parameters()))
parameter tensors: 4
parameter count: 82
八十二。第 4 章手建双层网正好八十二参数,而这个模型有五个 nn.Linear 层。其中三层——816 个参数——不在计数里。也不在检查点里,这就是检查点载入如此干净的原因:载入它的模型不觉得自己缺东西。
那三层存在。被构造,每次前向被调用,变换数据,autograd 对它们求导。错的不在模型的数学,而在 PyTorch 与程序员对模型是什么不一致。
第 4 章末尾问过 about 即将见的框架的三个问题:为什么 model.parameters() 找到埋四层深的权重,为什么 model.to("cuda") 搬没点名的张量,为什么放普通 Python 列表的模块从 state_dict() 消失。三个答案其实一个,我们刚看了第三个让训好的模型没了。
答案是递归组合——模块包含模块,框架操作走这个结构——但这样说只是口号,口号活不过调试。让它有用的是精确知道 walk 看得见什么:
PyTorch 把哪些对象看成这个模型的一部分,哪台机器查这个答案,我怎么检查而不是从源码推测?
读完,你应该能读没见过的模型类,预测 named_parameters()、state_dict()、.to(device)、eval() 与优化器各自找到什么——某个找到意外的东西时,知道先检查哪套结构。
四套系统,四个不同答案
修之前先拿证据。第一个问题是框架以为自己握着什么。
for name, module in model.named_modules():
print(f"{name!r:12s} {type(module).__name__}")
'' Classifier
'stem' Linear
'encoder' Encoder
'head' Linear
四模块,网里有七个。Encoder 里三 Linear 缺席。参数也缺席:
for name, p in model.named_parameters():
print(f"{name:12s} {tuple(p.shape)}")
stem.weight (16, 2)
stem.bias (16,)
head.weight (2, 16)
head.bias (2,)
第二个问题,不同的问题:autograd 到得了那些层吗?快照,短训,梯度与值都查。
before = [b.weight.detach().clone() for b in model.encoder.blocks]
optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
for _ in range(50):
loss = F.cross_entropy(model(X_train), y_train)
optimizer.zero_grad()
loss.backward()
optimizer.step()
for i, (old, block) in enumerate(zip(before, model.encoder.blocks)):
moved = (block.weight - old).abs().max().item()
print(f"encoder.blocks[{i}].weight max_change={moved:.6f} "
f"grad_is_none={block.weight.grad is None}")
encoder.blocks[0].weight max_change=0.000000 grad_is_none=False
encoder.blocks[1].weight max_change=0.000000 grad_is_none=False
encoder.blocks[2].weight max_change=0.000000 grad_is_none=False
梯度在。值不动。不是近似,不慢:五十个优化器步最大绝对变化精确零。
这是本章围绕的模式,值得直说,因为它违反大多数人带进 PyTorch 的反射:
梯度只说 autograd 到达了张量。它关于有没有东西去更新它什么都不说。
三套系统对同样三层给了三个不同答案。普通 Python 到得了,因为 self.blocks 是列表,前向 for 循环迭代它。autograd 到得了,因为它们参与了产出损失的计算。模块注册表没有它们,所以 model.parameters() 不返回它们,所以优化器从没拿到它们,所以 optimizer.step() 与它们无关。
那个循环里还藏着第四个症状,值得看,因为它是真资源 bug 而不只是正确性:
for step in range(5):
loss = F.cross_entropy(model(X_train), y_train)
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(f"step={step} "
f"stem.weight.grad_norm={model.stem.weight.grad.norm().item():.4f} "
f"blocks[0].weight.grad_norm="
f"{model.encoder.blocks[0].weight.grad.norm().item():.4f}")
step=0 stem.weight.grad_norm=0.0048 blocks[0].weight.grad_norm=0.0145
step=1 stem.weight.grad_norm=0.0050 blocks[0].weight.grad_norm=0.0287
step=2 stem.weight.grad_norm=0.0054 blocks[0].weight.grad_norm=0.0432
step=3 stem.weight.grad_norm=0.0059 blocks[0].weight.grad_norm=0.0580
step=4 stem.weight.grad_norm=0.0062 blocks[0].weight.grad_norm=0.0734
已注册参数的梯度每轮被 optimizer.zero_grad() 清掉。没注册参数的不被清,每次反向往 .grad 已存的值上再加一份。第 1 章确立 PyTorch 往 .grad 累积梯度、得有东西清;optimizer.zero_grad() 就是那个东西,只能清给它的参数。其余整个运行累积,握着权重同尺寸的梯度缓冲从不用。
这些不是 PyTorch 不一致。每套系统回答了问它的问题。问题是我们 assumed 这些问题答案相同。
self.something = ... 实际做了什么
分歧从赋值开始。nn.Module 重写 __setattr__,模块上的属性赋值不是看起来那个普通 Python 操作。按值的类型去四个地方之一,直接可观察:
class Probe(nn.Module):
def __init__(self):
super().__init__()
self.child = nn.Linear(2, 2)
self.weight = nn.Parameter(torch.zeros(3))
self.plain = torch.zeros(3)
self.register_buffer("running", torch.zeros(3))
self.number = 7
p = Probe()
print("ordinary __dict__:", [k for k in p.__dict__ if not k.startswith("_")])
print("_parameters: ", list(p._parameters))
print("_buffers: ", list(p._buffers))
print("_modules: ", list(p._modules))
ordinary __dict__: ['training', 'plain', 'number']
_parameters: ['weight']
_buffers: ['running']
_modules: ['child']
五次赋值,四个去处。nn.Module 值进 _modules。nn.Parameter 值进 _parameters。缓冲必须显式声明,因为普通张量没法示意意图,经 register_buffer 进 _buffers。其余——包括普通张量,包括恰好装着模块的 Python 列表——像普通 Python 属性落进实例 __dict__。
属性访问安排得让你分不出区别。p.weight 返回 _parameters 里的对象,p.child 返回 _modules 里的,同一对象不是拷贝:
print(p.weight is p._parameters["weight"])
print(p.child is p._modules["child"])
print(p.running is p._buffers["running"])
True
True
True
所以 self.blocks = [nn.Linear(16, 16), ...] 不是失败的注册。它是成功的普通属性赋值。列表存下了,里面模块活着可调用,PyTorch 没理由往 handed 进来的不透明 Python 数据里看。这三个字典是描述模块参数、缓冲与子模块的核心注册表。周围还有别的 bookkeeping,归属问题要紧的就是这些结构。
这个机制的两后果,出乎意料前先知道。
字典在 Module.__init__ 跑之前不存在。 这就是 super().__init__() 不是可选 boilerplate 的原因:
class NoSuper(nn.Module):
def __init__(self):
self.w = nn.Parameter(torch.zeros(3))
NoSuper()
AttributeError: cannot assign parameters before Module.__init__() call
注册按名字粘住。 weight 进 _parameters 后,给该名字赋普通张量被拒绝而不是悄悄降级:
layer = nn.Linear(2, 2)
layer.weight = torch.zeros(2, 2)
TypeError: cannot assign 'torch.FloatTensor' as parameter 'weight'
(torch.nn.Parameter or None expected)
这是有用的 guardrail,注意它多窄。只对已注册的名字触发。全新名字没这种保护,坏模型正是这种情况。
名字是穿过树的路径
三字典只握直属孩子。Classifier._modules 有 encoder;对 encoder 里有什么一无所知。named_parameters() 与 state_dict() 里的点名来自递归 walk,短到能全文写出。
def walk_parameters(module, prefix=""):
for name, param in module._parameters.items():
if param is not None:
yield prefix + name, param
for name, child in module._modules.items():
if child is not None:
yield from walk_parameters(child, prefix + name + ".")
在马上要建的修好模型上跑,与 PyTorch 产出的比对象同一性:
mine = [(n, id(p)) for n, p in walk_parameters(model)]
theirs = [(n, id(p)) for n, p in model.named_parameters()]
for name, _ in mine:
print(name)
print()
print("identical to named_parameters():", mine == theirs)
stem.weight
stem.bias
encoder.blocks.0.weight
encoder.blocks.0.bias
encoder.blocks.1.weight
encoder.blocks.1.bias
encoder.blocks.2.weight
encoder.blocks.2.bias
head.weight
head.bias
identical to named_parameters(): True
这个模型上小 walk 与 named_parameters() 名字相同、观测顺序相同、指向同一参数对象。
别把顺序当契约——PyTorch 真遍历处理重复对象等额外情形。重要的结果是结构性:已注册名字是穿过递归组合模块层级的路径。
一句话解释本章大量意外行为。encoder.blocks.0.weight 不是 PyTorch 发明的标签。它是路线:根上属性 encoder,其上属性 blocks,其上键 0,其上参数 weight。self.encoder 改名 self.backbone,这些名字全变,因为路线变了。层从一容器搬到另一容器,名字变。这就是检查点对重构敏感到出乎意料的原因,稍后回来。
它也解释父类为何不用特殊代码。Classifier 从没提 Linear.weight。它注册 encoder,Encoder 注册 blocks,ModuleList 注册条目,Linear 注册自己的权重偏置。每层只知直属孩子,递归组装剩下。一百个 block 的 Transformer 与这个没有更难;同样 walk,走得远。
四套结构
现在能精确说出四套结构,因为已看三套分歧。
Python 对象图。 普通属性访问到得了的一切:列表、字典、闭包、模块全局量、被别的对象握着的对象。这是 forward() 用的。四套里最大,PyTorch 不遍历它。
已注册模块树。 _modules、_parameters、_buffers 字典,递归走。这是归属声明,全由赋值建成,框架遍历的就是它。
autograd 图。 每次前向从实际执行的算子新建,如第 3 章。它记录这次损失如何依赖哪些张量。它没有模型的概念。
优化器的参数组。 构造时交给特定优化器的张量对象列表,按引用存。它是决定的快照,不是任何东西的 live view。
同一张量可同时参与其中几套,成员关系不必一致。坏模型的三编码器层在第一、三套,在另两套不在。四套分开看,框架不再像规则堆,像遍历堆,每个 API 变成问它走哪套结构:
named_modules() → registered module tree
named_parameters() → registered parameters, found by walking that tree
named_buffers() → registered buffers, found by walking that tree
state_dict() → registered parameters and persistent buffers, keyed by path
model.to(...) → registered parameters and buffers
model.train/eval() → the `training` flag on every registered module
loss.backward() → the autograd graph recorded by this forward pass
optimizer.step() → the tensors in this optimizer's parameter groups
缺东西时 productive 的问题不是“PyTorch 为什么无视我的张量”,而是:
出故障的操作遍历四套里哪套,我的对象在里面吗?
这是本章给诊断方法的增量。第 2 章说找第一个错的张量。第 3 章说找梯度通路第一次消失处。第 4 章说判定六断言里哪个坏。本章说:东西好似消失时,把想要的结构与 PyTorch 实际注册的结构对比,用检查而不是重读源码。
有梯度但不是参数的张量
普通列表 bug 藏整整三层,戏剧但容易当粗心 dismiss。同一机制产出更小更难看的失败。这里有个手写的线性层:
class BrokenLinear(nn.Module):
def __init__(self, in_features, out_features):
super().__init__()
self.weight = torch.randn(out_features, in_features) * 0.5
self.weight.requires_grad_(True)
self.bias = torch.zeros(out_features, requires_grad=True)
def forward(self, x):
return x @ self.weight.T + self.bias
跑之前先预测答案。值得纸上做;实验的价值在发现哪些预测本不该绑一起。
weight.requires_grad ?
weight.is_leaf ?
weight.grad after backward ?
model.named_parameters() ?
model.state_dict() ?
does model.to(...) convert it ?
can an optimizer update it ?
现在跑:
model = BrokenLinear(4, 2)
x = torch.randn(8, 4)
y = torch.randint(0, 2, (8,))
F.cross_entropy(model(x), y).backward()
w = model.weight
print("requires_grad :", w.requires_grad)
print("is_leaf :", w.is_leaf)
print("grad is None :", w.grad is None)
print("grad norm :", round(w.grad.norm().item(), 4))
print("named_parameters:", list(model.named_parameters()))
print("state_dict keys :", list(model.state_dict().keys()))
model.to(torch.float64)
print("dtype after .to :", model.weight.dtype)
requires_grad : True
is_leaf : True
grad is None : False
grad norm : 0.6618
named_parameters: []
state_dict keys : []
dtype after .to : torch.float32
第 3 章在乎的一切完美。weight 是叶,需要梯度,backward() 填了有限 .grad,前向算术对。本章在乎的一切空。模型无参数,存空,不转换。
七个预测的最后一个产出这个例子唯一的响亮失败:
torch.optim.SGD(model.parameters(), lr=0.1)
ValueError: optimizer got an empty parameter list
值得停一下。PyTorch 检查,也抱怨——但只对零已注册参数的模型。开篇 Classifier 有四个,检查过,悄悄跑。响亮失败是幸运情形。这个 bug 危险的版本永远是部分的那个。
nn.Parameter 是声明,不是张量口味
修复是两处各一词:
class ManualLinear(nn.Module):
def __init__(self, in_features, out_features):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_features, in_features) * 0.5)
self.bias = nn.Parameter(torch.zeros(out_features))
def forward(self, x):
return x @ self.weight.T + self.bias
同样探针,外加两条以前不值得跑的:
type : Parameter
requires_grad : True
is_leaf : True
grad is None : False
named_parameters: ['weight', 'bias']
state_dict keys : ['weight', 'bias']
dtype after .to : torch.float64
optimizer holds : 2 tensors
前四行与坏版本相同。这就是要点。nn.Parameter 没让张量可微——本来就可微。没让它是叶——本来就是。变的是赋值落进哪个字典,因而递归 walk 找得到什么。
这就是常见 gloss 值得拒绝的原因:
nn.Parameteris a tensor withrequires_grad=True.
两方向都错。第 3 章给了 plenty 带 requires_grad=True 却不属于任何东西的张量。而参数不必需要梯度:
class Frozen(nn.Module):
def __init__(self):
super().__init__()
self.w = nn.Parameter(torch.ones(3), requires_grad=False)
f = Frozen()
print("registered :", [n for n, _ in f.named_parameters()])
print("requires_grad:", f.w.requires_grad)
print("in state_dict:", list(f.state_dict().keys()))
registered : ['w']
requires_grad: False
in state_dict: ['w']
autograd 不跟踪的已注册参数。完全在模型里,完全在检查点里,跟着模型跨设备,收不到梯度。接受注册与梯度跟踪回答不同问题,就不矛盾:
assign nn.Parameter to a Module attribute
→ "register this object as a parameter of this module"
requires_grad
→ "record differentiable operations involving this tensor when grad mode permits it"
第一行有更锋利的版本。是 nn.Parameter 不是让张量属于模型的属性;注册是对象与特定模块的关系。坏 Classifier 里 model.encoder.blocks[0].weight 是真 nn.Parameter——nn.Linear 这样建的——注册在拥有它的 Linear 上。只是 walk 从 model 到不了,因为 Linear 自己从没注册到 Encoder。问“这是 nn.Parameter 吗”回答不了“它在 model.parameters() 里吗”。得问模型。
修模型与修生效的证据
回到开篇。三编码器层要注册成 Encoder 的孩子,装它们的容器要 PyTorch 遍历的。改一行:
class Encoder(nn.Module):
def __init__(self, width=16, depth=3):
super().__init__()
self.blocks = nn.ModuleList(
[nn.Linear(width, width) for _ in range(depth)]
)
def forward(self, x):
for block in self.blocks:
x = torch.relu(block(x))
return x
forward 不动。算术不动。初始化同样种子同样数。现在跑同样脚本,比同样测量。
'' Classifier
'stem' Linear
'encoder' Encoder
'encoder.blocks' ModuleList
'encoder.blocks.0' Linear
'encoder.blocks.1' Linear
'encoder.blocks.2' Linear
'head' Linear
parameter tensors: 10
parameter count: 898
epoch= 0 loss=0.6964 val_acc=0.512
epoch= 50 loss=0.0185 val_acc=0.995
epoch=100 loss=0.0081 val_acc=0.995
epoch=150 loss=0.0059 val_acc=0.995
epoch=199 loss=0.0033 val_acc=0.995
<All keys matched successfully>
reloaded val_acc=0.995
两跑并排:
| measurement | plain list | nn.ModuleList |
|---|---|---|
| registered modules | 4 | 8 |
len(list(model.parameters())) |
4 | 10 |
| parameter count | 82 | 898 |
state_dict() keys |
4 | 10 |
| epoch 0 loss | 0.6964 | 0.6964 |
| final validation accuracy | 0.957 | 0.995 |
| accuracy after save and reload | 0.512 | 0.995 |
epoch-0 行值得 dwell。损失相同到四位小数,因为两程序在同样数上做完全同样的计算。两列全部区别是框架被告知了什么。
终精度行是陷阱。坏模型到 95.7%, respectable 的数,监控 dashboard 不 flag。它到那因为 stem 与 head 可训练、冻结随机中层当固定非线性特征映射——合法模型,只是不是写下的那个。失败只在模型要活着离开进程时可见。
末行是这类 bug 值得一章的原因。检查点没坏。它忠实记录 PyTorch 以为模型有的每块 state。
Python 到得了不等于 PyTorch 注册了。参与计算不等于当模型 state 管理。
这是本章版的第 2 章规则:合法不等于正确,形状一样:程序跑,产出数,意思不是你想的。
ModuleList 是什么,不是什么
nn.ModuleList 是注册放进去的模块、用位置当名字的模块。工作就这些,两条多 assumed 的值得精确说。
它不定义计算:
layers = nn.ModuleList([nn.Linear(2, 2), nn.Linear(2, 2)])
layers(torch.randn(1, 2))
NotImplementedError: Module [ModuleList] is missing the required "forward" function
你的 forward 仍决定怎么调、调不调、什么顺序、调几次。可以倒着调、调一个两次、按输入跳过、一个从不调——注册不变。
这正是与 nn.Sequential 有用的对比,后者也注册孩子,外加定义按序调用的前向算。
这个简单例子两容器产出同样已注册孩子名:
print("ModuleList:", [n for n, _ in nn.ModuleList([nn.Linear(2,2), nn.Linear(2,2)]).named_modules()])
print("Sequential:", [n for n, _ in nn.Sequential(nn.Linear(2,2), nn.Linear(2,2)).named_modules()])
ModuleList: ['', '0', '1']
Sequential: ['', '0', '1']
同样名字,同样注册,同样检查点键。计算真是“按序施加”选 Sequential;forward 要对它们做别的选 ModuleList。要字符串键或裸参数有 nn.ModuleDict、nn.ParameterList、nn.ParameterDict,同样注册。
第二个值得拆的假设是普通 Python 容器被禁。没有。当模块只经未注册容器到得了才坏。这个没事:
class Both(nn.Module):
def __init__(self):
super().__init__()
self.a = nn.Linear(2, 2)
self.b = nn.Linear(2, 2)
self.order = [self.a, self.b] # plain list, contents registered by name
def forward(self, x):
for layer in self.order:
x = layer(x)
return x
['a.weight', 'a.bias', 'b.weight', 'b.bias']
两层都注册,因为它们被赋到属性。列表是同一对象的第二未注册视图,只管顺序。什么都没丢。规则关于 walk 到得了,不是允许用什么 Python 类型。
缓冲:不是参数的模型 state
模块拥有的不都该训练。运行统计、固定掩码、归一化常数、预计算表、计数器可以属于模型而不 trainable。它们可能要跟着模块走,可能要进存档,但不该经 model.parameters() 发现。
已注册缓冲就是这个关系。
class Normalize(nn.Module):
def __init__(self, features):
super().__init__()
self.register_buffer("mean", torch.zeros(features))
self.scale = torch.ones(features) # ordinary attribute
self.gain = nn.Parameter(torch.ones(features))
def forward(self, x):
return (x - self.mean) * self.scale * self.gain
三张量,与模块三种关系:
named_parameters: ['gain']
named_buffers : ['mean']
state_dict keys : ['gain', 'mean']
scale 三个里都没出现。前向里完美 work,因为前向用 Python 对象图,其余一切不可见。
三路区分值得精确握住,因为每行是不同答案集而不是不同张量种类:
in parameters() |
in buffers() |
in state_dict() |
converted by .to() |
given to an optimizer | |
|---|---|---|---|---|---|
| registered parameter | yes | no | yes | yes | if you pass it |
| persistent buffer | no | yes | yes | yes | not via model.parameters() |
| non-persistent buffer | no | yes | no | yes | not via model.parameters() |
| ordinary tensor attribute | no | no | no | no | no |
表里两条常被夸大,窄说。缓冲不是“不能有梯度的张量”——它是模块拥有、不是参数的 state,用 autograd 行为定义它搞错概念。而“converted by .to()”干的活比看起来多;见下。
为什么 model.to(device) 搬东西,落下什么
model.to(...) 不在对象图里搜张量。它走已注册参数与缓冲,和 named_parameters() 一模一样,逐个转换。walk 外的东西留在原地。
不用 GPU 也看得见。PyTorch 有 meta 设备,只握形状 dtype 不握数据——正为这种结构问题而生,每台机器都有:
m = Normalize(4)
m.to("meta")
print("gain :", m.gain.device)
print("mean :", m.mean.device)
print("scale:", m.scale.device)
m(torch.randn(2, 4, device="meta"))
gain : meta
mean : meta
scale: cpu
RuntimeError: Tensor on device cpu is not on the expected device meta!
参数搬了。缓冲搬了。普通属性没搬,前向在 mismatch 上挂。真 GPU 上同样结构产出大概见过的报错:
RuntimeError: Expected all tensors to be on the same device,
but found at least two devices, cuda:0 and cpu!
本能修复是在失败行加 .to(x.device)。错会消失,下个用 scale 的行回来,一直回来直到每个 use site 打补丁。结构问题更好:
错设备的张量在已注册 state 树外吗,如果是,它该在里面吗?
真是模型 state,register_buffer 放进 walk,问题不再复发。是输入派生的临时量,前向里从输入建,别存模块上。
to() 在模块上有两细节值得知道,因为与张量上的 to() 不同。
它原地改并返回自己。 第 2 章确立 tensor.to(...) 返回新张量、原件不动。模块转换每个已注册参数与缓冲握的数据,不替换 Parameter 对象:
layer = nn.Linear(2, 2)
w = layer.weight
print("returns self:", layer.to(torch.float64) is layer)
print("same object :", layer.weight is w, "| dtype:", layer.weight.dtype)
returns self: True
same object : True | dtype: torch.float64
对象同一性 load-bearing。优化器握参数对象引用,先建优化器后 model.to("cuda") 仍握对的。(优化器 state——动量缓冲之类——第一次用才 lazy 建,第一次 step 前搬模型就不用问它住哪。)
显式 dtype 转换作用于浮点与复数 state,整数 state 保持 dtype。 .to(torch.float64) 不把整数计数器与布尔掩码变成浮点:
layer.register_buffer("counter", torch.zeros(3, dtype=torch.long))
layer.to(torch.float64)
print(layer.weight.dtype, layer.counter.dtype)
torch.float64 torch.int64
设备移动作用于全部;dtype 转换有选择。这就是想要的行为,值得知道它是故意的,而不是 assumed 每个缓冲跟每次转换。
持久与非持久缓冲
注册回答“这属于模块吗”。第二个独立问题是“这进检查点吗”。大多数 state 两答案一致。有时不一致,persistent=False 就是这么说的。
最清楚的是配置完全决定的 state:
class Block(nn.Module):
def __init__(self, dim, max_len):
super().__init__()
self.proj = nn.Linear(dim, dim)
self.register_buffer(
"causal_mask",
torch.tril(torch.ones(max_len, max_len, dtype=torch.bool)),
persistent=False,
)
self.register_buffer("calls_seen", torch.zeros((), dtype=torch.long))
named_buffers : ['causal_mask', 'calls_seen']
state_dict keys : ['calls_seen', 'proj.weight', 'proj.bias']
掩码已注册,随大伙上 GPU,不用为它写设备转移。不进检查点,因为它没 learned 信息:torch.tril(torch.ones(...)) 从 max_len 精确重建,每次都行。存它让每个检查点大 max_len × max_len 数组,更糟把训练时序列长 bake 进文件,载入不同长度配置的模型变成形状错,而这个值本可重算。
计数器持久,因为模块见过多少 batch 从配置恢复不了。区分——从配置可重算 vs 从数据累积——通常是对的测试。
观测顺序也反映这个例子的递归遍历,但别让正确性依赖 state-dict 顺序。键与路径在这里是有用的契约。
state_dict() 就是 keyed by path 的树
现在能精确说模型 state_dict 装什么。它不序列化模型的 Python 结构,不收集任意 Python 属性。它装模块已注册参数与持久缓冲的引用,按穿过已注册树的路径 keyed。
完整训练检查点可能装更多——比如优化器 state、调度器 state、计数器或元数据——但模型部分通常就是这个 state dict。
人们觉得检查点神秘的一切都从这句跟出。state 不注册键消失。state 开始注册键意外出现。路径变键改名——路径变的原因在源码里看起来纯 cosmetic。
这里有两个模型,差一个属性名:
class V1(nn.Module):
def __init__(self, w=16, d=2):
super().__init__()
self.stem = nn.Linear(2, w)
self.blocks = nn.ModuleList([nn.Linear(w, w) for _ in range(d)])
self.head = nn.Linear(w, 2)
class V2(nn.Module): # after a rename
def __init__(self, w=16, d=2):
super().__init__()
self.stem = nn.Linear(2, w)
self.encoder = nn.ModuleList([nn.Linear(w, w) for _ in range(d)])
self.head = nn.Linear(w, 2)
不载入读 traceback,直接比键集。这是第 2 章形状跟踪的同样动作:期待对实际排齐,找第一次分手处。
checkpoint = V1().state_dict()
model = V2()
have = list(checkpoint.keys())
want = list(model.state_dict().keys())
for a, b in zip(have, want):
print(f"{a:24s} {b:24s} {'' if a == b else '<-'}")
print()
print("missing from checkpoint :", sorted(set(want) - set(have)))
print("unexpected in checkpoint:", sorted(set(have) - set(want)))
stem.weight stem.weight
stem.bias stem.bias
blocks.0.weight encoder.0.weight <-
blocks.0.bias encoder.0.bias <-
blocks.1.weight encoder.1.weight <-
blocks.1.bias encoder.1.bias <-
head.weight head.weight
head.bias head.bias
missing from checkpoint : ['encoder.0.bias', 'encoder.0.weight',
'encoder.1.bias', 'encoder.1.weight']
unexpected in checkpoint: ['blocks.0.bias', 'blocks.0.weight',
'blocks.1.bias', 'blocks.1.weight']
两集合同样大小、同样形状、同样顺序,恰在一个路径 component 分歧。load_state_dict 用 less structured 形式报告同样的事:
RuntimeError: Error(s) in loading state_dict for V2:
Missing key(s) in state_dict: "encoder.0.weight", "encoder.0.bias", ...
Unexpected key(s) in state_dict: "blocks.0.weight", "blocks.0.bias", ...
当 diff 读修复 obvious:属性改回去,或 remap 键,看哪边 authoritative。诱人的替代 obviously 错。strict=False 不修任何东西;它把错降级成返回值:
print(model.load_state_dict(checkpoint, strict=False))
_IncompatibleKeys(missing_keys=['encoder.0.weight', 'encoder.0.bias', ...],
unexpected_keys=['blocks.0.weight', 'blocks.0.bias', ...])
两编码器层——四参数张量,每层权重偏置——留在新模型的初始化,即使你以为从检查点载了它们——正是本章开篇的失败,换条路线到达。strict=False 在你打算部分载入、说得出哪些键该缺、为什么时是合法工具。拿它让信息消失,是把响亮失败变成静默失败。
state_dict() 还有条性质跟出机制并坑人。默认 state_dict() 返回的张量与 autograd detach,但 state dict 是模块当前 state 引用的浅快照而不是克隆的参数数据:
layer = nn.Linear(3, 2)
sd = layer.state_dict()
print("is the Parameter object:", sd["weight"] is layer.weight)
print("shares storage :", sd["weight"].data_ptr() == layer.weight.data_ptr())
is the Parameter object: False
shares storage : True
所以常见 early-stopping 写法做的不是看起来那个:
best_state = model.state_dict() # shallow state references
best_state = copy.deepcopy(model.state_dict()) # independent in-memory snapshot
torch.save 不受影响,因为它立刻序列化。内存里握着 state_dict 跨更多优化器步才咬:“最优”权重跟着当前走,最后恢复的是最后一个,不是最好那个。
eval() 不是 no_grad()
两设置常被搞混,部分因为通常一起用。它们控不同机制,独立。最干净的看法是两都变,看两样不同的东西变。
torch.manual_seed(0)
model = nn.Sequential(
nn.Linear(8, 8),
nn.Dropout(0.5),
nn.Linear(8, 2),
)
x = torch.randn(4, 8)
def probe(label, out, m):
grad_fn = type(out.grad_fn).__name__ if out.grad_fn is not None else "None"
print(f"{label:22s} training={str(m.training):5s} "
f"requires_grad={str(out.requires_grad):5s} "
f"grad_fn={grad_fn:16s} out[0,0]={out[0, 0].item(): .4f}")
model.train()
torch.manual_seed(1); probe("train()", model(x), model)
model.eval()
torch.manual_seed(1); probe("eval()", model(x), model)
model.train()
with torch.no_grad():
torch.manual_seed(1); probe("train() + no_grad()", model(x), model)
model.eval()
with torch.no_grad():
torch.manual_seed(1); probe("eval() + no_grad()", model(x), model)
train() training=True requires_grad=True grad_fn=AddmmBackward0 out[0,0]=-1.2312
eval() training=False requires_grad=True grad_fn=AddmmBackward0 out[0,0]=-0.3193
train() + no_grad() training=True requires_grad=False grad_fn=None out[0,0]=-1.2312
eval() + no_grad() training=False requires_grad=False grad_fn=None out[0,0]=-0.3193
当两独立列读。eval() 改了输出值,requires_grad 与 grad_fn 不动。no_grad() 改了 requires_grad 与 grad_fn,输出值到末位不动。
train()/eval()给每个已注册模块置布尔training。前向行为依赖它的模块——dropout、batch norm、读self.training的手写东西——改变算什么。autograd 不参与。torch.no_grad()告诉 autograd 别记录。模块行为什么都不变;同样算术跑出同样数,只是之后无图。
调 model.eval() 指望梯度跟踪停,是真常见错。反过来也一样。反过来用 batch norm 看,它的运行统计是训练模式前向写的缓冲:
bn = nn.BatchNorm1d(4)
x = torch.randn(32, 4) * 3 + 5
print("initial :", bn.running_mean)
with torch.no_grad():
bn(x)
print("no_grad, train() :", bn.running_mean)
bn.eval()
with torch.no_grad():
bn(x)
print("no_grad, eval() :", bn.running_mean)
initial : tensor([0., 0., 0., 0.])
no_grad, train() : tensor([0.4401, 0.5089, 0.5627, 0.5513])
no_grad, eval() : tensor([0.4401, 0.5089, 0.5627, 0.5513])
torch.no_grad() 没保护缓冲。验证跑在仍训练模式的模型上,用验证数据改它的运行统计——模型 state 的静默 corruption,梯度工具抓不住,稍后变成没人解释得了的 train/eval 分歧。防它的是 eval()。
flag 经已注册树传播,只到 walk 到得了的模块,开篇 bug 在这里还有最后一蜇:
class M(nn.Module):
def __init__(self):
super().__init__()
self.registered = nn.Dropout(0.5)
self.hidden = [nn.Dropout(0.5)]
m = M()
m.eval()
print("registered dropout .training:", m.registered.training)
print("hidden dropout .training :", m.hidden[0].training)
registered dropout .training: False
hidden dropout .training : True
只在普通列表的 dropout 层,注册模型切评估模式时留在训练模式。它的验证输出保持随机,不代表程序员想要的评估行为——周围训练循环还不一定看起来错。
冻结与决定参数动不动的三集合
冻结是看起来像一个的两个属性最清楚的情形:
model = nn.Sequential(nn.Linear(4, 4), nn.ReLU(), nn.Linear(4, 2))
for p in model[0].parameters():
p.requires_grad_(False)
for name, p in model.named_parameters():
print(f"{name:10s} requires_grad={p.requires_grad}")
print("state_dict keys:", list(model.state_dict().keys()))
F.cross_entropy(model(torch.randn(16, 4)), torch.randint(0, 2, (16,))).backward()
for name, p in model.named_parameters():
print(f"{name:10s} grad={'None' if p.grad is None else 'present'}")
0.weight requires_grad=False
0.bias requires_grad=False
2.weight requires_grad=True
2.bias requires_grad=True
state_dict keys: ['0.weight', '0.bias', '2.weight', '2.bias']
0.weight grad=None
0.bias grad=None
2.weight grad=present
2.bias grad=present
冻结参数仍注册,仍在 named_parameters(),仍在检查点,仍跟着模型跨设备。requires_grad_(False) 改了它与 autograd 的关系,没改注册。它们仍是模型参数,仍在 state dict,继续随模块走,只是普通反向不再往里累积梯度。这正是冻结预训练 backbone 想要的——权重是模型的一部分,必须存、必须搬;只是不必更新。
本书常规工作流有三个独立成员问题值得查:
REGISTERED MODEL PARAMETERS model.parameters() 模块树暴露出来发现的东西。
AUTOGRAD-REACHED TENSORS 这次计算收到梯度的张量。
THIS OPTIMIZER’S PARAMETERS 这个优化器实际拿到的张量对象。
别把这个图变成“注册是优化器改张量的必要条件”的数学规则。优化器能直接拿不属于任何模块的张量。
普通 torch.optim 训练,直接的更新问题更窄:
- 这个精确张量对象在优化器的某参数组里吗?
- 它的
.grad当前什么 state? - 按这个优化器的规则与 state,step 该改它吗?
None 梯度一般让 PyTorch 优化器整个跳过该张量,显式零梯度行为可能不同,因为动量、weight decay 或别的优化器 state 还在。
第 4 章把微分与更新分成六问之二。这里变成机械:优化器不是模型的 live view。它是构造时捕获的张量对象列表,忠实更新那些,别的一概不管。
x = torch.randn(32, 4)
y = torch.randint(0, 2, (32,))
model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 2))
optimizer = torch.optim.SGD(model[2].parameters(), lr=0.5) # head only
before = {n: p.detach().clone() for n, p in model.named_parameters()}
for _ in range(20):
loss = F.cross_entropy(model(x), y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
held = {id(p) for g in optimizer.param_groups for p in g["params"]}
for name, p in model.named_parameters():
print(f"{name:10s} grad={'yes' if p.grad is not None else 'no':3s} "
f"in_optimizer={str(id(p) in held):5s} "
f"moved={(p - before[name]).abs().max().item():.6f}")
0.weight grad=yes in_optimizer=False moved=0.000000
0.bias grad=yes in_optimizer=False moved=0.000000
2.weight grad=yes in_optimizer=True moved=0.163894
2.bias grad=yes in_optimizer=True moved=0.200340
已注册,有微分,梯度在,完全静止。只看梯度这个模型看起来健康。
故意传子集是正常事——微调 head,不同组不同学习率。意外版容易产出,因为重构可能根本没碰优化器:
model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 2))
optimizer = torch.optim.SGD(model.parameters(), lr=0.5)
model[2] = nn.Linear(8, 2) # swap the head after the optimizer exists
held = {id(p) for g in optimizer.param_groups for p in g["params"]}
for name, p in model.named_parameters():
print(f" {name:10s} in_optimizer={id(p) in held}")
0.weight in_optimizer=True
0.bias in_optimizer=True
2.weight in_optimizer=False
2.bias in_optimizer=False
新 head 正确注册在模型上。named_parameters() 列它,state_dict() 存它,.to() 搬它。优化器仍握旧 head 的参数对象,现在从模型到不了它们。
这不意味着那些陈旧对象会继续变。旧 head 不再参与前向,通常收不到新梯度;.grad is None 时标准 PyTorch 优化器跳过它。重要的失败是反方向:新 head 收到梯度但不在优化器里,所以从不 step。
两结构各自一致。只是装着不同的参数对象。
成员按对象同一性,不按名字不按值,这就是 id(p) in held 才是回答问题的检查的原因。也是 model.parameters() 先去重共享张量再交出去的原因——优化器有权抱怨同一张量出现两次:
ValueError: some parameters appear in more than one parameter group
模块树不是前向图
最后一区分,它让树对真实结构可理解。注册说模型拥有什么。前向说它做什么。两者互相约束很少。
注册一次的模块能执行任意多次:
class Recurrentish(nn.Module):
def __init__(self, dim):
super().__init__()
self.cell = nn.Linear(dim, dim)
def forward(self, x, steps=3):
for _ in range(steps):
x = torch.tanh(self.cell(x))
return x
modules: ['', 'cell']
params : ['cell.weight', 'cell.bias']
cell.weight.grad norm: 2.5847
一注册模块,一权重,一偏置——autograd 图里三次应用,梯度像第 3 章重复叶例子那样累积进同一权重。这就是循环、权重绑定、Transformer 共享部件背后的机制。已注册树与某次前向调模块几次独立。计算图里同一注册孩子可用一次、十次、零次。
模块树本身不是 immutable——赋值替换模块能改它,head 替换例子已说明。重要的是执行 forward() 不会因为模块又被调一次就再注册一份。
反过来是两名字注册一模块:
class Shared(nn.Module):
def __init__(self, dim):
super().__init__()
self.a = nn.Linear(dim, dim)
self.b = self.a # same object, second name
s = Shared(4)
print("named_modules :", [n for n, _ in s.named_modules()])
print("named_parameters:", [n for n, _ in s.named_parameters()])
print(" remove_duplicate=False:",
[n for n, _ in s.named_parameters(remove_duplicate=False)])
print("state_dict keys :", list(s.state_dict().keys()))
print("a.weight is b.weight:", s.a.weight is s.b.weight)
named_modules : ['', 'a']
named_parameters: ['a.weight', 'a.bias']
remove_duplicate=False: ['a.weight', 'a.bias', 'b.weight', 'b.bias']
state_dict keys : ['a.weight', 'a.bias', 'b.weight', 'b.bias']
同一对象三种答案,各对各自用途都对。named_modules() 与 named_parameters() 去重,因为数参数建优化器时每个张量要一次。state_dict() 不去重,因为它是从每条路径到该路径 state 的映射;两键都在,指向同一存储。语言模型的 tied 嵌入输出层正是这个,下次检查点好似有 duplicate 时记得。
结构审计
模型做出解释不了的事时,打印 PyTorch 有的东西,而不是推理源码暗示什么。两短函数覆盖大半。
第一个报告已注册 state,每张量一行,列区分一直在分的集合:
def registered_report(model, optimizer=None):
held = set()
if optimizer is not None:
held = {id(p) for g in optimizer.param_groups for p in g["params"]}
state = set(model.state_dict().keys())
print(f"{'name':26s} {'kind':7s} {'device':7s} "
f"{'req_grad':9s} {'grad':5s} {'state':6s} {'optim':5s}")
for name, t in list(model.named_parameters()) + list(model.named_buffers()):
kind = "param" if isinstance(t, nn.Parameter) else "buffer"
print(f"{name:26s} {kind:7s} {str(t.device):7s} {str(t.requires_grad):9s} "
f"{('yes' if t.grad is not None else 'no'):5s} "
f"{('yes' if name in state else 'NO'):6s} "
f"{('yes' if id(t) in held else 'no'):5s}")
第二个审计在普通属性里找经已注册树到不了的张量与模块。它故意浅——进常见 Python 容器一层——当实用诊断用,不当任意 Python 对象图的完整遍历。
def unregistered_report(model):
registered_modules = {id(m) for m in model.modules()}
registered_tensors = {id(t) for t in model.parameters()}
registered_tensors.update(id(t) for t in model.buffers())
for mod_name, module in model.named_modules():
prefix = mod_name + "." if mod_name else ""
for attr, value in vars(module).items():
if attr.startswith("_"):
continue
if isinstance(value, dict):
candidates = [(f"{attr}[{k!r}]", v) for k, v in value.items()]
elif isinstance(value, (list, tuple)):
candidates = [(f"{attr}[{i}]", v) for i, v in enumerate(value)]
else:
candidates = [(attr, value)]
for label, item in candidates:
path = prefix + label
if isinstance(item, nn.Module):
if id(item) not in registered_modules:
print(f"{path:26s} {type(item).__name__}")
elif isinstance(item, torch.Tensor):
if id(item) not in registered_tensors:
print(f"{path:26s} {type(item).__name__}")
vars(module) 是实例 __dict__——赋值实验的第四个去处。跳过下划线开头键去掉 _parameters、_buffers、_modules,剩的正好是普通 Python 属性,报告其中握张量或模块的,包括列表、元组、字典一层。
在集本章所有错误于一身的模型上跑两份:
class Classifier(nn.Module):
def __init__(self, width=16, depth=3):
super().__init__()
self.stem = nn.Linear(2, width)
self.encoder = Encoder(width, depth) # plain-list version
self.head = nn.Linear(width, 2)
self.scale = torch.ones(width)
self.register_buffer("calls", torch.zeros((), dtype=torch.long))
def forward(self, x):
self.calls += 1
return self.head(self.encoder(torch.relu(self.stem(x)) * self.scale))
model = Classifier()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
F.cross_entropy(model(torch.randn(8, 2)), torch.randint(0, 2, (8,))).backward()
registered_report(model, optimizer)
print("\nreachable but unregistered:")
unregistered_report(model)
name kind device req_grad grad state optim
stem.weight param cpu True yes yes yes
stem.bias param cpu True yes yes yes
head.weight param cpu True yes yes yes
head.bias param cpu True yes yes yes
calls buffer cpu False no yes no
reachable but unregistered:
scale Tensor
encoder.blocks[0] Linear
encoder.blocks[1] Linear
encoder.blocks[2] Linear
九行开头就能结束调查。第一表是已注册 state,每张量当前有没有梯度、在不在模型 state dict、优化器握的是不是这个精确对象。
这些事实让我们不把训练、保存、移动塌成一个问题地推理训练、保存与移动。第二表是每次前向都参与、哪张表都不在的四个对象。
不用非用这两个 exact 函数。重要的是模型出乎意料时,最快路径通常是打印 named_modules()、named_parameters()、named_buffers() 与 state_dict() 键,外加检查优化器实际握着什么——再调学习率、加 .to(device)、用 strict=False 之前。
在注册问题上用 AI
注册 bug 不适合人们常用问助手的方式,因为模型能跑。没有 traceback 可贴,代码看起来 idiomatic,“我的层不训”招来关于学习率、初始化或归一化的 plausible 自信答案。那些甚至可能让模型略好,比没帮忙更糟。
本书规则这里尤其适用:先要可检查的断言与判别测量,再要重写的代码。productive 的 prompt 点名结构并禁掉修复:
Here is a PyTorch model. One tensor participates in the forward pass but does
not appear to be training. Do not rewrite the model and do not suggest a fix yet.
Give me the smallest piece of inspection code that separately answers each of
these, and tell me what result would indicate a problem:
1. Can ordinary Python reach the tensor from the model object?
2. Is it an nn.Parameter, a registered buffer, or an ordinary attribute?
3. Does it appear in model.named_parameters() or model.named_buffers()?
4. Does it appear in model.state_dict(), and under what key?
5. Does it participate in the computation that produced this loss?
6. Does it have a .grad after backward(), and is that grad finite?
7. Is its exact object identity present in this optimizer's parameter groups?
8. Does its value change across one optimizer.step()?
9. Will model.to(device) convert it?
Then tell me which of those boundaries the evidence says is broken, and only
then propose the smallest change that would fix that specific boundary.
编号列表在做真活。它迫使助手把听起来像一个的问题当九个,这是本章手工一直在施的纪律。答案也短到自己能验证,重要,因为助手和任何人一样能不检查就断言张量已注册。
单对象的检查小到装进脑子。对任何点名的张量:
type : Parameter
registered param: []
registered buffer: []
in state_dict : []
requires_grad : True
grad : 0.0363
in optimizer : False
device : cpu
前两行合读就是整章的缩影。它是 nn.Parameter。它不是这个模型的参数。注册是关系,成立否只能问模型,不能问张量。
注意 state-dict 成员从已注册路径派生,而不是张量对象同一性。state_dict() 装 detach 的 state 条目而不是原来 Parameter 对象,模型的已注册名字是连接归属与序列化 state 更有用的桥。
东西好似看不见时
收成流程,按每步排除最多可能的顺序:
- 打印已注册结构。
named_modules()、named_parameters()、named_buffers()与state_dict()键。与想要的结构对比。大多数注册 bug 只在这里可见。 - 认出对象种类。 已注册孩子模块、已注册参数、已注册缓冲、普通 Python 属性。如果是最后一种,问它该不该是,该是另三种里哪个。
- 找容器。 模块缺失,检查它是否只在普通列表、元组或字典里。
unregistered_report找这些;心里装四个去处读__init__也找得到。 - 分开梯度问题与更新问题。 梯度只说 autograd 到达张量。下训练结论前先拿
id(p)对优化器参数组。 - 检查参数真动了。
detach().clone()快照,step,diff。这是更新的唯一直接证据,第 4 章第五问。 - 设备错先问注册再加转移。 张量在已注册树外,
.to(device)本来就搬不动它,补一个 use site 拦不住下一个。 - 检查点错 diff 键集。 找到第一次分歧的路径 component。说得出哪些键该缺、为什么,才用
strict=False。 - train/eval 分歧检查在乎的模块的
module.training。 打印 flag,别信model.eval()到了一切;它到已注册模块。
八条底下的习惯:
检查 PyTorch 看到的结构,而不是从源码推测。
你现在应该能回答什么
这里有会被递到手里的模型:小编码器上 bolt 适配器、冻结归一化层、门、位置缓冲、被人重初始化的 head。它能跑。先自己走一遍再看答案。
class Adapter(nn.Module):
def __init__(self, dim):
super().__init__()
self.down = nn.Linear(dim, dim // 4)
self.up = nn.Linear(dim // 4, dim)
class Model(nn.Module):
def __init__(self, dim=32, depth=2):
super().__init__()
self.embed = nn.Linear(8, dim)
self.adapters = [Adapter(dim) for _ in range(depth)]
self.gate = torch.ones(dim, requires_grad=True)
self.register_buffer("positions", torch.arange(dim).float(),
persistent=False)
self.norm = nn.LayerNorm(dim)
self.head = nn.Linear(dim, 4)
def forward(self, x):
x = self.embed(x) + self.positions
for a in self.adapters:
x = x + a.up(torch.relu(a.down(x)))
return self.head(self.norm(x) * self.gate)
model = Model()
for p in model.norm.parameters():
p.requires_grad_(False)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
model.head = nn.Linear(32, 4) # re-initialize the head
model.parameters() 返回多少参数张量,多少个数? 当前返回六张量 484 个数:embed.weight、embed.bias、norm.weight、norm.bias、head.weight、head.bias。
模型意图的参数类 state 共 1,620 个数,两适配器与门算上。但不全当前可训练:64 个 LayerNorm 值 requires_grad=False。
所以:
registered parameter values: 484 parameter-like values intended by the model: 1,620 values currently requiring gradients: 1,556
两适配器占 1,104 个值,gate 另 32 个,坏版本里 model.parameters() 都发现不了。
适配器为什么缺席? 在普通 Python 列表里,所以是 Model 的普通属性,从没进 _modules。forward 经列表到得了它们,计算才对。建 named_parameters() 的遍历看不见它们。
gate 为什么缺席? 是普通张量,不是 nn.Parameter,赋值落进实例 __dict__。requires_grad=True 让它可微,没让它成参数。
反向后哪些张量收到梯度?可训练的 embed 与当前 head 参数、gate、每个适配器权重偏置。不包括冻结的 norm.weight、norm.bias。注意收到梯度的集合与 parameters() 返回的集合交叠而不互相包含。
训练中哪些参数真变? 只有 embed.weight 与 embed.bias。跑十步 diff:
embed.weight req_grad=True grad=yes optim=True moved=0.010044
embed.bias req_grad=True grad=yes optim=True moved=0.010110
norm.weight req_grad=False grad=no optim=True moved=0.000000
norm.bias req_grad=False grad=no optim=True moved=0.000000
head.weight req_grad=True grad=yes optim=False moved=0.000000
head.bias req_grad=True grad=yes optim=False moved=0.000000
三零三种原因。norm 在优化器里无梯度,因为冻结。head 有梯度不在优化器里,因为优化器握着被替换掉的 head 的参数对象。适配器与 gate 根本不在表里。
优化器从 model.parameters() 建的,head 为什么不在优化器里? 因为优化器早一行建。model.head = nn.Linear(32, 4) 在模型上注册了新参数对象,优化器继续握旧的引用。
新 head 参与前向并收到梯度,但不在优化器里,所以从不 step。旧 head 留在优化器里但不再参与计算,梯度通常 None,标准优化器跳过它。
两结构各自一致。只是装着不同的 head。
成员按对象同一性,检查是 id(p) 对 optimizer.param_groups,不是参数名字。
state_dict() 里有什么? embed.weight、embed.bias、norm.weight、norm.bias、head.weight、head.bias。冻结的 norm 参数在,因为冻结不影响注册。positions 不在,因为它是非持久缓冲。适配器与 gate 不在,因为根本没注册。
positions 键缺席是 bug 吗? 不是,这里唯一故意的缺席。torch.arange(dim) 从配置精确重建它,存了除了形状约束什么都没加。区分它与适配器就是要点:两者都不在检查点,只有一个是决定。
model.to("cuda") 搬什么? 六个已注册参数与 positions 缓冲。不搬 gate 与任何适配器权重。第一次前向在设备 mismatch 上挂,失败行是 a.down(x) 或乘 gate,看哪个先到,都不是问题所在。
model.eval() 到哪? 从 Model 到得了的每个已注册模块:根 Model、embed、norm、当前 head。
适配器缺席因为只在普通 Python 列表里,保持已有的 train/eval 模式。
Linear 与 LayerNorm 在这里不因 training flag 变计算,这就是这个模型数值上没症状的原因。Adapter 里放 Dropout 或 BatchNorm,区别立刻可观测。这个模型评估模式下行为不变,这里不花钱——但同样结构在 Adapter 里放 nn.Dropout 或 nn.BatchNorm1d,每次验证都悄悄保持训练模式行为。
最小修复集是什么? 适配器包 nn.ModuleList,gate 做成 nn.Parameter。再重建优化器,或在 head 赋值后建。forward 不用改,算术也不用。变的是归属描述。
什么证据证明修生效? 不是损失降了。len(list(model.parameters())) 变成 15,参数数变成 1,620。state_dict() 多了适配器与门键,仍没有 positions。除冻结 pair 外每个已注册参数报告 in_optimizer=True。前后 diff 显示适配器、gate、head 动了,norm 仍零。存档再载入复现同样验证数,而不是掉回瞎猜。
练习
这些是用来跑的,对应本章配套 notebook。
-
预测七属性。 对
BrokenLinear类,写下requires_grad、is_leaf、backward()后grad、named_parameters()、state_dict()、.to(torch.float64)后 dtype、优化器能不能更新它的预测。然后跑。然后改一词成nn.Parameter跑同样探针。列出哪些属性变了、哪些本来就对。 -
四种弄坏注册。 写普通列表容器、裸张量当权重、该缓冲的张量属性、普通字典里赋值模块各一模型。对每个跑
registered_report与unregistered_report。确认四者前向都 work。 -
部分训练签名。 拿开篇
Classifier训练,产出每层训练期最大参数变化表。然后只从表论证哪些层在优化器里,不看模型源码。 -
持久与否。 给小模块加
causal_mask缓冲与steps_trained缓冲。问重载丢什么决定哪个持久。用state_dict()键、存载验证,检查载入后两缓冲。 -
2×2。 对同时有 dropout 与 batch norm 的模型复现
train()/eval()×no_grad()表。加bn.running_mean每前向前后列,说出四格里哪个 corrupt 运行统计。 -
三集合。 构造一参数已注册但冻结、一已注册但没进优化器、一已注册有微分有更新的模型。跑
registered_report前预测每者的grad、in_optimizer、moved。 -
diff 检查点。 存模型,再重构:容器改名、层下移一层、两层包
Sequential。不载入预测缺失与意外键集。再写函数把旧键 remap 到新名,固定输入比输出证明 work。 -
一模块,多次调用。 写按参数定次数施加同一注册层的模块。确认参数数与次数无关、梯度大小有关。再从第 3 章机制解释梯度为何累积不覆盖。
-
审计没写过的东西。 拿库或仓库的任意模型跑
registered_report与unregistered_report,回答:多少参数、多少缓冲、哪些缓冲非持久、第二份报告有没有东西。有,弄清 bug 还是故意。
下一步:输入从哪来?
模型组织好了。模块是已注册孩子、参数与缓冲的树;名字是穿过树的路径;每天用的每个框架操作都是走它。parameters() 给优化器握的东西。state_dict() 把树变成检查点。.to() 走它搬 state。train() 与 eval() 走它置 flag。autograd 另行记录某次前向实际发生什么,两结构只在你让它们一致的程度一致。
这足够不再为模型大小担心。一百个 Transformer block 与三层线性层同样 walk, misbehave 时问本章的问题。
另一边还缺一块。本书到此每个训练循环的数据都躺在张量里,已在内存,已是正确形状,已在正确设备。真实输入从磁盘、网络、要解码的文件、要转换的格式、不装进内存的量来。原始字节到 model(x) 之间有条流水线,每个训练步前产出 batch。
那条流水线有本章工具检不出的失败模式,因为它哪都没错。模型对,梯度对,检查点对——GPU 大多数时间什么都不干,等下一 batch 到来。
喂模型。