13.4  显存与精度

前几节探讨的是一个训练步能跑多快;但如果这一步根本装不进 GPU 显存,它就根本跑不起来。用 fp32 Adam 训练我们的 1B 参数 GPT 时,每个参数需保存四个 fp32 数值——权重、梯度以及 Adam 的两个矩估计——在读取单个词元之前,就已经占去了 24 GiB RTX 4090 中的 \(16N \approx 15.1\) GiB。余下的约 9 GiB 必须存放前向传播为反向传播保留的激活值,每个词元需占数兆字节。结果单卡只能装下两三条 1,024 词元的序列,而大语言模型的全局批量通常高达五十万至数百万词元 (Brown 等 2020年)。

一个训练步的显存占用由正比于 \(N\) 的固定参数项和正比于词元数 \(n\) 的激活项构成。本节将为我们的 GPT 核算这两项,并与实测峰值显存核对,随后研究三项作用于激活项或微批量大小的技术:混合精度(以 16 位执行计算)、激活检查点(在反向传播中重计算激活值而非存储它们)以及梯度累积(将大全局批量拆分为顺序执行的微批量)。三者均不能缩小 \(16N\) 字节的参数状态;将该状态分片到多块 GPU 则是 13.7 节 的主题。

import os
import re
from torch.utils.checkpoint import checkpoint
# Detach PyTorch's profiler from the GPU when a profile ends; without this,
# every kernel launch after the first profile stays about 30% slower
os.environ['TEARDOWN_CUPTI'] = '1'
import re

13.4.1 训练步的显存构成

13.4.1.1 每参数显存

参数显存取决于优化器:普通 fp32 SGD 保存权重与梯度(每参数 8 字节),带动量的 SGD 增加速度项(12 字节),Adam 则保存两个矩估计(每参数 16 字节,5.7.3.2 节)。混合精度训练将这四份都保留在 fp32 中,并在单步期间额外持有一份 16 位权重副本(每参数 18 字节)。

我们的参考模型是 d2l.GPT(11.2 节):宽度 \(d = 2048\)、16 个头、\(L = 18\) 个前置规范化 SwiGLU 模块、词表 \(V = 50{,}257\) 以及可学习位置嵌入。每个模块含约 \(12d^2 \approx 50\)M 参数(18 个模块共约 0.9B,加上共享权重的词元嵌入约 0.1B)。在仅追踪形状的元设备上检视模型,无需分配 4 GB 权重即可确认 \(N\)(5.2.2.2 节):

config = dict(vocab_size=50257, num_hiddens=2048, num_heads=16,
              num_blks=18, pos='learned')
with torch.device('meta'):  # Shapes and dtypes only, no data
    model = d2l.GPT(**config)
N = d2l.num_params(model)
print(f'{N / 1e9:.2f} billion parameters, 16N = {16 * N / 2**30:.1f} GiB')
1.01 billion parameters, 16N = 15.1 GiB
config = dict(vocab_size=50257, num_hiddens=2048, num_heads=16,
              num_blks=18, pos='learned')
key = d2l.get_key()
model = nnx.eval_shape(lambda: d2l.GPT(**config, rngs=nnx.Rngs(key)))
N = d2l.num_params(model)
print(f'{N / 1e9:.2f} billion parameters, 16N = {16 * N / 2**30:.1f} GiB')
1.01 billion parameters, 16N = 15.1 GiB

13.4.1.2 每词元显存

前向传播期间,各层保存反向传播所需的中间激活值;反向传播期间,随着参数梯度逐层生成,这些激活值逐层释放(图 13.4.1)。因此,显存占用在反向传播开始之际达到峰值。

图 13.4.1: 使用 Adam 的训练步显存曲线,以 \(4N\) 字节为单位。权重(\(4N\))与 Adam 矩估计(\(8N\))贯穿整步。激活值在前向传播期间累积、在反向传播期间释放,同时梯度(\(4N\))逐步出现。显存在反向传播开始时达到峰值。

三条规则决定了 Transformer 模块需要为反向传播保存哪些张量:

  1. 线性层 \(\mathbf{y} = \mathbf{W}\mathbf{x}\) 保存其输入 \(\mathbf{x}\)(因为 \(\nabla_{\mathbf{W}} = (\nabla_{\mathbf{y}})\mathbf{x}^\top\))。
  2. 逐元素非线性 \(f\) 保存其输入或输出。
  3. 逐元素乘积 \(\mathbf{p} \odot \mathbf{q}\) 同时保存两个因子。

以宽度 \(d = 2048\) 为单位统计每个词元的保存量:

  • 注意力子层:注意力前 RMSNorm 保存输入(\(d\));QKV 投影保存规范化后的输出(\(d\));融合因果注意力保存 \(\mathbf{Q}, \mathbf{K}, \mathbf{V}\)(\(3d\))及其输出(\(d\),外加每头每词元仅一个标量对数归一化因子,而非 \(T \times T\) 分数矩阵);输出投影保存注意力输出(若别名复用为 \(0\),合并多头时拷贝则为 \(d\))。合计:\(6d\text{--}7d\)。
  • SwiGLU FFN 子层:FFN 前 RMSNorm 保存输入(\(d\));门控投影与升维投影共享规范化输出(\(d\));\(\textrm{SiLU}(\mathbf{g}) \odot \mathbf{u}\) 与降维投影保存门控 \(\mathbf{g}\)、激活后的门控 \(\textrm{SiLU}(\mathbf{g})\)、升维输出 \(\mathbf{u}\) 以及它们的乘积——四个宽度为 \(\tfrac{8}{3}d \approx 10.7d\) 的向量。合计:约 \(12.7d\)。

总计单个融合模块每词元保存 \(18.7d\text{--}19.7d \approx \mathbf{20d}\) 个数值(fp32 下 \(d = 2048\) 时为 160 KiB;对比 Korthikanti 等 (2022年) 中无门控 GPT-3 模块的 \(16d\))。由于融合注意力在反向传播期间在片上重计算其 \(T \times T\) 权重,上述计数中没有任何一项随序列长度 \(T\) 增长。最后,交叉熵损失每词元保存 \(V = 50{,}257\) 个 fp32 对数概率(196 KiB)——比一整层 Transformer 模块还要多。

为了实证核对这份清单,我们先定义 saved_bytes 统计 gpt_loss 反向传播所保留的张量字节总数:

def saved_bytes(f, *args):
    """Bytes of the tensors that autograd keeps for the backward pass of f."""
    storages = {}
    def pack(t):  # Called on every tensor saved for the backward pass
        storages[t.untyped_storage().data_ptr()] = (
            t.untyped_storage().nbytes())
        # A detached alias shares the storage. Returning t itself would form
        # a reference cycle between a saved output and the graph that made
        # it, and the graph, with all its tensors, would never be freed
        return t.detach()
    with torch.autograd.graph.saved_tensors_hooks(pack, lambda t: t):
        f(*args)
    return sum(storages.values())

def gpt_loss(model, X, bf16=False):
    """Cross-entropy of a GPT's predictions, with the inputs as targets."""
    with torch.autocast(X.device.type, torch.bfloat16, enabled=bf16):
        return F.cross_entropy(model(X).flatten(0, 1), X.flatten())
def saved_bytes(f, *args):
    """Bytes of the arrays that the backward pass of f keeps."""
    _, f_vjp = jax.vjp(f, *args)  # The leaves of f_vjp are the saved arrays
    return sum(x.nbytes for x in jax.tree_util.tree_leaves(f_vjp))

def gpt_loss(model, X):
    """Cross-entropy of a GPT's predictions, with the inputs as targets."""
    logits = model(X).astype(jnp.float32)
    return optax.softmax_cross_entropy_with_integer_labels(logits, X).mean()

通过在批量大小 \(b \in \{1, 2\}\) 上评估 1 块与 2 块 GPT 模型的 saved_bytes,bytes_per_token 将单个 Transformer 模块的每词元边际激活显存(block)与嵌入、输出头及损失部分(head)分离开来:

def bytes_per_token(config, bf16=False, num_steps=1024):
    """Bytes stored per token by one block, and by the rest of a GPT."""
    gpu, per_token = d2l.try_gpu(), []
    for L in (1, 2):  # GPTs with one and with two blocks
        model = d2l.GPT(**{**config, 'num_blks': L}).to(gpu)
        X1, X2 = (torch.randint(0, config['vocab_size'], (b, num_steps),
                                device=gpu) for b in (1, 2))
        per_token.append((saved_bytes(gpt_loss, model, X2, bf16)
                          - saved_bytes(gpt_loss, model, X1, bf16))
                         / num_steps)
    return per_token[1] - per_token[0], 2 * per_token[0] - per_token[1]

block, head = bytes_per_token(config)
print(f'one block: {block / 2**10:.0f} KiB per token '
      f'({block / (4 * config["num_hiddens"]):.1f} fp32 values of width d)')
print(f'embedding, output layer, and loss: {head / 2**10:.0f} KiB per token')
one block: 149 KiB per token (18.7 fp32 values of width d)
embedding, output layer, and loss: 212 KiB per token
def to_bf16(model):
    """Make the linear layers of `model` compute in bf16; parameters stay
    fp32."""
    for _, layer in nnx.iter_graph(model):
        if isinstance(layer, nnx.Linear):
            layer.dtype = jnp.bfloat16
    return model

def bytes_per_token(config, bf16=False, num_steps=1024):
    """Bytes stored per token by one block, and by the rest of a GPT."""
    per_token = []
    for L in (1, 2):  # GPTs with one and with two blocks
        model = d2l.GPT(**{**config, 'num_blks': L},
                        rngs=nnx.Rngs(d2l.get_key()))
        model = to_bf16(model) if bf16 else model
        # The structure, the weights, and the other state of the model;
        # nnx.merge puts them back together, so the loss is a function of
        # the weights
        graphdef, params, rest = nnx.split(model, nnx.Param, ...)
        loss = lambda params, X: gpt_loss(nnx.merge(graphdef, params, rest), X)
        X1, X2 = (jax.random.randint(d2l.get_key(), (b, num_steps), 0,
                                     config['vocab_size']) for b in (1, 2))
        per_token.append((saved_bytes(loss, params, X2)
                          - saved_bytes(loss, params, X1)) / num_steps)
    return per_token[1] - per_token[0], 2 * per_token[0] - per_token[1]

block, head = bytes_per_token(config)
print(f'one block: {block / 2**10:.0f} KiB per token '
      f'({block / (4 * config["num_hiddens"]):.1f} fp32 values of width d)')
print(f'embedding, output layer, and loss: {head / 2**10:.0f} KiB per token')
one block: 232 KiB per token (29.0 fp32 values of width d)
embedding, output layer, and loss: 228 KiB per token

由于 scaled_dot_product_attention、RMSNorm 与 SiLU 均作为单个融合内核运行,PyTorch 精确存储了理论最小值:每模块 \(18.7d\) 个数值(149 KiB),嵌入、输出投影与损失合计 212 KiB。

在 XLA 编译之前,jax.vjp 记录了每模块 \(29.0d\) 个数值(232 KiB),因为 nnx.RMSNorm 与 jax.nn.silu 是以复合逐元素表达式编写的,其中间数组保留在原始 VJP 残差中。编译后的程序是否全部保留它们取决于 XLA 的内存规划,下文我们将直接查看。

13.4.1.3 显存预算

将参数状态(当梯度跨微批量持久保留时为 \(16N\) 字节)与每模块每词元 \(a\) 字节、以及嵌入/输出头/损失的每词元 \(a_\textrm{out}\) 字节相加,便得 \(n\) 个词元的单步显存预算:

\[ M(n) \approx 16N + n \, (L a + a_\textrm{out}) \;\leq\; M_\textrm{GPU}. \tag{13.4.1}\]

对于 24 GiB 显卡上的 18 块 GPT(\(16N = 15.1\) GiB,留给激活值 8.9 GiB),原始计数预测:

\(La + a_\textrm{out} \approx 2.8\) MiB/词元(约 3,200 词元,即 3 条 1,024 词元序列)。

\(La + a_\textrm{out} \approx 4.3\) MiB/词元(约 2,100 词元,即 2 条 1,024 词元序列)。

13.4.1.4 实测峰值显存

为了看清反向传播在已存激活值之外还临时分配了多少显存,我们在 1,024 至 8,192 词元上测量 2 块版 GPT 超出权重部分的峰值显存。

gpu, V = d2l.try_gpu(), config['vocab_size']
model = d2l.GPT(**{**config, 'num_blks': 2}).to(gpu)
gpt_loss(model, torch.randint(0, V, (1, 1024), device=gpu)).backward()
peaks = {}  # The step above was a warm-up
for n in (1024, 2048, 4096, 8192):  # Tokens per step, in sequences of 1,024
    X = torch.randint(0, V, (n // 1024, 1024), device=gpu)
    model.zero_grad(set_to_none=True)
    peaks[n] = d2l.peak_memory(lambda: gpt_loss(model, X).backward())
    print(f'{n:5d} tokens: peak {peaks[n] / 2**30:.2f} GiB above the weights')
for n in (2048, 4096):  # Growth per token from n to 2n tokens
    slope = (peaks[2 * n] - peaks[n]) / n
    print(f'{n:5d} to {2 * n:5d} tokens: measured {slope / 2**10:.0f} KiB '
          f'per token; counted {(2 * block + head) / 2**10:.0f} KiB')
 1024 tokens: peak 1.53 GiB above the weights
 2048 tokens: peak 1.77 GiB above the weights
 4096 tokens: peak 3.53 GiB above the weights
 8192 tokens: peak 7.06 GiB above the weights
 2048 to  4096 tokens: measured 905 KiB per token; counted 511 KiB
 4096 to  8192 tokens: measured 903 KiB per token; counted 511 KiB
key = d2l.get_key()
model = nnx.eval_shape(
    lambda: d2l.GPT(**{**config, 'num_blks': 2}, rngs=nnx.Rngs(key)))
graphdef, params, rest = nnx.split(model, nnx.Param, ...)
grad_fn = jax.jit(jax.grad(
    lambda params, rest, X: gpt_loss(nnx.merge(graphdef, params, rest), X)))
peaks = {}
for n in (1024, 2048, 4096, 8192):  # Tokens per step, in sequences of 1,024
    X = jax.ShapeDtypeStruct((n // 1024, 1024), jnp.int32)
    plan = grad_fn.lower(params, rest, X).compile().memory_analysis()
    peaks[n] = plan.output_size_in_bytes + plan.temp_size_in_bytes
    print(f'{n:5d} tokens: peak {peaks[n] / 2**30:.2f} GiB above the weights')
for n in (2048, 4096):  # Growth per token from n to 2n tokens
    slope = (peaks[2 * n] - peaks[n]) / n
    print(f'{n:5d} to {2 * n:5d} tokens: planned {slope / 2**10:.0f} KiB '
          f'per token; counted {(2 * block + head) / 2**10:.0f} KiB')
 1024 tokens: peak 1.23 GiB above the weights
 2048 tokens: peak 1.63 GiB above the weights
 4096 tokens: peak 3.09 GiB above the weights
 8192 tokens: peak 5.79 GiB above the weights
 2048 to  4096 tokens: planned 749 KiB per token; counted 692 KiB
 4096 to  8192 tokens: planned 691 KiB per token; counted 692 KiB

在较小规模下固定开销依然可见;一旦固定开销可忽略,峰值便随词元数成比例增长,而每词元增量正是应与前述清单核对的数值。

实测峰值每词元增长约 905 KiB,比我们统计的 511 KiB 多出 393 KiB。多余部分出现在反向传播启动之际、全部前向激活仍存活之时:交叉熵反向传播同时物化了关于对数概率的梯度与关于 logit 的梯度——两个宽度为 \(V = 50{,}257\) 的 fp32 临时张量(在已存张量计数之上多出 \(8V \approx 393\) KiB/词元)。

从 4,096 到 8,192 词元,XLA 规划峰值每词元增长约 690 KiB,与原始 VJP 计数的 692 KiB 一致。因此编译后的程序每词元所需显存与 jax.vjp 记录的相同,损失处没有可测的额外峰值,该计数可直接作为预算。

我们可以借助 PyTorch 的分配器历史 API 可视化 4,096 词元上一步 Adam 的完整分配时间线:

X = torch.randint(0, V, (4, 1024), device=gpu)
opt = torch.optim.Adam(model.parameters())
gpt_loss(model, X).backward()  # A first step creates the moment estimates
opt.step()
opt.zero_grad(set_to_none=True)

# _snapshot, _record_memory_history and the keys of their records are a
# private API of PyTorch 2.11 and may change between versions
events = lambda: torch.cuda.memory._snapshot()['device_traces'][0]
start = torch.cuda.memory_allocated()
torch.cuda.memory._record_memory_history()  # Record from here on
loss = gpt_loss(model, X)
forward_end = len(events())
loss.backward()
backward_end = len(events())
opt.step()
opt.zero_grad(set_to_none=True)
trace = events()
torch.cuda.memory._record_memory_history(enabled=None)

在 trace 上累加带符号字节变化(alloc 减 free_completed),并按 forward_end 与 backward_end 分段,即可绘制单步三个阶段的实时显存轨迹:

sign = {'alloc': 1, 'free_completed': -1}  # Other actions change nothing
sizes = torch.tensor([sign.get(e['action'], 0) * e['size'] for e in trace])
series = ((start + sizes.cumsum(0)) / 2**30).tolist()
bounds = [0, forward_end, backward_end, len(trace)]
phases = list(zip(bounds[:-1], bounds[1:]))
d2l.plot([list(range(a, b)) for a, b in phases],
         [series[a:b] for a, b in phases], 'allocation event',
         'allocated (GiB)', legend=['forward', 'backward', 'optimizer step'])

轨迹从 \(12N\)(权重与两个 Adam 矩)起步,前向传播期间逐模块线性攀升,在 logit 与反向传播起点处冲上尖峰,随后随着激活值释放与梯度分配呈阶梯状回落。

13.4.2 混合精度

混合精度训练(5.5 节)将主权重、梯度、优化器矩、规范化层、残差流以及损失保留在 fp32 中,同时以 16 位浮点数执行矩阵乘法与中间激活计算(bf16 与 fp32 共享 8 位指数范围,无需损失缩放;fp16 则需配合损失缩放,5.5.3.3 节)。

由于每个模块中进入规范化层的两条残差流输入保持在 fp32(4 字节),而每模块 \(20d\) 个保存值中其余 18 项降为 bf16(2 字节),单个模块的已存激活大约缩小至 fp32 大小的 \((2 \cdot 4 + 18 \cdot 2) / (20 \cdot 4) = 0.55\):

block16, head16 = bytes_per_token(config, bf16=True)
print(f'one block: {block16 / 2**10:.0f} KiB per token in bf16, '
      f'{block16 / block:.2f} of fp32')
print(f'embedding, output layer, and loss: {head16 / 2**10:.0f} KiB per token')
one block: 87 KiB per token in bf16, 0.58 of fp32
embedding, output layer, and loss: 306 KiB per token
block16, head16 = bytes_per_token(config, bf16=True)
print(f'one block: {block16 / 2**10:.0f} KiB per token in bf16, '
      f'{block16 / block:.2f} of fp32')
print(f'embedding, output layer, and loss: {head16 / 2**10:.0f} KiB per token')
one block: 140 KiB per token in bf16, 0.60 of fp32
embedding, output layer, and loss: 228 KiB per token

单个模块的激活字节数降至 fp32 时的 \(0.58\text{--}0.60\)。然而,在单步期间持有 bf16 权重副本会使固定参数显存从 \(16N = 15.1\) GiB 增至 \(18N = 17.0\) GiB,留给激活的空间仅剩 7.0 GiB。激活节省与额外权重副本基本相互抵消,使 24 GiB 显卡上的最大词元容量仅增加 15–27%。

bf16 混合精度的首要收益是速度而非容量:在 RTX 4090 上,bf16 张量核心达 165 TFLOP/s,是 tf32 与 fp32 82.6 TFLOP/s 的两倍。为了将张量核心的效应(tf32 对比标量 fp32)与 16 位操作数的效应(bf16 对比 tf32)分离开来,我们在 2,048 样本批量上对一个计算受限的宽度 8,192 三层 MLP 的单步 SGD 做基准测试(每步 \(1.1 \times 10^{12}\) FLOPs:82.6 TFLOP/s 下 Roofline 下界 13.3 ms,165 TFLOP/s 下为 6.7 ms,外加访存受限 SGD 更新约 1.3 ms)。

sizes = [(64 * 64, 8192), (8192, 8192), (8192, 10)]  # (inputs, outputs)
mlp = nn.Sequential(nn.Linear(*sizes[0], bias=False), nn.ReLU(),
                    nn.Linear(*sizes[1], bias=False), nn.ReLU(),
                    nn.Linear(*sizes[2], bias=False)).to(gpu)
for layer in mlp[::2]:  # Weights drawn from N(0, 0.02^2)
    nn.init.normal_(layer.weight, std=0.02)
X_mlp = torch.randn(2048, 64 * 64, device=gpu)
y_mlp = torch.randint(0, 10, (2048,), device=gpu)
opt = torch.optim.SGD(mlp.parameters(), lr=0.01)

def step(bf16):
    with torch.autocast(X_mlp.device.type, torch.bfloat16, enabled=bf16):
        l = F.cross_entropy(mlp(X_mlp), y_mlp)
    l.backward()
    opt.step()
    opt.zero_grad(set_to_none=True)
def net_fn(params, X, dtype):
    h = X.astype(dtype)
    for W in params[:-1]:
        h = jax.nn.relu(h @ W.astype(dtype))
    return h @ params[-1].astype(dtype)

sizes = [(64 * 64, 8192), (8192, 8192), (8192, 10)]  # (inputs, outputs)
mlp_params = [jax.random.normal(k, s) * 0.02
              for k, s in zip(jax.random.split(d2l.get_key(), 3), sizes)]
X_mlp = jax.random.normal(d2l.get_key(), (2048, 64 * 64))
y_mlp = jax.random.randint(d2l.get_key(), (2048,), 0, 10)

def loss_fn(params, X, y, dtype):
    logits = net_fn(params, X, dtype).astype(jnp.float32)
    return optax.softmax_cross_entropy_with_integer_labels(logits, y).mean()

def sgd_step(params, X, y, dtype):
    grads = jax.grad(loss_fn)(params, X, y, dtype)
    return [p - 0.01 * g for p, g in zip(params, grads)]

step = jax.jit(sgd_step, static_argnums=3)
args = mlp_params, X_mlp, y_mlp

接下来,我们精确统计该 MLP 前向与反向矩阵乘的乘加次数(macs)与总 flops,并定义 report 以毫秒和 TFLOP/s 评测每种精度格式:

# Two FLOPs per multiply-add, in the forward pass, the weight gradients, and
# the input gradients of every layer but the first
macs = sum(i * o for i, o in sizes)  # Per example and pass
flops = 2 * len(X_mlp) * (3 * macs - sizes[0][0] * sizes[0][1])
print(f'{flops:.2e} FLOPs per step')

def report(desc, f):
    """Print the time per call of f and the arithmetic rate it achieves."""
    t = d2l.Benchmark(f).time
    print(f'{desc}: {1000 * t:5.2f} ms, {flops / t / 1e12:3.0f} TFLOP/s')
1.10e+12 FLOPs per step
# Two FLOPs per multiply-add, in the forward pass, the weight gradients, and
# the input gradients of every layer but the first
macs = sum(i * o for i, o in sizes)  # Per example and pass
flops = 2 * len(X_mlp) * (3 * macs - sizes[0][0] * sizes[0][1])
print(f'{flops:.2e} FLOPs per step')

def report(desc, f):
    """Print the time per call of f and the arithmetic rate it achieves."""
    t = d2l.Benchmark(f).time
    print(f'{desc}: {1000 * t:5.2f} ms, {flops / t / 1e12:3.0f} TFLOP/s')
1.10e+12 FLOPs per step

现在我们在严格标量 'fp32'、张量核心 'tf32' 以及混合精度 'bf16' 上运行 report:

torch.set_float32_matmul_precision('highest')  # True fp32
report('fp32', lambda: step(False))
torch.set_float32_matmul_precision('high')  # fp32 matmuls may use tf32
report('tf32', lambda: step(False))
report('bf16', lambda: step(True))
fp32: 23.15 ms,  48 TFLOP/s
tf32: 15.01 ms,  73 TFLOP/s
bf16:  9.68 ms, 114 TFLOP/s
with jax.default_matmul_precision('highest'):  # True fp32
    report('fp32', lambda: step(*args, jnp.float32))
report('tf32', lambda: step(*args, jnp.float32))
report('bf16', lambda: step(*args, jnp.bfloat16))
fp32: 21.72 ms,  51 TFLOP/s
tf32: 14.30 ms,  77 TFLOP/s
bf16:  8.28 ms, 133 TFLOP/s

标量单元上的纯 fp32 仅达到 82.6 TFLOP/s 峰值的约 60%,因为每次乘加与地址计算都要争抢指令发射槽;张量核心上的 tf32 达到同一峰值的约 90%,在不改变存储类型的情况下将步时砍去三分之一。从 tf32 切换到 bf16 会使单步再快 \(1.5\text{--}1.75\times\)(接近 \(6.7 + 1.3 = 8.0\) ms 的算力下界加更新耗时,因为 fp32 SGD 更新与权重类型转换不会缩小)。

13.4.3 激活检查点

要成倍扩大单卡装得下的词元数,每步就必须少存激活值。激活检查点(5.7.3.3 节,(Chen 等 2016年))在前向传播期间仅保存每个 Transformer 模块的输入(\(d\) 个 fp32 数值,即每词元 \(4d\) 字节),而在反向传播期间逐块重计算模块内部激活。这以额外一次前向传播(约多出 33% 计算量,即每词元 \(8N\) 而非 \(6N\) FLOPs)为代价,将 \(L\) 个模块的每词元峰值显存从 \(L a + a_\textrm{out} + \Delta\) 压低至至多:

\[ L \cdot 4d + a + a_\textrm{out} + \Delta, \]

其中 \(a\) 为当前正在重计算的单个模块,而 \(\Delta\) 为实测峰值超出清单的余量(13.4.1.4 节)。

M_gpu, d, L = 24 * 2**30, config['num_hiddens'], config['num_blks']
slope = (peaks[8192] - peaks[4096]) / 4096  # Growth per token, measured
excess = slope - (2 * block + head)  # Measured peak above the count
budgets = {  # Configuration: (fixed bytes, bytes per token at the peak)
    'fp32, count': (16 * N, L * block + head),
    'fp32, measured': (16 * N, L * block + head + excess),
    'bf16, measured': (18 * N, L * block16 + head16 + excess),
    'fp32, checkpointing': (16 * N, L * 4 * d + block + head + excess),
    'bf16, checkpointing': (18 * N, L * 4 * d + block16 + head16 + excess)}
for name, (fixed, per_token) in budgets.items():  # M(n) <= M_gpu
    print(f'{name:19s}: {per_token / 2**20:.2f} MiB per token, room for '
          f'{(M_gpu - fixed) / per_token:6,.0f} tokens')
fp32, count        : 2.83 MiB per token, room for  3,229 tokens
fp32, measured     : 3.22 MiB per token, room for  2,844 tokens
bf16, measured     : 2.21 MiB per token, room for  3,272 tokens
fp32, checkpointing: 0.88 MiB per token, room for 10,435 tokens
bf16, checkpointing: 0.91 MiB per token, room for  7,956 tokens
M_gpu, d, L = 24 * 2**30, config['num_hiddens'], config['num_blks']
slope = (peaks[8192] - peaks[4096]) / 4096  # Growth per token, measured
excess = slope - (2 * block + head)  # Measured peak above the count
budgets = {  # Configuration: (fixed bytes, bytes per token at the peak)
    'fp32, count': (16 * N, L * block + head),
    'fp32, measured': (16 * N, L * block + head + excess),
    'bf16, measured': (18 * N, L * block16 + head16 + excess),
    'fp32, checkpointing': (16 * N, L * 4 * d + block + head + excess),
    'bf16, checkpointing': (18 * N, L * 4 * d + block16 + head16 + excess)}
for name, (fixed, per_token) in budgets.items():  # M(n) <= M_gpu
    print(f'{name:19s}: {per_token / 2**20:.2f} MiB per token, room for '
          f'{(M_gpu - fixed) / per_token:6,.0f} tokens')
fp32, count        : 4.30 MiB per token, room for  2,127 tokens
fp32, measured     : 4.30 MiB per token, room for  2,128 tokens
bf16, measured     : 2.68 MiB per token, room for  2,691 tokens
fp32, checkpointing: 0.59 MiB per token, room for 15,529 tokens
bf16, checkpointing: 0.50 MiB per token, room for 14,461 tokens

启用逐块检查点后,全部 18 个模块合计每词元仅存 \(18 \times 8 = 144\) KiB(甚至少于单独的输出层与损失),使词元预算扩大三倍以上(达到 10,000–15,000 词元)。注意在检查点模式下,bf16 实际装下的词元反而少于 fp32:额外的 \(2N\) 字节 bf16 权重副本,加上(在 PyTorch 中)更大的 bf16 输出层与损失,超过了单个重计算模块省下的激活显存。此时,输出 logit 与交叉熵损失成为每词元显存的主导项;将输出投影与损失按词元分块包裹在独立检查点内计算,仅需增加 \(2dV / (6N) \approx 3\%\) 的 FLOPs 即可消除这一瓶颈(6)。

我们在 4 块堆叠、两条 1,024 词元序列上实测逐块检查点(4 个模块输入加最终输出应保存 \(5 \times 4d = 40\) KiB/词元):

blocks = d2l.GPT(**{**config, 'num_blks': 4}).to(gpu).blks
def stack(H, remat):
    for blk in blocks:
        H = checkpoint(blk, H, use_reentrant=False) if remat else blk(H)
    return H.square().mean()

d = config['num_hiddens']
H1, H2 = (torch.randn(b, 1024, d, device=gpu, requires_grad=True)
          for b in (1, 2))
for remat in (False, True):
    stored = (saved_bytes(stack, H2, remat)
              - saved_bytes(stack, H1, remat)) / 1024
    stack(H2, remat).backward()  # Warm-up; allocates the gradients
    peak = d2l.peak_memory(lambda: stack(H2, remat).backward())
    t = d2l.Benchmark(lambda: stack(H2, remat).backward()).time
    print(f'checkpointing={remat!s:5}: stores {stored / 2**10:4.0f} KiB per '
          f'token, peak {peak / 2**30:.2f} GiB, {1000 * t:.0f} ms per step')
checkpointing=False: stores  606 KiB per token, peak 1.25 GiB, 47 ms per step
checkpointing=True : stores   40 KiB per token, peak 0.42 GiB, 59 ms per step
blocks = [nnx.split(blk, nnx.Param, ...) for blk in d2l.GPT(
    **{**config, 'num_blks': 4}, rngs=nnx.Rngs(d2l.get_key())).blks]
blk_params = [p for _, p, _ in blocks]
def stack(params, H, remat):
    def block(graphdef, p, rest, H):  # A block as a function of its weights
        return nnx.merge(graphdef, p, rest)(H)
    if remat:
        # On a CPU, XLA's default scheduler runs the recomputations early,
        # so that they coexist and the saving vanishes; setting XLA_FLAGS to
        # --xla_cpu_enable_concurrency_optimized_scheduler=false before JAX
        # starts restores it there
        block = jax.checkpoint(block, static_argnums=0)
    for (graphdef, _, rest), p in zip(blocks, params):
        H = block(graphdef, p, rest, H)
    return (H ** 2).mean()

d = config['num_hiddens']
H1, H2 = (jax.random.normal(d2l.get_key(), (b, 1024, d)) for b in (1, 2))
for remat in (False, True):
    f = lambda params, H: stack(params, H, remat)
    stored = (saved_bytes(f, blk_params, H2)
              - saved_bytes(f, blk_params, H1)) / 1024
    stack_grad = jax.jit(jax.grad(f))
    peak = d2l.peak_memory(stack_grad, blk_params, H2)
    t = d2l.Benchmark(lambda: stack_grad(blk_params, H2)).time
    print(f'checkpointing={remat!s:5}: stores {stored / 2**10:4.0f} KiB per '
          f'token, peak {peak / 2**30:.2f} GiB, {1000 * t:.0f} ms per step')
checkpointing=False: stores  936 KiB per token, peak 0.78 GiB, 45 ms per step
checkpointing=True : stores   40 KiB per token, peak 0.45 GiB, 57 ms per step

检查点将已存张量精准压至预测的 40 KiB/词元,大幅降低峰值激活显存,步时仅增加约 25%(低于一次额外前向传播的 33% 上界)。除了重算整个模块外,选择性重计算 (Korthikanti 等 2022年) 保留昂贵的矩阵乘输出,只重计算诸如 SwiGLU 门控乘积之类廉价的逐元素激活(5)。

13.4.4 梯度累积

为了在不增加激活存储的前提下达到数十万词元的全局批量 \(B_\textrm{global} = m \, B_\textrm{micro}\),梯度累积将全局批量拆分为 \(m\) 个顺序微批量,累加它们的梯度(将每个微批量的平均损失除以 \(m\)),最后只运行一次优化器。

尽管梯度累积执行的算术量与单个大批量完全相同,但首个微批量之后的每个微批量都要读取运行中的梯度累加器与新梯度并写出两者之和(\(12N\) 字节访存流量),而该微批量自身在 \(n\) 个词元上执行 \(6Nn\) FLOPs。相对于峰值计算时间,这份累加器流量的开销比例为:

\[ \frac{12N / \beta}{6Nn / P} = \frac{2 I^*}{n}, \]

其中 \(I^* = P/\beta\) 为屋脊拐点(13.1 节)。在 tf32(\(I^* = 82\))与 \(n = 1{,}024\) 词元微批量下,其余 \(m - 1\) 个累积微批量各自付出约 16% 的额外开销;到 \(n = 4{,}096\) 词元时则降至 4%。

我们在 2 块 GPT 上对比将 4,096 词元作为 1 批处理与拆分为 \(m = 4\) 个 1,024 词元微批量,同时验证数值等价性与显存/时间开销:

X = torch.randint(0, V, (4, 1024), device=gpu)  # 4,096 tokens per step

def accumulate(model, X, m):
    """Gradient of the loss on X in .grad, accumulated over m micro-batches."""
    model.zero_grad(set_to_none=True)
    for Xb in X.chunk(m):
        (gpt_loss(model, Xb) / m).backward()  # / m: the loss averages

accumulate(model, X, 1)
full = [p.grad.clone() for p in model.parameters()]  # One-batch gradient
for m in (1, 4):
    model.zero_grad(set_to_none=True)
    peak = d2l.peak_memory(accumulate, model, X, m)
    assert max((p.grad - g).norm() / g.norm()
               for p, g in zip(model.parameters(), full)) < 1e-2
    f = lambda: accumulate(model, X, m)
    times = 1000 * np.array([d2l.Benchmark(f).time for _ in range(5)])  # ms
    kernels = d2l.kernel_times(f)        # Device ms per step, per kernel
    busy = sum(kernels.values())
    products = sum(ms for name, ms in kernels.items()
                   if re.search(d2l.PRODUCT_KERNELS, name, re.I))
    print(f'{m} x {4096 // m:4d} tokens: peak {peak / 2**30:.2f} GiB above '
          f'the weights, {np.median(times):.0f} ms per step '
          f'({times.min():.0f} to {times.max():.0f}), device busy '
          f'{busy:.0f} ms\n{"":16s}matrix products {products:.0f} ms, '
          f'other kernels {busy - products:.0f} ms')
1 x 4096 tokens: peak 3.53 GiB above the weights, 83 ms per step (83 to 83), device busy 83 ms
                matrix products 69 ms, other kernels 13 ms
4 x 1024 tokens: peak 1.92 GiB above the weights, 99 ms per step (99 to 99), device busy 99 ms
                matrix products 74 ms, other kernels 25 ms
model = d2l.GPT(**{**config, 'num_blks': 2}, rngs=nnx.Rngs(d2l.get_key()))
graphdef, params, rest = nnx.split(model, nnx.Param, ...)
X = jax.random.randint(d2l.get_key(), (4, 1024), 0, config['vocab_size'])

def accumulate(params, rest, X, m):
    """Gradient of the loss on X, accumulated over m micro-batches."""
    loss = lambda params, Xb: gpt_loss(nnx.merge(graphdef, params, rest), Xb)
    def add(g, Xb):  # One micro-batch; / m because the loss averages
        g_b = jax.grad(loss)(params, Xb)
        return jax.tree.map(lambda a, b: a + b / m, g, g_b), None
    zeros = jax.tree.map(jnp.zeros_like, params)
    return jax.lax.scan(add, zeros, X.reshape(m, -1, X.shape[-1]))[0]

accumulate = jax.jit(accumulate, static_argnums=3)
full = accumulate(params, rest, X, 1)  # One-batch gradient
for m in (1, 4):
    plan = accumulate.lower(params, rest, X, m).compile().memory_analysis()
    peak = plan.output_size_in_bytes + plan.temp_size_in_bytes
    assert max(jax.tree.leaves(jax.tree.map(
        lambda a, b: jnp.linalg.norm(a - b) / jnp.linalg.norm(b),
        accumulate(params, rest, X, m), full))) < 1e-2
    f = lambda: accumulate(params, rest, X, m)
    times = 1000 * np.array([d2l.Benchmark(f).time for _ in range(5)])  # ms
    kernels = d2l.kernel_times(f)        # Device ms per step, per kernel
    busy = sum(kernels.values())
    products = sum(ms for name, ms in kernels.items()
                   if re.search(d2l.PRODUCT_KERNELS, name, re.I))
    print(f'{m} x {4096 // m:4d} tokens: peak {peak / 2**30:.2f} GiB above '
          f'the weights, {np.median(times):.0f} ms per step '
          f'({times.min():.0f} to {times.max():.0f}), device busy '
          f'{busy:.0f} ms\n{"":16s}matrix products {products:.0f} ms, '
          f'other kernels {busy - products:.0f} ms')
1 x 4096 tokens: peak 3.09 GiB above the weights, 80 ms per step (80 to 80), device busy 80 ms
                matrix products 67 ms, other kernels 13 ms
4 x 1024 tokens: peak 1.43 GiB above the weights, 90 ms per step (89 to 90), device busy 89 ms
                matrix products 69 ms, other kernels 21 ms

超出权重部分的峰值显存大约减半(因为 \(4N = 0.77\) GiB 的持久梯度跨微批量保持分配,而激活显存缩减四倍),步时因累加器加法与较小微批量上略低的张量核心效率而增加 10–20%。因此,最优微批量始终是显存能装下的最大微批量。

13.4.5 选择显存技术

表 13.4.1 按触发症状汇总了各项显存技术。

表 13.4.1: 按症状分类的显存技术、对 式 13.4.1 的影响及其代价。
症状 技术 对显存的影响 代价
矩阵乘主导步时 bf16 混合精度 激活 \(\times 0.6\),固定状态因权重副本 \(+2N\) 8 位有效数字舍入(fp16 还需损失缩放)
合理微批量装不下 激活检查点 每模块已存激活从 \(a\) 降至每词元 \(4d\) 字节 额外一次前向传播(约增时 25–33%)
输出层与损失占主导 分块交叉熵损失 每次仅保留一个词元块的 \(a_\textrm{out}\) 与 \(\Delta\) 额外一次输出投影(约 3% FLOPs)
全局批量超过微批量容量 梯度累积 无;全局批量扩大 \(m\) 倍 累加器流量 \(2I^*/n\);每微批量重复读取权重
仅 \(16N\) 参数状态就塞满单卡 权重、梯度与优化器状态分片(13.7 节) \(k\) 块 GPU 上每卡降至 \(16N/k\) 卡间集合通信

对于单块 RTX 4090 上的 1B 参数 GPT,bf16 混合精度在不开启检查点时即可装下两三条 1,024 词元序列,累积 256 个微批量便能达到 524,288 词元的全局批量。然而在每词元 \(6N\) FLOPs 下,单个全局步需要 \(3.2 \times 10^{15}\) FLOPs——单卡每步至少耗时 19 s,跑完 100,000 步(52B 词元)需要超过三周。单块 GPU 虽能装下 GPT 的一步,但要完成整个训练仍需多块 GPU(13.5 节)。

13.4.6 小结

训练步显存分为固定参数项(fp32 Adam 为 \(16N\) 字节,带 bf16 权重副本为 \(18N\))与每词元激活项。依据三条微分规则(线性层保存输入、逐元素函数保存输入或输出、乘积保存两个因子),一个融合 SwiGLU Transformer 模块每词元保存约 \(20d\) 个数值,交叉熵损失保存 \(V\) 个对数概率;由于损失处的反向临时张量会使峰值超出清单,因此必须实测验证。混合精度在张量核心上加速矩阵乘,而总显存容量几乎不变;激活检查点仅保存模块输入(每词元 \(4d\) 字节),代价是约 25% 额外耗时;梯度累积则由装得下的微批量拼出大全局批量,引入 \(2I^*/n\) 的累加器流量开销。

13.4.7 练习

  1. 峰值的落点。图 13.4.1 将训练步峰值标在反向传播起点。考虑由 \(n\) 个相同层组成的堆叠,每层参数占 \(w\) 字节,前向传播保存 \(a\) 字节激活。假设反向传播开始时不存在梯度,每层反向传播释放其 \(a\) 字节激活并分配 \(w\) 字节参数梯度。
    1. 写出反向传播处理完 \(n\) 层中的 \(j\) 层后,激活与梯度合计占用的字节数。证明当 \(a > w\) 时峰值位于反向传播起点,而当 \(a < w\) 时峰值位于反向传播终点。
    2. 我们 GPT 的一个模块约含 \(12d^2\) 参数,每词元保存约 \(20d\) 个 fp32 数值。每步词元数超过多少时,峰值落在反向传播起点?
    3. 在跨越 \(m\) 个微批量的梯度累积下,第一个微批量的梯度在后续微批量运行期间保持分配。求累积模式下的峰值,以及使累积峰值低于单个整批步的 \(m\) 取值范围。
  2. [code] 优化器步显存。用三种 torch.optim.Adam 配置构建 13.4.1.4 节 中的两块 GPT:foreach=False、默认配置以及 fused=True。
    1. 用每种优化器运行两步。在第二步中,以梯度大小 \(4N\) 为单位测量 opt.step() 期间额外分配的峰值字节数。
    2. 结合三种实现更新参数张量的方式(逐张量、批量多张量逐元素算子,或单个融合内核)解释三组测量结果。优化器步在什么情况下会决定整个训练步的全局峰值?
  3. 累积下的梯度裁剪。裁剪至范数 \(\tau\) 会将 \(\mathbf{g}\) 替换为 \(\mathbf{g} \min(1, \tau / \|\mathbf{g}\|)\)。设 \(\mathbf{g}_1, \ldots, \mathbf{g}_m\) 为已乘以 \(1/m\) 的微批量梯度,使其和 \(\mathbf{g}\) 等于全局批量梯度。
    1. 若循环在将每个 \(\mathbf{g}_i\) 加入累加器前先各自裁剪,累积梯度可能达到的最大范数是多少?逐微批量裁剪何时与全局裁剪一致?
    2. 在因子为 \(S\) 的 fp16 损失缩放下,最后一个微批量结束后累加器保存 \(S \mathbf{g}\)。循环必须按何种顺序执行除以 \(S\) 反缩放、裁剪与优化器步?若 \(S\) 在微批量之间发生变化会出什么问题?
  4. [code] fp16 梯度窗口。● fp16 的 5 位指数使其规格化数范围为 \(2^{-14}\) 到 65,504,非规格化数下探至 \(2^{-24}\)。损失缩放 (Micikevicius 等 2018年) 在 backward() 前将损失乘以 \(S\),之后将梯度除以 \(S\)。使用 13.4.2 节 中的 mlp、X_mlp、y_mlp 及纯 fp32 参考梯度:
    1. 绘制全部非零参考梯度元素的 \(\log_2 |g|\) 直方图,找出能使 99.9% 的缩放后元素 \(Sg\) 落入 fp16 规格化范围的缩放因子 \(S\)。
    2. 对 \(S = 2^0, 2^2, \ldots, 2^{24}\),在 torch.autocast('cuda', dtype=torch.float16) 下计算梯度,除以 \(S\) 反缩放,并绘制相对误差 \(\|\hat{\mathbf{g}} - \mathbf{g}\| / \|\mathbf{g}\|\)。用 torch.bfloat16 重复该过程。在哪个 \(S\) 窗口内 fp16 比 bf16 更精确?为什么?
    3. 若批量大小从 2,048 增至 32,768,\(S\) 的有效窗口会如何移动?
  5. [code] 选择性重计算。● 逐块检查点仅保存每块的输入。通过 checkpoint 的 context_fn 参数传入 torch.utils.checkpoint.create_selective_checkpoint_contexts,可缓存指定算子(如 torch.ops.aten.mm.default)的输出并重计算其余部分。
    1. 针对我们 GPT 的单个模块,列出三种策略下保存的张量与重计算的矩阵乘:完整逐块检查点、缓存所有 mm 输出,以及缓存除 FFN 门控与升维投影之外的全部 mm 输出。
    2. 在 13.4.3 节 的 4 块堆叠上实现后两种策略,比较每词元保存字节数、峰值显存与步时。
  6. [extended] 分块计算损失。●● 在逐块检查点下,我们 GPT 的输出层与交叉熵损失每词元占用的显存超过了全部 18 个模块之和,因为损失为每个词元物化了 \(V = 50{,}257\) 个对数概率及其梯度。
    1. 改写输出投影与交叉熵损失,使其按大小 \(n_c = 1024\) 的词元块分块处理,并将每一块包裹在检查点内,使任意时刻仅存在一个块的 logit 与对数概率。验证损失与梯度与未分块版本一致。
    2. 预测 24 GiB 显卡上 18 块 GPT 结合逐块检查点与分块损失后的最大微批量大小,并在 2 块 GPT 上实测每词元显存斜率与步时。
  1. 峰值的落点。图 13.4.1 将训练步峰值标在反向传播起点。考虑由 \(n\) 个相同层组成的堆叠,每层参数占 \(w\) 字节,前向传播保存 \(a\) 字节激活。假设反向传播开始时不存在梯度,每层反向传播释放其 \(a\) 字节激活并分配 \(w\) 字节参数梯度。
    1. 写出反向传播处理完 \(n\) 层中的 \(j\) 层后,激活与梯度合计占用的字节数。证明当 \(a > w\) 时峰值位于反向传播起点,而当 \(a < w\) 时峰值位于反向传播终点。
    2. 我们 GPT 的一个模块约含 \(12d^2\) 参数,每词元保存约 \(20d\) 个 fp32 数值。每步词元数超过多少时,峰值落在反向传播起点?
    3. 在跨越 \(m\) 个微批量的梯度累积下,第一个微批量的梯度在后续微批量运行期间保持分配。求累积模式下的峰值,以及使累积峰值低于单个整批步的 \(m\) 取值范围。
  2. [code] 优化器步显存。用 optax.adam 将 13.4.1.4 节 中编译好的梯度扩展为完整的 Adam 更新。
    1. 为 512 个词元编译该训练步,并以 \(4N\) 为单位报告 memory_analysis() 返回的 argument_size_in_bytes、output_size_in_bytes 与 temp_size_in_bytes。
    2. 使用覆盖参数与优化器状态的 donate_argnums 重新编译,报告 alias_size_in_bytes,并解释缓冲区捐赠如何改变峰值显存。
  3. 累积下的梯度裁剪。裁剪至范数 \(\tau\) 会将 \(\mathbf{g}\) 替换为 \(\mathbf{g} \min(1, \tau / \|\mathbf{g}\|)\)。设 \(\mathbf{g}_1, \ldots, \mathbf{g}_m\) 为已乘以 \(1/m\) 的微批量梯度,使其和 \(\mathbf{g}\) 等于全局批量梯度。
    1. 若循环在将每个 \(\mathbf{g}_i\) 加入累加器前先各自裁剪,累积梯度可能达到的最大范数是多少?逐微批量裁剪何时与全局裁剪一致?
    2. 在因子为 \(S\) 的 fp16 损失缩放下,最后一个微批量结束后累加器保存 \(S \mathbf{g}\)。循环必须按何种顺序执行除以 \(S\) 反缩放、裁剪与优化器步?若 \(S\) 在微批量之间发生变化会出什么问题?
  4. [code] fp16 梯度窗口。● fp16 的 5 位指数使其规格化数范围为 \(2^{-14}\) 到 65,504,非规格化数下探至 \(2^{-24}\)。损失缩放 (Micikevicius 等 2018年) 在微分前将损失乘以 \(S\),之后将梯度除以 \(S\)。使用 13.4.2 节 中的 mlp_params、X_mlp、y_mlp、loss_fn 及纯 fp32 参考梯度:
    1. 绘制全部非零参考梯度元素的 \(\log_2 |g|\) 直方图,找出能使 99.9% 的缩放后元素 \(Sg\) 落入 fp16 规格化范围的缩放因子 \(S\)。
    2. 对 \(S = 2^0, 2^2, \ldots, 2^{24}\),用 jnp.float16 计算梯度,除以 \(S\) 反缩放,并绘制相对误差 \(\|\hat{\mathbf{g}} - \mathbf{g}\| / \|\mathbf{g}\|\)。用 jnp.bfloat16 重复该过程。在哪个 \(S\) 窗口内 fp16 比 bf16 更精确?为什么?
    3. 若批量大小从 2,048 增至 32,768,\(S\) 的有效窗口会如何移动?
  5. [code] 选择性重计算。● jax.checkpoint 接受 policy 参数,例如 jax.checkpoint_policies.dots_with_no_batch_dims_saveable,它保存权重矩阵乘的输出并重计算逐元素算子。
    1. 针对我们 GPT 的单个模块,列出无检查点、默认 jax.checkpoint 与 dots_with_no_batch_dims_saveable 三种策略下保存的残差与重计算的矩阵乘,并用 jax.ad_checkpoint.print_saved_residuals 验证。
    2. 将该策略加入 13.4.3 节 的 4 块基准测试,比较每词元保存字节数、规划峰值显存与步时。
  6. [extended] 分块计算损失。●● 在逐块检查点下,我们 GPT 的输出层与交叉熵损失每词元占用的显存超过了全部 18 个模块之和,因为损失为每个词元物化了 \(V = 50{,}257\) 个对数概率及其梯度。
    1. 改写输出投影与交叉熵损失,使其按大小 \(n_c = 1024\) 的词元块分块处理,并将每一块包裹在检查点内,使任意时刻仅存在一个块的 logit 与对数概率。验证损失与梯度与未分块版本一致。
    2. 预测 24 GiB 显卡上 18 块 GPT 结合逐块检查点与分块损失后的最大微批量大小,并在 2 块 GPT 上实测每词元显存斜率与步时。

讨论