9.8  批量大小

实践中,小批量大小 \(b\) 往往只是选来填满加速器显存,随后便不再触碰。然而一旦将训练扩展到多块 GPU,或在挂钟训练时间与总计算 FLOPs 之间权衡,我们立刻面对一个根本问题:若将小批量大小 \(b\) 翻倍(使每步并行计算量翻倍),训练能否在减半的步数内达到目标损失?

在 9.2 节 中我们看到,含 \(b\) 个样本的小批量将梯度采样方差降至 \(\operatorname{tr}(\boldsymbol{\Sigma})/b\)。这蕴含着两个截然不同的区间:

  1. 小批量(噪声主导)区间:当采样噪声大于真实梯度时,将 \(b\) 翻倍使噪声方差减半,从而允许更大学习率,把所需步数 \(S(b)\) 减半而保持已处理总样本数 \(E(b) = b\,S(b)\) 恒定(完美线性缩放)。
  2. 大批量(曲率主导)区间:一旦 \(b\) 大到使小批量梯度已逼近真实全批量梯度,继续增大 \(b\) 对 \(S(b)\) 的缩减收益递减,同时却按线性成倍推高数据与算力开销 \(E(b)\)。

McCandlish 等 (2018年) 表明,这两个区间的转折发生在临界批量大小 \(b_{\text{crit}}\),它可由梯度噪声尺度 \(b_{\text{noise}} = \operatorname{tr}(\boldsymbol{\Sigma}) / \|\nabla f\|^2\) 预测。本节构建 \(b_{\text{noise}}\) 的双批量估计量,推导步数–数据权衡前沿以及 SGD(\(\eta \propto b\))与 Adam(\(\eta \propto \sqrt{b}\))的学习率缩放规则,并在 TinyLM 与 FashionCNN 上检验两项预测。

import random

9.8.1 梯度噪声尺度

9.8.1.1 信号、噪声与双批量估计量

记 \(\nabla f(\mathbf{x})\) 为精确全量梯度,\(\hat{\mathbf{g}}_b\) 为 \(b\) 个独立样本平均所得的小批量梯度,逐样本梯度协方差为 \(\boldsymbol{\Sigma}\)。由于 \(\mathbb{E}[\hat{\mathbf{g}}_b] = \nabla f\) 且 \(\mathbb{E}[\|\hat{\mathbf{g}}_b - \nabla f\|^2] = \operatorname{tr}(\boldsymbol{\Sigma})/b\),小批量梯度平方范数的期望分解为信号功率 \(\|\nabla f\|^2\) 与噪声功率 \(\operatorname{tr}(\boldsymbol{\Sigma})/b\) 之和:

\[\mathbb{E}\big[\|\hat{\mathbf{g}}_b\|^2\big] = \|\nabla f\|^2 + \frac{\operatorname{tr} \boldsymbol{\Sigma}}{b}. \tag{9.8.1}\]

信号功率与噪声功率恰好相等之处定义为简单梯度噪声尺度 (McCandlish 等 2018年):

\[b_{\textrm{noise}} = \frac{\operatorname{tr} \boldsymbol{\Sigma}}{\|\nabla f\|^2}. \tag{9.8.2}\]

我们无需遍历整个数据集即可估计 \(\operatorname{tr}\boldsymbol{\Sigma}\) 与 \(\|\nabla f\|^2\):只需在两个批量大小 \(b_{\text{s}} < b_{\text{l}}\) 处测量平均梯度平方范数 \(N_b = \mathbb{E}[\|\hat{\mathbf{g}}_b\|^2]\),再求解二元线性方程组 式 9.8.1:

\[ \operatorname{tr} \boldsymbol{\Sigma} \approx \frac{N_{b_{\textrm{s}}} - N_{b_{\textrm{l}}}}{1/b_{\textrm{s}} - 1/b_{\textrm{l}}}, \qquad \|\nabla f\|^2 \approx \frac{b_{\textrm{l}} N_{b_{\textrm{l}}} - b_{\textrm{s}} N_{b_{\textrm{s}}}}{b_{\textrm{l}} - b_{\textrm{s}}}. \]

先将 WikiText-103 与 Fashion-MNIST 加载到加速器上,并定义随机小批量采样器 sample_fashion(b) 与 sample_lm(b):

device = d2l.try_gpu()
data = d2l.WikiText103(batch_size=64, num_steps=64)
fashion = d2l.FashionMNIST(batch_size=256)
X_f = (fashion.train.data.float() / 255).unsqueeze(1).to(device)
y_f = fashion.train.targets.to(device)

def sample_fashion(b):  # b random training images
    i = torch.randint(len(y_f), (b,), device=device)
    return X_f[i], y_f[i]

def sample_lm(b):  # b windows at random offsets in the training text
    starts = torch.randint(len(data.train) - data.num_steps, (b,))
    X, Y = data.windows(data.train, starts.numpy())
    return X.to(device), Y.to(device)
Downloading ../data/wikitext-103/train-00000-of-00002.parquet from https://huggingface.co/datasets/Salesforce/wikitext/resolve/main/wikitext-103-raw-v1/train-00000-of-00002.parquet...
Downloading ../data/wikitext-103/validation-00000-of-00001.parquet from https://huggingface.co/datasets/Salesforce/wikitext/resolve/main/wikitext-103-raw-v1/validation-00000-of-00001.parquet...
data = d2l.WikiText103(batch_size=64, num_steps=64)
fashion = d2l.FashionMNIST(batch_size=256)
X_f = jnp.asarray(fashion.train[0], jnp.float32)[..., None] / 255
y_f = jnp.asarray(fashion.train[1], jnp.int32)
rng = np.random.default_rng(d2l.get_seed())

def sample_fashion(b):  # b random training images
    i = rng.integers(len(y_f), size=b)
    return X_f[i], y_f[i]

def sample_lm(b):  # b windows at random offsets in the training text
    return data.windows(data.train,
                        rng.integers(len(data.train) - data.num_steps, size=b))

利用这些采样器,我们在 d2l 中保存交叉熵辅助函数 ce_loss、全参数平方梯度范数 grad_sq_norm 以及双批量估计量 noise_scale:

def ce_loss(model, X, Y):
    """Mean cross-entropy of the logits model(X) for the labels Y."""
    logits = model(X)
    return F.cross_entropy(logits.reshape(-1, logits.shape[-1]),
                           Y.reshape(-1))

def grad_sq_norm(model, X, Y):
    """Squared norm of the gradient of ce_loss over all parameters."""
    grads = torch.autograd.grad(ce_loss(model, X, Y),
                                list(model.parameters()))
    return sum((g ** 2).sum() for g in grads)

def noise_scale(model, sample, b_small=16, b_big=2048, m=400):
    """Gradient-noise scale from the mean squared gradient norms of m
    minibatches of size b_small and m // 8 of size b_big from sample(b)."""
    def mean_sq_norm(b, m):  # N_b, averaged over m random minibatches
        return torch.stack([grad_sq_norm(model, *sample(b))
                            for _ in range(m)]).mean()
    n_small, n_big = mean_sq_norm(b_small, m), mean_sq_norm(b_big, m // 8)
    tr_sigma = (n_small - n_big) / (1 / b_small - 1 / b_big)
    sq_norm = (b_big * n_big - b_small * n_small) / (b_big - b_small)
    return (tr_sigma / sq_norm).item()
def ce_loss(model, X, Y):
    """Mean cross-entropy of the logits model(X) for the labels Y."""
    logits = model(X)
    return optax.softmax_cross_entropy_with_integer_labels(
        logits.reshape(-1, logits.shape[-1]), Y.reshape(-1)).mean()

@nnx.jit
def grad_sq_norm(model, X, Y):
    """Squared norm of the gradient of ce_loss over all parameters."""
    grads = nnx.grad(ce_loss)(model, X, Y)
    return sum((g ** 2).sum() for g in jax.tree.leaves(grads))

def noise_scale(model, sample, b_small=16, b_big=2048, m=400):
    """Gradient-noise scale from the mean squared gradient norms of m
    minibatches of size b_small and m // 8 of size b_big from sample(b)."""
    def mean_sq_norm(b, m):  # N_b, averaged over m random minibatches
        return jnp.stack([grad_sq_norm(model, *sample(b))
                          for _ in range(m)]).mean()
    n_small, n_big = mean_sq_norm(b_small, m), mean_sq_norm(b_big, m // 8)
    tr_sigma = (n_small - n_big) / (1 / b_small - 1 / b_big)
    sq_norm = (b_big * n_big - b_small * n_small) / (b_big - b_small)
    return float(tr_sigma / sq_norm)

现在在 TinyLM(\(b_{\text{s}} = 8, b_{\text{l}} = 256\))的初始化处以及经 \(500\) 步 Adam(\(\eta = 3 \times 10^{-3}\))后分别计算 noise_scale:

lm = d2l.TinyLM(len(data.vocab)).to(device)
print(f'noise scale at initialization: '
      f'{noise_scale(lm, sample_lm, b_small=8, b_big=256):.1f}')
optimizer = torch.optim.Adam(lm.parameters(), lr=0.003)
d2l.train_steps(lm, data, optimizer, num_steps=500)
print(f'after 500 steps of Adam: '
      f'{noise_scale(lm, sample_lm, b_small=8, b_big=256):.0f}')
noise scale at initialization: 2.2
after 500 steps of Adam: 93
lm = d2l.TinyLM(len(data.vocab), rngs=nnx.Rngs(d2l.get_key()))
print(f'noise scale at initialization: '
      f'{noise_scale(lm, sample_lm, b_small=8, b_big=256):.1f}')
optimizer = nnx.Optimizer(lm, optax.adam(0.003), wrt=nnx.Param)
d2l.train_steps(lm, data, optimizer, num_steps=500)
print(f'after 500 steps of Adam: '
      f'{noise_scale(lm, sample_lm, b_small=8, b_big=256):.0f}')
noise scale at initialization: 2.0
after 500 steps of Adam: 91

图像卷积网络的噪声尺度是否以同样方式增长?我们在 FashionCNN 上以默认 \(b_{\text{s}} = 16\) 与 \(b_{\text{l}} = 2{,}048\) 张图像重复测量,分别取初始化时及经 \(200\) 步 Adam(\(\eta = 0.004\),即下文扫描在 \(b = 256\) 处使用的学习率)后:

cnn = d2l.FashionCNN().to(device)
print(f'noise scale at initialization: {noise_scale(cnn, sample_fashion):.0f}')
optimizer = torch.optim.Adam(cnn.parameters(), lr=0.004)
d2l.train_steps(cnn, fashion, optimizer, num_steps=200)
print(f'after 200 steps of Adam: {noise_scale(cnn, sample_fashion):.0f}')
noise scale at initialization: 64
after 200 steps of Adam: 120
cnn = d2l.FashionCNN(rngs=nnx.Rngs(d2l.get_key()))
print(f'noise scale at initialization: {noise_scale(cnn, sample_fashion):.0f}')
optimizer = nnx.Optimizer(cnn, optax.adam(0.004), wrt=nnx.Param)
d2l.train_steps(cnn, fashion, optimizer, num_steps=200)
print(f'after 200 steps of Adam: {noise_scale(cnn, sample_fashion):.0f}')
noise scale at initialization: 95
after 200 steps of Adam: 76

在 TinyLM 初始化处,每个窗口都需要相同的粗粒度一元频次调整,因此信号 \(\|\nabla f\|^2\) 极大,\(b_{\text{noise}} \approx 2\) 条序列。一旦常见字节统计被学到(到第 \(500\) 步),\(\|\nabla f\|^2\) 下降而序列间方差 \(\operatorname{tr}\boldsymbol{\Sigma}\) 持续存在,使 \(b_{\text{noise}}\) 暴增十倍以上至 \(\sim 50\text{--}150\) 条序列。

FashionCNN 的表现截然不同。其十个类别均衡分布,未训练网络找不到所有图像一致同意的调整方向,因此从第一步起噪声尺度就在 \(100\) 张图像量级。经历 \(200\) 步后,估计值随运行不同向任一方向变动不足两倍,始终停留在 \(100\) 张图像量级。

9.8.2 批量大小、步数效率与学习率缩放

9.8.2.1 最优步长与效率前沿

对 \(L\)-光滑下降上界 \(f(\mathbf{x} - \eta\hat{\mathbf{g}}_b) - f(\mathbf{x}) \le -\eta\nabla f^\top \hat{\mathbf{g}}_b + \frac{L}{2}\eta^2\|\hat{\mathbf{g}}_b\|^2\) 取期望并代入 式 9.8.1 得

\[ \mathbb{E}\big[f(\mathbf{x} - \eta\, \hat{\mathbf{g}}_b)\big] - f(\mathbf{x}) \leq -\eta\, \|\nabla f\|^2 + \frac{L}{2}\, \eta^2 \Big(\|\nabla f\|^2 + \frac{\operatorname{tr} \boldsymbol{\Sigma}}{b}\Big). \tag{9.8.3}\]

对右侧关于 \(\eta\) 最小化,给出最优步长 \(\eta_{\text{opt}}(b)\) 与单步保证降幅:

\[ \begin{aligned} \eta_{\textrm{opt}}(b) &= \frac{1}{L} \cdot \frac{1}{1 + b_{\textrm{noise}} / b}, \\ f(\mathbf{x}) - \mathbb{E}\big[f(\mathbf{x} - \eta_{\textrm{opt}}\, \hat{\mathbf{g}}_b)\big] &\geq \frac{\|\nabla f\|^2}{2L} \cdot \frac{1}{1 + b_{\textrm{noise}} / b}. \end{aligned} \tag{9.8.4}\]

(用局部海森矩阵 \(\mathbf{H}\) 替换标量光滑上界 \(L\mathbf{I}\) 会导出完全相同的表达式,只是替换为曲率加权噪声尺度 \(\operatorname{tr}(\mathbf{H}\boldsymbol{\Sigma}) / (\nabla f^\top\mathbf{H}\nabla f)\) (McCandlish 等 2018年),而 式 9.8.2 中的 \(b_{\text{noise}}\) 是它的无海森代理。)

由于批量大小为 \(b\) 的每一步取得精确全批量步进展的 \((1 + b_{\text{noise}}/b)^{-1}\),达到需要 \(S_{\min}\) 次全批量步的目标损失总共需要 \(S(b)\) 步与 \(E(b) = b\,S(b)\) 个训练样本:

\[ \frac{S(b)}{S_{\min}} = 1 + \frac{b_{\textrm{noise}}}{b}, \qquad \frac{E(b)}{E_{\min}} = 1 + \frac{b}{b_{\textrm{noise}}}, \tag{9.8.5}\]

其中 \(E_{\min} = b_{\text{noise}} S_{\min}\) 是在小批量极限 \(b \ll b_{\text{noise}}\) 下达到的最小数据预算。在临界批量大小 \(b_{\text{crit}} = b_{\text{noise}}\) 处,步数与样本数恰好均为各自理论最小值的两倍(\(S = 2S_{\min}, E = 2E_{\min}\)),标出帕累托前沿 \(((E/E_{\min} - 1)(S/S_{\min} - 1) = 1\))的拐点。

9.8.2.2 线性对比平方根学习率缩放

在噪声主导区间(\(b_0, b \ll b_{\text{noise}}\))将批量大小从 \(b_0\) 增至 \(b\) 时,学习率 \(\eta\) 应如何缩放?

  • SGD 与动量法(线性缩放):由 式 9.8.4,当 \(b \ll b_{\text{noise}}\) 时 \(\eta_{\text{opt}}(b) \approx \frac{b}{L b_{\text{noise}}} \propto b\)。等价地,批量 \(b_0\) 上步长 \(\eta_0\) 的 \(k\) 步与批量 \(k b_0\) 上步长 \(k\eta_0\) 的一步匹配,同时保持稳态噪声下限 \(\propto \eta / b\) 不变 (Goyal 等 2017年; Smith 等 2018年)。
  • Adam 与 AdamW(平方根缩放):在噪声主导区间,若某坐标梯度均值为 \(\bar{g}\)、标准差为 \(\sigma / \sqrt{b}\),Adam 会用其 RMS 尺度 \(\sqrt{\hat{v}_t} \approx \sigma / \sqrt{b}\) 规范化梯度,得到单步漂移 \(-\eta(\sqrt{b}/\sigma)\bar{g}\) 与步幅噪声 \(-\eta z\)(\(z \sim \mathcal{N}(0, 1)\))。由于分母 \(\sigma/\sqrt{b}\) 已自带因子 \(\sqrt{b/b_0}\),用单个大步匹配 \(k = b/b_0\) 个小步的漂移与累积方差要求将 \(\eta\) 乘以 \(\sqrt{b/b_0}\) (Malladi 等 2022年):

\[ \begin{aligned} \eta(b) &= \frac{b}{b_0}\, \eta_0 \;\; \textrm{(SGD)}, \\ \eta(b) &= \sqrt{\frac{b}{b_0}}\, \eta_0 \;\; \textrm{(Adam / AdamW)}. \end{aligned} \tag{9.8.6}\]

一旦 \(b\) 超过 \(b_{\text{crit}}\),梯度噪声不再主导分母,最优学习率在确定性曲率极限处饱和,不再随 \(b\) 继续增长 (Shallue 等 2019年)。

9.8.3 实证验证:达标步数与缩放规则

为了测量达到固定留出损失目标所需的步数 \(S(b)\),先定义 eval_loss 以 \(4{,}096\) 样本为块在验证张量上计算 ce_loss:

def eval_loss(model, X, Y, chunk=4096):
    with torch.inference_mode():
        return torch.stack([ce_loss(model, X[i:i + chunk], Y[i:i + chunk])
                            for i in range(0, len(Y), chunk)]).mean().item()
eval_chunk = nnx.jit(ce_loss)

def eval_loss(model, X, Y, chunk=4096):
    return float(jnp.stack([eval_chunk(model, X[i:i + chunk], Y[i:i + chunk])
                            for i in range(0, len(Y), chunk)]).mean())

终止封装 train_to_target 在 d2l.train_steps 内每隔 eval_every 步检查 eval_loss,返回达到 target 时的步数(若耗尽 max_steps 则返回 inf):

def train_to_target(model, data, optimizer, X_eval, Y_eval, target,
                    max_steps, eval_every=10):
    """Return the number of steps until the eval loss reaches target."""
    def reached(step):
        return (step % eval_every == 0
                and eval_loss(model, X_eval, Y_eval) <= target)
    steps = len(d2l.train_steps(model, data, optimizer, max_steps,
                                stop=reached))
    return steps if reached(steps) else float('inf')
def train_to_target(model, data, optimizer, X_eval, Y_eval, target,
                    max_steps, eval_every=10):
    """Return the number of steps until the eval loss reaches target."""
    def reached(step):
        return (step % eval_every == 0
                and eval_loss(model, X_eval, Y_eval) <= target)
    steps = len(d2l.train_steps(model, data, optimizer, max_steps,
                                stop=reached))
    return steps if reached(steps) else float('inf')

先在 TinyLM(目标验证损失 \(1.9\) 奈特/字节)上从共享初始化出发跨 \(b \in \{4, 16, 64, 256\}\) 条序列运行 train_to_target,按 \(\eta = 0.003\sqrt{b / 64}\) 缩放 Adam 学习率:

starts = np.arange(0, len(data.val) - data.num_steps, data.num_steps)
X_val, Y_val = (t.to(device) for t in data.windows(data.val,
                                                   starts[::8][:2048]))
lm_bs, lm_steps = [4, 16, 64, 256], []
seed = random.getrandbits(32)  # One initialization for all batch sizes
for b in lm_bs:
    torch.manual_seed(seed)
    data.batch_size = b
    model = d2l.TinyLM(len(data.vocab)).to(device)
    optimizer = torch.optim.Adam(model.parameters(),
                                 lr=0.003 * math.sqrt(b / 64))
    lm_steps.append(train_to_target(model, data, optimizer, X_val, Y_val,
                                    target=1.9, max_steps=8000))
    print(f'b={b:4d}  steps={lm_steps[-1]:6.0f}  '
          f'examples={b * lm_steps[-1]:8.0f}')
d2l.plot(lm_bs, [lm_steps, [lm_steps[0] * lm_bs[0] / b for b in lm_bs]],
         'batch size (sequences)', 'steps to loss 1.9', xscale='log',
         yscale='log', legend=['measured', 'perfect scaling'])
b=   4  steps=  3880  examples=   15520
b=  16  steps=  1200  examples=   19200
b=  64  steps=   440  examples=   28160
b= 256  steps=   210  examples=   53760

starts = np.arange(0, len(data.val) - data.num_steps, data.num_steps)
X_val, Y_val = data.windows(data.val, starts[::8][:2048])
lm_bs, lm_steps = [4, 16, 64, 256], []
seed = d2l.get_seed()  # One initialization for all batch sizes
for b in lm_bs:
    data.batch_size = b
    model = d2l.TinyLM(len(data.vocab), rngs=nnx.Rngs(seed))
    optimizer = nnx.Optimizer(model,
                              optax.adam(0.003 * math.sqrt(b / 64)),
                              wrt=nnx.Param)
    lm_steps.append(train_to_target(model, data, optimizer, X_val, Y_val,
                                    target=1.9, max_steps=8000))
    print(f'b={b:4d}  steps={lm_steps[-1]:6.0f}  '
          f'examples={b * lm_steps[-1]:8.0f}')
d2l.plot(lm_bs, [lm_steps, [lm_steps[0] * lm_bs[0] / b for b in lm_bs]],
         'batch size (sequences)', 'steps to loss 1.9', xscale='log',
         yscale='log', legend=['measured', 'perfect scaling'])
b=   4  steps=  4110  examples=   16440
b=  16  steps=  1130  examples=   18080
b=  64  steps=   420  examples=   26880
b= 256  steps=   220  examples=   56320

再在 FashionCNN(目标损失 \(0.35\))上跨 \(b \in \{8, 32, 128, 512, 2048\}\) 张图像重复达标步数扫描,在 \(b = 512\) 以下按 \(\eta = 0.004\sqrt{\min(b, 512)/256}\) 缩放:

cnn_bs, cnn_steps = [8, 32, 128, 512, 2048], []
seed = random.getrandbits(32)  # One initialization for all batch sizes
for b in cnn_bs:
    torch.manual_seed(seed)
    fashion_b = d2l.FashionMNIST(batch_size=b)
    model = d2l.FashionCNN().to(device)
    lr = 0.004 * math.sqrt(min(b, 512) / 256)  # Held fixed above 512
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)
    cnn_steps.append(train_to_target(model, fashion_b, optimizer,
                                     X_f[:8192], y_f[:8192], target=0.35,
                                     max_steps=8000))
    print(f'b={b:4d}  steps={cnn_steps[-1]:6.0f}  '
          f'examples={b * cnn_steps[-1]:8.0f}')
d2l.plot(cnn_bs, [cnn_steps,
                  [cnn_steps[0] * cnn_bs[0] / b for b in cnn_bs]],
         'batch size', 'steps to loss 0.35', xscale='log', yscale='log',
         legend=['measured', 'perfect scaling'])
b=   8  steps=  2340  examples=   18720
b=  32  steps=   650  examples=   20800
b= 128  steps=   230  examples=   29440
b= 512  steps=   130  examples=   66560
b=2048  steps=    80  examples=  163840

cnn_bs, cnn_steps = [8, 32, 128, 512, 2048], []
seed = d2l.get_seed()  # One initialization for all batch sizes
for b in cnn_bs:
    fashion_b = d2l.FashionMNIST(batch_size=b)
    model = d2l.FashionCNN(rngs=nnx.Rngs(seed))
    lr = 0.004 * math.sqrt(min(b, 512) / 256)  # Held fixed above 512
    optimizer = nnx.Optimizer(model, optax.adam(lr), wrt=nnx.Param)
    cnn_steps.append(train_to_target(model, fashion_b, optimizer,
                                     X_f[:8192], y_f[:8192], target=0.35,
                                     max_steps=8000))
    print(f'b={b:4d}  steps={cnn_steps[-1]:6.0f}  '
          f'examples={b * cnn_steps[-1]:8.0f}')
d2l.plot(cnn_bs, [cnn_steps,
                  [cnn_steps[0] * cnn_bs[0] / b for b in cnn_bs]],
         'batch size', 'steps to loss 0.35', xscale='log', yscale='log',
         legend=['measured', 'perfect scaling'])
b=   8  steps=  3040  examples=   24320
b=  32  steps=   760  examples=   24320
b= 128  steps=   250  examples=   32000
b= 512  steps=   110  examples=   56320
b=2048  steps=    80  examples=  163840

由于 \(S(b) = S_{\min}(1 + b_{\text{crit}}/b)\) 关于 \(1/b\) 线性,fit_steps 通过加权最小二乘为两个模型提取渐近步数下限 \(S_{\min}\) 与实证临界批量大小 \(b_{\text{crit}}\):

def fit_steps(bs, steps):
    """Fit S(b) = S_min (1 + b_crit / b) by least squares in 1/b."""
    b, S = np.array(bs, dtype=float), np.array(steps, dtype=float)
    ok = np.isfinite(S)  # Leave out runs that never reached the target
    slope, S_min = np.polyfit(1 / b[ok], S[ok], 1, w=1 / S[ok])
    assert S_min > 0, 'step counts never level off: no floor to fit'
    return S_min, slope / S_min

fits = {'TinyLM': fit_steps(lm_bs, lm_steps),
        'FashionCNN': fit_steps(cnn_bs, cnn_steps)}
for name, (S_min, b_crit) in fits.items():
    print(f'{name:10s}  S_min = {S_min:4.0f} steps  b_crit = {b_crit:4.0f}')
TinyLM      S_min =  157 steps  b_crit =  102
FashionCNN  S_min =   78 steps  b_crit =  241
def fit_steps(bs, steps):
    """Fit S(b) = S_min (1 + b_crit / b) by least squares in 1/b."""
    b, S = np.array(bs, dtype=float), np.array(steps, dtype=float)
    ok = np.isfinite(S)  # Leave out runs that never reached the target
    slope, S_min = np.polyfit(1 / b[ok], S[ok], 1, w=1 / S[ok])
    assert S_min > 0, 'step counts never level off: no floor to fit'
    return S_min, slope / S_min

fits = {'TinyLM': fit_steps(lm_bs, lm_steps),
        'FashionCNN': fit_steps(cnn_bs, cnn_steps)}
for name, (S_min, b_crit) in fits.items():
    print(f'{name:10s}  S_min = {S_min:4.0f} steps  b_crit = {b_crit:4.0f}')
TinyLM      S_min =  161 steps  b_crit =   98
FashionCNN  S_min =   68 steps  b_crit =  340

将每次运行的样本数 \(E(b) = b\,S(b)\) 按 \(E_{\min} = b_{\text{crit}} S_{\min}\) 规范化、步数按 \(S_{\min}\) 规范化,把两个模型叠加绘制在普适帕累托前沿 式 9.8.5 上:

x = np.logspace(0.005, 1.3, 100)  # E / E_min along the model curve
xs, ys = [x], [1 + 1 / (x - 1)]
for (S_min, b_crit), bs, steps in zip(fits.values(), (lm_bs, cnn_bs),
                                      (lm_steps, cnn_steps)):
    xs.append([b * S / (b_crit * S_min) for b, S in zip(bs, steps)])
    ys.append([S / S_min for S in steps])
d2l.plot(xs, ys, 'examples / minimum', 'steps / minimum', xscale='log',
         yscale='log', fmts=('-', 'o', 's'),
         legend=['model', 'TinyLM', 'FashionCNN'])

x = np.logspace(0.005, 1.3, 100)  # E / E_min along the model curve
xs, ys = [x], [1 + 1 / (x - 1)]
for (S_min, b_crit), bs, steps in zip(fits.values(), (lm_bs, cnn_bs),
                                      (lm_steps, cnn_steps)):
    xs.append([b * S / (b_crit * S_min) for b, S in zip(bs, steps)])
    ys.append([S / S_min for S in steps])
d2l.plot(xs, ys, 'examples / minimum', 'steps / minimum', xscale='log',
         yscale='log', fmts=('-', 'o', 's'),
         legend=['model', 'TinyLM', 'FashionCNN'])

两种架构都落在普适曲线 \((E/E_{\min} - 1)(S/S_{\min} - 1) = 1\) 附近(靠近 \(E = E_{\min}\) 的点位于曲线陡壁上,实测步数的微小误差就会让它大幅上下移动),拟合出的临界批量大小对 TinyLM 为 \(b_{\text{crit}} \sim 100\) 条序列,对 FashionCNN 为 \(b_{\text{crit}} \sim 200\text{--}400\) 张图像。在 TinyLM 上,拟合值与前文测得略低于 \(100\) 条序列的双批量估计 \(b_{\text{noise}}\) 相符;在 FashionCNN 上,拟合值则是约 \(100\) 张图像估计值的二至四倍。简单噪声尺度忽略了曲率,因此给出的是 \(b_{\text{crit}}\) 的数量级而非精确值。

最后,我们在固定 \(12{,}800\) 张图像(\(1/5\) 轮)的数据预算下,在 FashionCNN 上直接检验线性(\(\eta \propto b\))对比平方根(\(\eta \propto \sqrt{b}\))学习率缩放规则 式 9.8.6。辅助函数 final_loss_at 在批量大小 b 下运行 d2l.lr_sweep 共 num_examples // b 步,返回每次运行最后四分之一阶段的均值损失:

def final_loss_at(make_optimizer, lrs, b, seed, num_examples=12800):
    """Train the CNN once per learning rate; return the final losses."""
    curves, _ = d2l.lr_sweep(d2l.FashionCNN, make_optimizer,
                             d2l.FashionMNIST(batch_size=b), lrs, seed,
                             num_examples // b, verbose=False)
    return [d2l.final_loss(c, k=len(c) // 4) for c in curves.values()]
def final_loss_at(make_tx, lrs, b, seed, num_examples=12800):
    """Train the CNN once per learning rate; return the final losses."""
    init_key, order_key = jax.random.split(jax.random.key(seed))
    data = d2l.DataModule()  # Every run sees the images in one order
    data.train_dataloader = lambda: d2l.ArrayLoader(
        (X_f, y_f), b, shuffle=True, key=order_key)
    curves, _ = d2l.lr_sweep(d2l.FashionCNN, make_tx, data, lrs, init_key,
                             num_examples // b, verbose=False)
    return [d2l.final_loss(c, k=len(c) // 4) for c in curves.values()]

在带动量(\(\beta = 0.9\))的 SGD 下,跨 sgd_lrs 将批量大小从 \(b = 8\) 放大 \(8\times\) 至 \(b = 64\),使最优学习率向右平移 \(4\text{--}8\times\)(\(b = 64\) 时最终损失在 \(\eta = 0.05\) 与 \(0.1\) 之间几乎平齐):

sgd_lrs = [0.003125, 0.00625, 0.0125, 0.025, 0.05, 0.1, 0.2]
make_sgd = lambda model, lr: torch.optim.SGD(model.parameters(), lr,
                                             momentum=0.9)
seed = random.getrandbits(32)
sgd_small = final_loss_at(make_sgd, sgd_lrs, b=8, seed=seed)
sgd_big = final_loss_at(make_sgd, sgd_lrs, b=64, seed=seed)
for b, loss in ((8, sgd_small), (64, sgd_big)):
    print(f'b={b:2d}: best lr {sgd_lrs[np.nanargmin(loss)]:g}')
d2l.plot(sgd_lrs, [sgd_small, sgd_big], 'learning rate', 'final loss',
         xscale='log', legend=['b=8', 'b=64'])
b= 8: best lr 0.0125
b=64: best lr 0.05

sgd_lrs = [0.003125, 0.00625, 0.0125, 0.025, 0.05, 0.1, 0.2]
make_sgd = lambda lr: optax.sgd(lr, momentum=0.9)
seed = d2l.get_seed()
sgd_small = final_loss_at(make_sgd, sgd_lrs, b=8, seed=seed)
sgd_big = final_loss_at(make_sgd, sgd_lrs, b=64, seed=seed)
for b, loss in ((8, sgd_small), (64, sgd_big)):
    print(f'b={b:2d}: best lr {sgd_lrs[np.nanargmin(loss)]:g}')
d2l.plot(sgd_lrs, [sgd_small, sgd_big], 'learning rate', 'final loss',
         xscale='log', legend=['b=8', 'b=64'])
b= 8: best lr 0.0125
b=64: best lr 0.1

相比之下,在 Adam 下跨 adam_lrs 将批量大小从 \(b = 2\) 放大 \(64\times\) 至 \(b = 128\),最优学习率仅右移 \(4\text{--}8\times\)(\(2\) 到 \(3\) 个 \(2\times\) 网格步),吻合 \(\sqrt{64} = 8\times\) 而非 \(64\times\):

adam_lrs = [0.0001 * 2 ** k for k in range(13)]  # 0.0001 to 0.4096
make_adam = lambda model, lr: torch.optim.Adam(model.parameters(), lr)
seed = random.getrandbits(32)
adam_small = final_loss_at(make_adam, adam_lrs, b=2, seed=seed)
adam_big = final_loss_at(make_adam, adam_lrs, b=128, seed=seed)
i, j = int(np.nanargmin(adam_small)), int(np.nanargmin(adam_big))
print(f'best lr: {adam_lrs[i]:g} at b=2; {adam_lrs[j]:g} at b=128, '
      f'final loss {adam_big[j]:.3f}')
for rule, k in (('no scaling', 0), ('square root', 3), ('linear', 6)):
    if i + k < len(adam_lrs):
        print(f'{rule:11s}: lr {adam_lrs[i + k]:g} at b=128, '
              f'final loss {adam_big[i + k]:.3f}')
    else:
        print(f'{rule:11s}: lr {adam_lrs[i] * 2 ** k:g}, beyond the grid')
d2l.plot(adam_lrs, [adam_small, adam_big], 'learning rate', 'final loss',
         xscale='log', legend=['b=2', 'b=128'])
best lr: 0.0008 at b=2; 0.0064 at b=128, final loss 0.510
no scaling : lr 0.0008 at b=128, final loss 0.635
square root: lr 0.0064 at b=128, final loss 0.510
linear     : lr 0.0512 at b=128, final loss 0.726

adam_lrs = [0.0001 * 2 ** k for k in range(13)]  # 0.0001 to 0.4096
make_adam = optax.adam
seed = d2l.get_seed()
adam_small = final_loss_at(make_adam, adam_lrs, b=2, seed=seed)
adam_big = final_loss_at(make_adam, adam_lrs, b=128, seed=seed)
i, j = int(np.nanargmin(adam_small)), int(np.nanargmin(adam_big))
print(f'best lr: {adam_lrs[i]:g} at b=2; {adam_lrs[j]:g} at b=128, '
      f'final loss {adam_big[j]:.3f}')
for rule, k in (('no scaling', 0), ('square root', 3), ('linear', 6)):
    if i + k < len(adam_lrs):
        print(f'{rule:11s}: lr {adam_lrs[i + k]:g} at b=128, '
              f'final loss {adam_big[i + k]:.3f}')
    else:
        print(f'{rule:11s}: lr {adam_lrs[i] * 2 ** k:g}, beyond the grid')
d2l.plot(adam_lrs, [adam_small, adam_big], 'learning rate', 'final loss',
         xscale='log', legend=['b=2', 'b=128'])
best lr: 0.0016 at b=2; 0.0064 at b=128, final loss 0.455
no scaling : lr 0.0016 at b=128, final loss 0.528
square root: lr 0.0128 at b=128, final loss 0.495
linear     : lr 0.1024 at b=128, final loss 2.305

9.8.3.1 选取批量大小的实用步骤

  1. 先喂饱硬件算力:至少增大 \(b\) 直至单步执行时间开始随 \(b\) 线性增长(9.2 节)。
  2. 预热后估计 \(b_{\text{noise}}\):在初始损失骤降之后(例如训练几百步后)测量 noise_scale,因为 \(b_{\text{noise}}\) 在初始化处可能极小,随后在训练中增长 \(1\text{--}2\) 个数量级,正如 TinyLM 所见(这正是 GPT-3 (Brown 等 2020年) 等大规模预训练采用批量大小预热攀升的动因)。
  3. 相对 \(b_{\text{crit}} \approx b_{\text{noise}}\) 定位 \(b\):当算力/数据是瓶颈时,选 \(b \lesssim 0.3\,b_{\text{crit}}\);当跨并行加速器的挂钟时间是瓶颈时,选 \(b \approx b_{\text{crit}}\)(此处 \(S = 2S_{\min}\) 且 \(E = 2E_{\min}\)),避免 \(b \gg b_{\text{crit}}\)。
  4. 按 式 9.8.6 缩放 \(\eta\):在 \(b_{\text{crit}}\) 以下,SGD/动量法按 \(\eta \propto b\) 缩放,AdamW 按 \(\eta \propto \sqrt{b}\) 缩放,并配合线性预热(9.7.3 节)。

9.8.4 小结

梯度噪声尺度 \(b_{\text{noise}} = \operatorname{tr}(\boldsymbol{\Sigma}) / \|\nabla f\|^2\) 标定了采样噪声功率等于信号功率的批量大小,无需遍历全量数据集,仅凭两个批量大小 \(b_{\text{s}} < b_{\text{l}}\) 处的平方梯度范数即可在线估计(式 9.8.1)。在调优学习率下,达到目标损失所需的步数 \(S(b)\) 与样本数 \(E(b) = b\,S(b)\) 围绕拐点 \(b_{\text{crit}} \approx b_{\text{noise}}\) 遵循双曲权衡 \(S(b)/S_{\min} = 1 + b_{\text{crit}}/b\) 与 \(E(b)/E_{\min} = 1 + b/b_{\text{crit}}\),将数据高效的小批量区间(\(b \ll b_{\text{crit}}\))与步数饱和的大批量区间(\(b \gg b_{\text{crit}}\))分隔开来。在 \(b_{\text{crit}}\) 以下,最优学习率对 SGD 与动量法按线性缩放(\(\eta \propto b\)),对 Adam 与 AdamW 按平方根缩放(\(\eta \propto \sqrt{b}\)),一旦 \(b\) 越过 \(b_{\text{crit}}\) 便趋于平缓。

9.8.5 练习

  1. 学习率不变时增大批量大小。利用 式 9.8.3 与 式 9.8.4 证明:若将 \(\eta\) 固定在 \(\eta_0 = \eta_{\text{opt}}(b_0)\) 而把批量大小增至 \(b > b_0\),单步保证降幅仅提高 \(2 - (1 + b_{\text{noise}}/b)/(1 + b_{\text{noise}}/b_0) < 2\) 倍,即便 \(b \to \infty\) 也绝不会超过两倍。

  2. 时间最优对比算力最优批量大小。若批量大小 \(b\) 的单步挂钟耗时为 \(t(b) = t_0(1 + b/b_{\text{sat}})\),利用 式 9.8.5 推导最小化总挂钟时间 \(T(b) = t(b)S(b)\) 的批量大小 \(b^\star\),并计算其数据额外开销 \(E(b^\star)/E_{\min}\)。

  3. [code] 信号与噪声随训练的演化。修改 noise_scale 使其分别返回 \(\operatorname{tr}\boldsymbol{\Sigma}\)、\(\|\nabla f\|^2\) 及其比值 \(b_{\text{noise}}\),在 TinyLM 的第 \(0, 25, 50, 100, 200, 500, 1000, 2000, 3000\) 步追踪三者,验证 \(b_{\text{noise}}\) 的 \(100\times\) 增长主要由信号 \(\|\nabla f\|^2\) 下降而非 \(\operatorname{tr}\boldsymbol{\Sigma}\) 上升驱动。

  4. [code] 越过临界批量大小继续缩放。将 9.8.3 节 的 TinyLM 达标步数扫描扩展至 \(b = 1{,}024\),对比继续按平方根规则 \(\eta \propto \sqrt{b}\) 缩放与将 \(\eta\) 封顶于 \(b = 256\) 处的取值,解释为何越过 \(b_{\text{crit}}\) 后继续放大 \(\eta\) 会损害收敛。

讨论