参数、状态与内存

Dive into Deep Learning · §5.2

参数、状态与内存
状态树 · 可训练参数与缓冲区 · Adam 每参数 16 B 下限 · 权重绑定 · 冻结

为什么 8B 模型在批量大小为 1 之前就需要 128 GB

系统内存预算

  • 四份全精度副本(16\text{ B/param}):fp32 Adam 存储权重 \mathbf{w}(4\text{ B})、梯度 \mathbf{g}(4\text{ B})、一阶矩 \mathbf{m}(4\text{ B})和二阶矩 \mathbf{v}(4\text{ B})。
  • 8B 参数静态下限:8 \times 10^9 \times 16\text{ B} = 128\text{ GB},尚未加载任何输入批量就已超出 80 GB GPU 的容量。
  • 理解状态树的重要性:规划内存预算、保存检查点和冻结层都需要追踪状态树中的每一个张量。

贯穿示例:双块残差 MLP

构建状态树

  • 我们在一个包含 6 个线性层和 12 个参数张量的紧凑残差 MLP(20 \to 64 \to \text{ two } 64\text{-wide residual blocks } \to 10)上观察状态遍历:
class ResidualBlock(nn.Module):
    def __init__(self, num_hiddens):
        super().__init__()
        self.body = nn.Sequential(
            nn.Linear(num_hiddens, num_hiddens), nn.ReLU(),
            nn.Linear(num_hiddens, num_hiddens))

    def forward(self, X):
        return X + self.body(X)

net = nn.Sequential(nn.Linear(20, 64), ResidualBlock(64),
                    ResidualBlock(64), nn.Linear(64, 10))
X = torch.randn(2, 20)
net(X).shape

按状态树路径访问参数

树遍历

  • 全树迭代器会返回每个叶节点及其在树中的路径:
named = list(net.named_parameters())
len(named), [(name, p.shape) for name, p in named[2:6]]
(12,
 [('1.body.0.weight', torch.Size([64, 64])),
  ('1.body.0.bias', torch.Size([64])),
  ('1.body.2.weight', torch.Size([64, 64])),
  ('1.body.2.bias', torch.Size([64]))])
list(net.state_dict()) == [name for name, _ in net.named_parameters()]
True

层中张量的三类划分

参数与缓冲区

  • 参数:由优化器更新,随检查点保存,并迁移到 GPU(\mathbf{W}, \mathbf{b}, \mathbf{g})。
  • 已注册缓冲区:优化器会跳过,但会随检查点保存,并与模型一同迁移或转换数据类型(特征 \boldsymbol{\mu}, \boldsymbol{\sigma}、批量规范化运行统计量)。
  • 普通属性:对检查点和设备迁移不可见;切勿将持久张量存为普通 Python 属性。

在 Standardizer 中注册不可训练的缓冲区

代码中的缓冲区

  • Standardizer 层将训练集统计量 \boldsymbol{\mu} 和 \boldsymbol{\sigma} 注册为不可训练的缓冲区。

包含两个缓冲区的 Standardizer 层

代码中的缓冲区

class Standardizer(nn.Module):
    def __init__(self, mean, std):
        super().__init__()
        self.register_buffer('mean', mean)
        self.register_buffer('std', std)
        self.out = nn.Linear(4, 2)

    def forward(self, X):
        return self.out((X - self.mean) / self.std)

sample = torch.randn(100, 4) * torch.arange(1., 5.)
standardizer = Standardizer(sample.mean(0), sample.std(0, correction=0))
list(standardizer.state_dict())
['mean', 'std', 'out.weight', 'out.bias']

检查点包含缓冲区;优化器跳过它们

过滤状态树

  • 将完整状态树与可训练参数对比可以确认,mean 和 std 会随模型写入磁盘并迁移至 GPU,而优化器仅更新 weight 和 bias:
[name for name, _ in standardizer.named_parameters()]
['out.weight', 'out.bias']

残差 MLP 的参数量与字节数核算

内存计算

我们可以解析计算残差 MLP 的参数量,并按 fp32 下 Adam 每参数 16 字节的规则将其换算为字节数:

层组 参数量公式(W + b) 参数量 fp32 Adam 状态(16\text{ B/param})
输入层(0) 20 \times 64 + 64 1{,}344 21{,}504\text{ B}
残差块(1、2) 2 \times [2 \times (64 \times 64 + 64)] 16{,}640 266{,}240\text{ B}
输出头(3) 64 \times 10 + 10 650 10{,}400\text{ B}
整个网络 12 个参数张量 18{,}634 298{,}144\text{ B}(0.28\text{ MiB})
18634 parameters: 0.28 MiB for weights + gradients + Adam state

验证 Adam 分配了两份完整模型副本

优化器状态分配

  • Adam 为每个参数维护滑动一阶矩和二阶矩(\mathbf{m} 和 \mathbf{v}),额外增加 2 \times 18{,}634 = 37{,}268 个浮点数(8\text{ B/param}):
adam = torch.optim.Adam(net.parameters())
net(X).sum().backward()
adam.step()
moments = sum(t.numel() for state in adam.state.values()
              for t in state.values() if t.ndim > 0)
moments == 2 * n
True

不分配内存即可抽象统计参数量

元设备与形状追踪

  • 框架仅凭形状和数据类型就能抽象追踪构造函数——以零字节内存分配核算 Llama 3 8B 含 525.3\text{M} 参数(2.1 GB)的输出头:
with torch.device('meta'):
    head = nn.Linear(4096, 128256, bias=False)   # shapes, no data
n_head = sum(p.numel() for p in head.parameters())
print(head.weight.device, f'{n_head:,} parameters, '
      f'{4 * n_head / 1e9:.1f} GB in fp32')
meta 525,336,576 parameters, 2.1 GB in fp32

在目标硬件上具象化元设备模型

零浪费检查点加载

  • 在 torch.device('meta') 上构建模型,并在调用 load_state_dict 前先调用 to_empty(device=...),可跳过多余的 CPU 随机初始化:
with torch.device('meta'):
    clone = nn.Sequential(nn.Linear(20, 64), ResidualBlock(64),
                          ResidualBlock(64), nn.Linear(64, 10))
clone = clone.to_empty(device='cpu')   # memory, no values yet
clone.load_state_dict(net.state_dict())
torch.equal(clone(X), net(X))
True

权重绑定:单个参数张量兼任多重角色

共享参数

语言模型通过 |V| \times d 嵌入表将输入词元 ID 映射为 d 维向量,再通过 |V| \times d 输出头将最终的 d 维向量投影回 |V| 个词元 logit:

  • 共享语义几何结构:将两层绑定到完全相同的 |V| \times d 张量,可强制统一词元表示,并省去 |V| \times d 个参数。
  • 显著节省内存:在 GPT-2 small(|V|=50{,}257, d=768)中,绑定后的表在 124\text{M} 总参数中占 38.6\text{M}(占整个网络的 31\%)。

在微型语言模型中实现权重绑定

代码中的权重绑定

class ToyLM(nn.Module):
    def __init__(self, vocab_size, d, tied=True):
        super().__init__()
        self.emb = nn.Embedding(vocab_size, d)
        self.body = nn.Linear(d, d)
        self.head = nn.Linear(d, vocab_size, bias=False)
        if tied:
            self.head.weight = self.emb.weight   # one tensor, two roles

    def forward(self, tokens):
        return self.head(torch.relu(self.body(self.emb(tokens))))

lm = ToyLM(vocab_size=100, d=16)
lm.head.weight is lm.emb.weight
  • 在 ToyLM(|V| = 100, d = 16)中,输出投影是输入嵌入表的别名,因此该表仅存储一份:
True

绑定张量会被去重并仅统计一次

参数去重

  • 树遍历器会对共享存储去重,因此 100 \times 16 = 1{,}600 的嵌入表仅统计一次(绑定后 1{,}872,未绑定 3{,}472):
untied = ToyLM(vocab_size=100, d=16, tied=False)
(sum(p.numel() for p in lm.parameters()),
 sum(p.numel() for p in untied.parameters()))
(1872, 3472)

各调用点的梯度会累加到绑定张量中

多元链式法则

\frac{\partial L}{\partial \mathbf{W}} = \frac{\partial L}{\partial \mathbf{W}_{\text{emb}}} + \frac{\partial L}{\partial \mathbf{W}_{\text{head}}}

untied.load_state_dict(lm.state_dict())   # same values, separate tensors
tokens = torch.randint(0, 100, (2, 8))
lm(tokens).sum().backward()
untied(tokens).sum().backward()
torch.allclose(lm.emb.weight.grad,
               untied.emb.weight.grad + untied.head.weight.grad)
True

冻结参数用于迁移学习

选择性优化

在小数据集上微调预训练骨干网络时,我们冻结骨干权重,仅训练输出头(在我们的残差 MLP 中为 18{,}634 个参数中的 650 个):

finetune = nn.Sequential(nn.Linear(20, 64), ResidualBlock(64),
                         ResidualBlock(64), nn.Linear(64, 10))
for p in finetune[:-1].parameters():
    p.requires_grad = False

(sum(p.numel() for p in finetune.parameters() if p.requires_grad),
 sum(p.numel() for p in finetune.parameters()))
(650, 18634)

冻结后仅训练输出头

选择性优化

head_opt = torch.optim.Adam(
    (p for p in finetune.parameters() if p.requires_grad), lr=0.1)
before = [p.clone() for p in finetune.parameters()]
finetune(X).sum().backward()
head_opt.step()
[not torch.equal(b, p) for b, p in zip(before, finetune.parameters())]
[False,
 False,
 False,
 False,
 False,
 False,
 False,
 False,
 False,
 False,
 True,
 True]

冻结参数的两个隐蔽陷阱

冻结的系统隐患

bn = nn.BatchNorm1d(4)
for p in bn.parameters():
    p.requires_grad = False
before = bn.running_mean.clone()
bn(torch.randn(8, 4) + 3)          # training mode: the statistics update
torch.allclose(bn.running_mean, before)
False
  • 陷阱 1:除非优化器仅涵盖未冻结参数,否则 Adam 矩(8\text{ B/param})仍会常驻内存。
  • 陷阱 2:在训练模式下,除非切换到评估模式,否则 BatchNorm 层在前向传播时仍会更新滑动均值和方差缓冲区。

概念自测:内存预算与参数共享

概念自测

结合 80 亿参数语言模型(fp32、Adam,输出头含 4096 \times 128{,}256 \approx 525\text{M} 个参数)检验你的理解:

  1. 假设冻结除 525\text{M} 参数输出头外的整个 8B 骨干网络,并仅为输出头构建 Adam 优化器。在 fp32 下需要多少持久状态内存?能否装入单张 80 GB GPU?
  2. 如果改为对全部 8B 参数构建 Adam,运行 1 步预热,然后冻结骨干网络且不重建优化器,结果又如何?
  3. 如果两层共享权重矩阵 \mathbf{W},而你通过嵌入层冻结了 \mathbf{W},那么 self.head 还能继续更新吗?

答案:

  1. \approx 38.3\text{ GB}(单张 80 GB GPU 可容纳):全部 8B 权重需要 32\text{ GB},而 525\text{M} 输出头的梯度与 Adam 矩仅需 12 \times 0.525\text{B} = 6.3\text{ GB}。
  2. \approx 98.1\text{ GB}(在 80 GB GPU 上会显存溢出):Adam 会保留第 1 步分配的 64\text{ GB} 矩状态(32\text{ GB weights} + 64\text{ GB moments} + 2.1\text{ GB head grad})。
  3. 不能:由于 self.emb.weight 和 self.head.weight 指向完全相同的参数张量,冻结其中一个会同时冻结两个角色。

小结:参数、状态与内存

核心要点

  • 参数与缓冲区:两者都会随模型保存至检查点并迁移到 GPU,但优化器仅更新可训练参数。
  • 静态内存与元设备统计:fp32 下的 Adam 消耗 16\text{ B/param}(8B 模型需 128 GB);元设备无需物理内存分配即可核算精确字节预算。
  • 权重绑定与冻结:共享张量仅统计一次,并汇总各调用点的梯度;冻结参数时须过滤优化器参数列表,并将 BatchNorm 切换为评估模式。