import os
import re
from torch.utils.checkpoint import checkpoint13.8 案例研究:优化 Transformer
本章此前各节分别孤立出训练步缓慢的某一个成因以及消除它的改动:主机派发开销、小内核引发的访存流量、过宽的数值格式以及单 GPU 边界。真实的训练步往往同时受多个瓶颈拖累,消除其中一个又会把瓶颈转移到其余环节。这里我们像工程实践者一样拿起一个具体模型,追问它的训练步究竟能加快多少——以及各项改动应按何种顺序施加。
研究对象是 11.2 节 中的 GPT,但将其宽度翻倍至 512(1,900 万参数)。在 64 个长度为 128 字节的窗口(\(8{,}192\) 个词元)上执行一步训练,大约进行 \(6 \times 1.9 \times 10^{7} \times 8{,}192 \approx 9 \times 10^{11}\) 次 FLOP:前向传播每参数每词元 2 次,反向传播 4 次。在 RTX 4090(bf16 下 \(165\text{ TFLOP/s}\))上,这些算术运算只需不到 \(6\text{ ms}\)。而使用 AdamW 的普通 fp32 单步耗时约 \(25\text{ ms}\)。在这 \(19\text{ ms}\) 差距中,仅数值格式就占去约 \(6\text{ ms}\)(tf32 张量核心速率为 bf16 的一半,需要 \(11\text{ ms}\));剩余约 \(13\text{ ms}\) 则是张量核心低于峰值运行或干脆空闲的时间。
我们遵循 13.1 节 的方法:先计数、再预测、再测量、最后解释偏差。每次改动前,上一步的剖析结果界定了本次改动最多能带来多少收益;改动后,我们将实测值与预测对照。每项改动都在前序改动的基础上累积测量。本节最后会检验最快的单步是否仍能正常训练模型,并核算剩余时间都花在了哪里。
# Let XLA overlap collectives with computation. JAX reads XLA_FLAGS once,
# when it starts, so this cell runs before the imports. Our outputs come
# from a run with three more settings in the environment, which you set
# before starting: --xla_gpu_enable_triton_gemm=false in XLA_FLAGS, so that
# XLA calls cuBLAS for the matrix products (the Triton kernels it would
# generate run the products of the large minibatches more slowly on the
# RTX 4090); NCCL_LOCAL_REGISTER=0, since NCCL's buffer registration fails
# on GPUs without peer-to-peer access and would print a warning at every
# collective; and XLA_PYTHON_CLIENT_ALLOCATOR=vmm, which maps each array
# into one contiguous range: the fp32 step of the training check needs
# about 13 GiB in one piece after many other arrays have come and gone.
import os
os.environ['XLA_FLAGS'] = (os.environ.get('XLA_FLAGS', '') +
' --xla_gpu_enable_latency_hiding_scheduler=true')import re
from jax.sharding import NamedSharding, PartitionSpec as Ptorch.set_float32_matmul_precision('high') # fp32 products on tf32 cores
# 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'13.8.1 实验设置
本节的每项改动都以同一套度量标准评判,因此模型、数据与吞吐量基准全程保持固定。
13.8.1.1 模型与数据
我们训练 d2l.GPT(11.2 节):6 个前规范化块,每块 8 个注意力头,采用旋转位置编码、RMS 规范化、SwiGLU,以及与输出层共享权重的输入嵌入。数据是从 256 字节词表的 WikiText-103 中按随机偏移抽取的 128 字节窗口(d2l.WikiText103,见 9.3 节)。
我们将宽度从 256 翻倍到 512,使矩阵乘法稳稳落在计算受限区域(13.1 节)。一个 \(n \times d\) 激活矩阵乘以 \(d \times d'\) 权重矩阵执行 \(2ndd'\) 次 FLOP,移动 \(b(nd + dd' + nd')\) 字节(每元素 \(b\) 字节)。当词元数 \(n = 8{,}192\)、宽度 \(d = 512\) 时,块内投影的算术强度在 tf32(\(b = 4\))下达到 \(125\text{--}185\text{ FLOP/byte}\),在 bf16(\(b = 2\))下达到 \(250\text{--}370\text{ FLOP/byte}\),均远高于 RTX 4090 的屋脊拐点(tf32 为 \(82\text{ FLOP/byte}\),bf16 为 \(164\text{ FLOP/byte}\))。因此,更快的数值格式能直接缩短这些乘法的耗时。而在宽度 256 时,它们恰好跨在屋脊拐点附近(6)。
270 MB 的训练语料可以作为平坦字节数组直接放进 GPU 显存。下一个代码块将其放入 GPU,定义 windows 直接在设备上采样小批量以避免主机传输,并构建模型。
device = d2l.try_gpu()
data = d2l.WikiText103(batch_size=64, num_steps=128)
corpus = torch.tensor(data.train, device=device) # One byte per token
def windows(corpus, batch_size, num_steps=128):
"""Endless minibatches of windows at random offsets, each position with
the next byte as its target."""
offsets = torch.arange(num_steps + 1, device=corpus.device)
while True:
starts = torch.randint(len(corpus) - num_steps, (batch_size, 1),
device=corpus.device)
W = corpus[starts + offsets].long()
yield W[:, :-1], W[:, 1:]
model = d2l.GPT(len(data.vocab), num_hiddens=512).to(device)
num_params = d2l.num_params(model)
print(f'{num_params / 1e6:.1f}M parameters, '
f'{len(corpus) / 1e6:.0f}M training bytes on the GPU')19.0M parameters, 270M training bytes on the GPU
data = d2l.WikiText103(batch_size=64, num_steps=128)
corpus = jnp.asarray(data.train) # One byte per token
def windows(corpus, batch_size, num_steps=128, *, sharding=None):
"""Endless minibatches of windows at random offsets, each position with
the next byte as its target; `sharding` spreads them over devices."""
offsets = jnp.arange(num_steps + 1)
while True:
starts = jax.random.randint(d2l.get_key(), (batch_size, 1), 0,
len(corpus) - num_steps)
if sharding is not None:
starts = jax.device_put(starts, sharding)
W = corpus[starts + offsets].astype(jnp.int32)
yield W[:, :-1], W[:, 1:]
model = d2l.GPT(len(data.vocab), num_hiddens=512,
rngs=nnx.Rngs(d2l.get_key()))
num_params = d2l.num_params(model)
print(f'{num_params / 1e6:.1f}M parameters, '
f'{len(corpus) / 1e6:.0f}M training bytes on the GPU')19.0M parameters, 270M training bytes on the GPU
按每参数 16 字节(权重、梯度与两个 Adam 矩估计)计算,1,900 万参数的训练状态仅占 \(0.3\text{ GiB}\),既不需要梯度累积,也不需要分片(13.4 节、13.7 节)。将语料留在 GPU 上还能把训练步与输入流水线隔离开来(13.2 节)。
13.8.1.2 吞吐量测量
我们以每秒词元数衡量端到端训练吞吐量,涵盖小批量采样、前向与反向传播以及优化器更新:
| 设置 | 取值 |
|---|---|
| 硬件 | 4 块 RTX 4090 中的 1 块(数据并行时用 2 块和 4 块) |
| 模型 | d2l.GPT:6 块,宽度 512,8 头,字节词表,上下文长度 128 |
| 数据 | 每步在 GPU 上随机抽取的 WikiText-103 128 字节窗口 |
| 优化器 | AdamW(\(\text{lr} = 10^{-3}\),权重衰减 \(0.01\)) |
| 精度 | 引入 bf16 前采用 fp32 配合 tf32 矩阵乘法 |
| 计时 | d2l.Benchmark:20 步预热,随后在设备同步间测量 3 个各 50 步的窗口 |
| 结果 | 3 个窗口的中位词元/秒、相对上一保留配置的加速比,以及相对窗口极差 |
tokens_per_second 通过 d2l.Benchmark(13.1 节)执行上述规则。record 记录每项结果,并打印其相对上一保留配置的加速比以及三个测量窗口间的相对波动(\(\text{range} / \text{median}\))。传入 kept=False 的配置会作为分支保存,后续配置不会建立在其上。
def tokens_per_second(step, batches, warmup=20, repeats=50, num_windows=3):
"""Median training throughput of `step` on minibatches drawn from
`batches`, over `num_windows` timed windows of `repeats` steps each, and
the spread of the windows (largest minus smallest) relative to it."""
X, _ = next(batches)
speeds = [math.prod(X.shape) / d2l.Benchmark(
lambda: step(*next(batches)), warmup if i == 0 else 0,
repeats).time for i in range(num_windows)]
return np.median(speeds), np.ptp(speeds) / np.median(speeds)
results, branches = {}, {}
def record(name, measured, kept=True):
"""Store a measured throughput and print it with its ratio to the last
kept configuration and the spread of its windows; a configuration that
is not kept is stored in `branches`."""
speed, spread = measured
previous = list(results.values())[-1] if results else speed
(results if kept else branches)[name] = speed
print(f'{name}: {speed:,.0f} tokens/s ({speed / previous:.2f}x), '
f'windows within {spread:.1%}')def tokens_per_second(step, batches, warmup=20, repeats=50, num_windows=3):
"""Median training throughput of `step` on minibatches drawn from
`batches`, over `num_windows` timed windows of `repeats` steps each, and
the spread of the windows (largest minus smallest) relative to it."""
X, _ = next(batches)
speeds = [math.prod(X.shape) / d2l.Benchmark(
lambda: step(*next(batches)), warmup if i == 0 else 0,
repeats).time for i in range(num_windows)]
return np.median(speeds), np.ptp(speeds) / np.median(speeds)
results, branches = {}, {}
def record(name, measured, kept=True):
"""Store a measured throughput and print it with its ratio to the last
kept configuration and the spread of its windows; a configuration that
is not kept is stored in `branches`."""
speed, spread = measured
previous = list(results.values())[-1] if results else speed
(results if kept else branches)[name] = speed
print(f'{name}: {speed:,.0f} tokens/s ({speed / previous:.2f}x), '
f'windows within {spread:.1%}')包含大量主机工作的单步对后台主机活动很敏感,其窗口波动比编译后或图捕获后的单步更宽。由于不同日期的主机负载变化大于单次运行中相邻窗口的起伏,我们将加速比读至小数点后一位,且只有在剖析结果有明确预测时才采信几个百分点的小幅提升。
13.8.2 单 GPU 优化
我们首先在单块 GPU 上从 11.2 节 的基线实现出发,每次施加一项改动来优化训练步。
13.8.2.1 基线
基线即 11.2 节 中配合 AdamW 的标准训练步:前向传播、交叉熵损失、反向传播与参数更新。
该单步以即时模式运行:Python 与自动微分逐一派发每个前向和反向操作的内核启动,而 AdamW(fused=True)则用少数几个融合内核更新所有参数与矩估计。make_step 封装训练步,其 forward 与 bf16 参数用于支持后续小节的改动。
train_step 与 d2l.train_steps(9.3 节)一样用 nnx.jit 编译。它接收模型与优化器作为参数,并根据 fp32 对数几率计算交叉熵损失。
def make_step(model, forward=None, bf16=False, warmup=0):
"""An AdamW training step of `model` on a minibatch (X, Y); `forward`
replaces the model's forward pass, `bf16` turns on autocast, and a
`warmup` > 0 raises the learning rate linearly to 1e-3 over as many
steps."""
forward = model if forward is None else forward
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3,
weight_decay=0.01, fused=True)
if warmup:
schedule = torch.optim.lr_scheduler.LambdaLR(
optimizer, lambda i: min(1, (i + 1) / warmup))
def step(X, Y):
with torch.autocast('cuda', torch.bfloat16, enabled=bf16):
loss = F.cross_entropy(forward(X).flatten(0, 1), Y.flatten())
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()
if warmup:
schedule.step()
return loss
return step
step = make_step(model)
record('baseline', tokens_per_second(step, windows(corpus, 64)))baseline: 317,736 tokens/s (1.00x), windows within 1.9%
def train_step(model, optimizer, X, Y):
"""Loss, gradients, and AdamW update for one minibatch."""
def loss_fn(model):
logits = model(X).astype(jnp.float32)
return optax.softmax_cross_entropy_with_integer_labels(
logits, Y).mean()
loss, grads = nnx.value_and_grad(loss_fn)(model)
optimizer.update(model, grads)
return loss
adamw = optax.adamw(1e-3, weight_decay=0.01)
optimizer = nnx.Optimizer(model, adamw, wrt=nnx.Param)
jit_step = nnx.jit(train_step)
step = lambda X, Y: jit_step(model, optimizer, X, Y)
record('baseline', tokens_per_second(step, windows(corpus, 64)))baseline: 340,062 tokens/s (1.00x), windows within 10.7%
不出所料,由于每步存在主机开销,基线的窗口波动大约是后续配置的十倍。为了看清单步时间花在哪里,profile 用 d2l.kernel_times 记录五步,借助 d2l.show_profile(13.1.4 节)展示拆解结果(总设备内核时间对比挂钟单步时间、矩阵乘法含融合注意力内核的占比以及最耗时内核),并保存该剖析结果供最终核算。
profiles = {}
def profile(step, batches):
"""Kernel profile of `step`, the configuration recorded last, on
minibatches drawn from `batches`: printed against the throughput that
`record` measured, and stored in `profiles` under the same name."""
name, speed = list(results.items())[-1]
X, _ = next(batches)
kernels = d2l.kernel_times(lambda: step(*next(batches)), steps=5)
d2l.show_profile(kernels, 1e3 * math.prod(X.shape) / speed, rows=4)
profiles[name] = kernels
profile(step, windows(corpus, 64))wall clock 25.78 ms per step, device busy 24.44 ms (95%), matrix products 64%
3.28 ms 13% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
3.08 ms 13% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_t
2.84 ms 12% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
2.41 ms 10% vectorized_elementwise_kernel<4, BinaryFunctor<float
profiles = {}
def profile(step, batches):
"""Kernel profile of `step`, the configuration recorded last, on
minibatches drawn from `batches`: printed against the throughput that
`record` measured, and stored in `profiles` under the same name."""
name, speed = list(results.items())[-1]
X, _ = next(batches)
kernels = d2l.kernel_times(lambda: step(*next(batches)), steps=5)
d2l.show_profile(kernels, 1e3 * math.prod(X.shape) / speed, rows=4)
profiles[name] = kernels
profile(step, windows(corpus, 64))wall clock 24.09 ms per step, device busy 23.61 ms (98%), matrix products 65%
3.02 ms 13% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
1.99 ms 8% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
1.90 ms 8% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_t
1.39 ms 6% loop_add_multiply_fusion_5
设备几乎在整个单步期间都在运行内核,其中矩阵乘法占去大约三分之二的时间。由于主机基本跟得上节奏,单步的瓶颈在设备端工作。
矩阵乘法之外剩余的三分之一时间零散分布在众多短内核上(SwiGLU、旋转位置编码、残差相加与 RMS 规范化),每个内核都要读写设备显存,因而受限于显存带宽(13.3.2 节)。
由于 nnx.jit 编译了整个单步,XLA 已经把逐元素操作融合进了周围的内核中。矩阵乘法之外那三分之一的设备时间花在这些融合内核上,它们依然受限于所搬运的字节数。
13.8.2.2 主机开销与小内核
有两种手段针对矩阵乘法之外的时间,而剖析结果界定了它们各自的收益上限。这个上界即阿姆达尔定律 (Amdahl 1967年):如果某项改动将占单步比例 \(f\) 的部分提速 \(s\) 倍,整步加速比为 \(1/(1 - f + f/s)\),无论 \(s\) 多大都无法超过 \(1/(1 - f)\)。套用到这两种手段上:
- 降低主机开销针对设备等待主机的空闲缝隙(13.1 节);其加速比受限于单步中的空闲比例。
- 内核融合将一连串访存带宽受限的逐元素内核合并,使中间数组留在片上;其加速比受限于非矩阵乘法的设备时间。
我们的基线处于第二种情形:GPU 仅在单步的几个百分点里空闲,而非矩阵乘法内核在 \(24.5\text{ ms}\) 的设备时间中占去 \(8.8\text{ ms}\)。即便编译能彻底消除所有非矩阵乘法内核与空闲缝隙,单步也顶多缩减到矩阵乘法的 \(15.6\text{ ms}\)——至多 \(1.6\times\) 加速。torch.compile(13.3 节)在前向与反向传播中融合逐元素操作,同时保留矩阵乘法和融合优化器更新不变。传入 mode='reduce-overhead' 与 dynamic=False 还会捕获静态形状的 CUDA 图(13.3.4 节),既消除了眼前这几个百分点由主机引起的空闲时间,也防止后续设备执行缩短后主机派发反客为主成为瓶颈。我们先验证编译后的模型与即时模式的对数几率一致。
我们的单步已被 XLA 融合,且 GPU 等待主机的时间仅占单步的 2%,因此眼下减少主机工作最多只能带来 2% 的收益。我们依然要去掉它,因为这是一笔固定的每步开销,等后续优化缩短设备执行后就会浮出水面。每次调用时,nnx.jit 都要遍历 Python 模型与优化器对象以提取并更新其中的数组。下面我们在空操作函数上基准测试这种遍历开销,对比普通 nnx.jit、nnx.jit(..., graph=False)(树模式)和 nnx.jit_partial(..., graph=False)(一次性绑定模型与优化器状态,使每步只传入小批量)。
compiled = torch.compile(model, dynamic=False, mode='reduce-overhead')
X, _ = next(windows(corpus, 64))
high = model(X)
error = ((compiled(X) - high).norm() / high.norm()).item()
print(f'relative difference of the compiled logits: {error:.1e}')
assert error < 1e-4
step = make_step(model, compiled)
record('+ compile', tokens_per_second(step, windows(corpus, 64)))relative difference of the compiled logits: 1.5e-05
+ compile: 368,688 tokens/s (1.16x), windows within 0.0%
print(f'{len(jax.tree.leaves(nnx.state((model, optimizer))))} arrays in '
'the model and the optimizer')
noop = lambda model, optimizer: None
walk, tree = nnx.jit(noop), nnx.jit(noop, graph=False)
bound = nnx.jit_partial(noop, model, optimizer, graph=False)
for name, call in (('nnx.jit', lambda: walk(model, optimizer)),
('nnx.jit, graph=False', lambda: tree(model, optimizer)),
('nnx.jit_partial', bound)):
seconds = d2l.Benchmark(call, repeats=100).time
print(f'{name}: {1e3 * seconds:.2f} ms per call that does nothing')146 arrays in the model and the optimizer
nnx.jit: 8.69 ms per call that does nothing
nnx.jit, graph=False: 1.76 ms per call that does nothing
nnx.jit_partial: 0.23 ms per call that does nothing
编译后的对数几率在四位有效数字内吻合(细微差异源于融合内核中重排后的 fp32 舍入被 tf32 矩阵乘法放大)。吞吐量提升超过 10%,稳稳落在 \(1.6\times\) 上界之内。
经由 nnx.jit 的空操作调用竟耗费近 \(9\text{ ms}\) 的主机时间,超过单步设备时间的三分之一。这笔开销只有在主机跑在设备前面时才会被隐藏;切到树遍历就能去掉其中大部分,而用 nnx.jit_partial 绑定后几乎能消除剩余的全部开销。接下来我们验证 nnx.jit_partial 与 nnx.jit 产生完全相同的损失和权重更新。
twin = nnx.clone((model, optimizer)) # Equal states for the check
step = nnx.jit_partial(train_step, model, optimizer, graph=False)
X, Y = next(windows(corpus, 64))
loss, twin_loss = step(X, Y), jit_step(*twin, X, Y)
gaps = jax.tree.map(lambda a, b: jnp.abs(a - b).max(),
nnx.state(model, nnx.Param), nnx.state(twin[0], nnx.Param))
gap = max(float(g) for g in jax.tree.leaves(gaps))
print(f'losses {loss:.4f} and {twin_loss:.4f}, largest difference of the '
f'updated weights {gap:.1e}')
assert gap < 1e-6
record('+ jit_partial', tokens_per_second(step, windows(corpus, 64)))losses 2.3074 and 2.3074, largest difference of the updated weights 0.0e+00
+ jit_partial: 343,869 tokens/s (1.01x), windows within 0.2%
更新后的权重完全吻合,吞吐量提升约 1%,符合 2% 上界和基线噪声波动范围。
第二次剖析展示了单步的变化:
profile(step, windows(corpus, 64))wall clock 22.22 ms per step, device busy 22.27 ms (100%), matrix products 71%
4.01 ms 18% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
3.05 ms 14% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_t
2.83 ms 13% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
1.44 ms 6% fmha_cutlassB_f32_aligned_64x64_k64_sm80
profile(step, windows(corpus, 64))wall clock 23.82 ms per step, device busy 23.61 ms (99%), matrix products 65%
3.03 ms 13% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
1.99 ms 8% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
1.90 ms 8% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_t
1.39 ms 6% loop_add_multiply_fusion_5
设备几乎在整个单步期间保持忙碌,矩阵乘法如今占到设备时间的三分之二乃至更高。
每步设备时间从 \(24.5\text{ ms}\) 降至 \(22.3\text{ ms}\),内核间缝隙消失:Inductor 融合从非矩阵乘法时间中削去 \(2.2\text{ ms}\)(四分之一),而 CUDA 图重放填平了约 \(1\text{ ms}\) 的主机启动缝隙。
设备内核时间未变,因为 nnx.jit_partial 只降低了主机侧的派发开销。
13.8.2.3 降低精度
如今 GPU 全程忙碌且矩阵乘法主导设备时间,下一步自然是加速矩阵乘法。从 tf32 切换到 bf16 会将 RTX 4090 张量核心峰值吞吐量翻倍至 \(165\text{ TFLOP/s}\),并把 bf16 激活值的显存占用减半(13.4 节)。若矩阵乘法占单步比例 \(f \in [2/3, 0.7]\) 且只有它速度翻倍,单步耗时将缩至原来的 \(1 - f/2\)——大约 \(1.5\times\) 加速(若非矩阵乘法内核搬运的字节数也减半,则加速比会向 \(2\times\) 靠近)。
我们沿用 13.4.2 节 的混合精度方案:矩阵乘法(含注意力)与中间逐元素操作以 bf16 运行,而主权重、梯度、Adam 矩估计、规范化、损失与残差流保留在 fp32(让残差流留在 fp32 可防止小幅块更新在 bf16 的 8 位有效数字中被舍入抹掉)。由于 bf16 的指数范围与 fp32 一致,无需损失缩放。计时前,我们先验证 bf16 前向传播的对数几率与 fp32 在 bf16 精度(~1%)内一致。
X, _ = next(windows(corpus, 64))
with torch.autocast('cuda', torch.bfloat16):
low = compiled(X).float()
high = compiled(X)
error = ((low - high).norm() / high.norm()).item()
print(f'relative difference of the bf16 logits: {error:.1e}')
assert error < 0.01
step = make_step(model, compiled, bf16=True)
record('+ bf16', tokens_per_second(step, windows(corpus, 64)))relative difference of the bf16 logits: 2.0e-03
+ bf16: 643,350 tokens/s (1.74x), windows within 0.1%
xla16 = d2l.GPT(len(data.vocab), num_hiddens=512,
rngs=nnx.Rngs(d2l.get_key()))
nnx.update(xla16, nnx.state(model, nnx.Param)) # The same weights
d2l.to_bf16(xla16)
X, _ = next(windows(corpus, 64))
high = model(X)
error = float(jnp.linalg.norm(xla16(X) - high) / jnp.linalg.norm(high))
print(f'relative difference of the bf16 logits: {error:.1e}')
assert error < 0.01
step = nnx.jit_partial(train_step, xla16,
nnx.Optimizer(xla16, adamw, wrt=nnx.Param), graph=False)
record('+ bf16', tokens_per_second(step, windows(corpus, 64)))relative difference of the bf16 logits: 2.0e-03
+ bf16: 499,090 tokens/s (1.45x), windows within 0.4%
bf16 对数几率与 fp32 在 1% 以内吻合。
吞吐量提升约 \(1.75\times\)——超过了仅把 71% 矩阵乘法占比减半所预测的 \(1.55\times\),因为 bf16 GEMM 的利用率高于 tf32,且中间融合内核搬运的是 2 字节 bf16 激活值而非 4 字节浮点数。注意 F.scaled_dot_product_attention 从基线起就已经在使用融合的 FlashAttention 内核。
吞吐量提升 \(1.45\times\),略低于仅把 65% 矩阵乘法占比减半所预测的 \(1.48\times\),说明非矩阵乘法内核并未提速。罪魁祸首之一是注意力:默认情况下 jax.nn.dot_product_attention 使用 XLA 的实现,会在设备显存中物化完整的注意力矩阵(10.5 节)。现在激活值已是 16 位精度,我们可以切换到 cuDNN 的融合 FlashAttention 内核(implementation='cudnn'),把注意力分数留在片上。
class FusedGPT(d2l.GPT):
"""d2l.GPT with cuDNN's fused attention."""
class CausalAttention(d2l.GPT.CausalAttention):
@staticmethod
def attend(q, k, v): # cuDNN takes 16-bit inputs only
return jax.nn.dot_product_attention(q, k, v, is_causal=True,
implementation='cudnn')我们用相同参数转为 bf16 后从 FusedGPT 实例化 model16,验证其对数几率仍与 fp32 参考 high 在 1% 内一致,并对训练步进行基准测试:
model16 = FusedGPT(len(data.vocab), num_hiddens=512,
rngs=nnx.Rngs(d2l.get_key()))
nnx.update(model16, nnx.state(model, nnx.Param)) # The same weights
d2l.to_bf16(model16)
error = float(jnp.linalg.norm(model16(X) - high) / jnp.linalg.norm(high))
print(f'relative difference of the bf16 logits: {error:.1e}')
assert error < 0.01
step = nnx.jit_partial(train_step, model16,
nnx.Optimizer(model16, adamw, wrt=nnx.Param),
graph=False)
record('+ fused attention', tokens_per_second(step, windows(corpus, 64)))relative difference of the bf16 logits: 1.9e-03
+ fused attention: 675,436 tokens/s (1.35x), windows within 0.2%
切换到 cuDNN 融合注意力在保持 1% 对数几率吻合的前提下,又将吞吐量提高了三分之一,使 bf16 加融合注意力的综合加速比接近 \(2\times\)。
13.8.2.4 增大小批量
增大小批量可将每步固定开销摊薄到更多词元上。由于设备已经在整个单步中满载,只有随参数量而非词元数缩放的设备工作才能被摊薄:
- AdamW 读取权重、梯度与两个矩估计,并写回权重与两个矩估计(fp32 下 \(28\text{ bytes/param}\))。
- 混合精度在前向传播中将 fp32 主权重转为 bf16,在反向传播中将 bf16 权重梯度转回 fp32(\(12\text{ bytes/param}\))。
两者合计搬运 \(40\text{ bytes/param}\),即 \(0.76\text{ GB/step}\)。按 \(1.0\text{ TB/s}\) 显存带宽计,这项固定工作耗时约 \(0.75\text{ ms}\)——大约是批量 64 时 \(12\text{--}13\text{ ms}\) bf16 单步的 \(1/16\)。将小批量放大 \(8\times\),从 64 增至 512 个窗口(\(65{,}536\) 个词元),可摊薄这项固定开销的 \(7/8\),预测吞吐量提升约 5%。
即便单 GPU 收益不大,这一步也值得做,因为只有当单卡步时远长于梯度全归约时,数据并行才能良好扩展(13.8.3 节)。不过请记住,一旦批量超过临界批量大小,更大批量会降低样本效率(9.8 节、5)。由于激活显存随批量大小线性增长,我们还记录了权重与优化器状态之外的峰值显存(13.4.1.4 节)。
torch.cuda.reset_peak_memory_stats()
start = torch.cuda.memory_allocated()
record('+ batch 512', tokens_per_second(step, windows(corpus, 512)))
memory = (torch.cuda.max_memory_allocated() - start) / 2**30
print(f'memory beyond weights and optimizer state: {memory:.1f} GiB')+ batch 512: 653,141 tokens/s (1.02x), windows within 0.0%
memory beyond weights and optimizer state: 8.6 GiB
batches = windows(corpus, 512)
plan = step.lower(*next(batches)).compile().memory_analysis()
record('+ batch 512', tokens_per_second(step, batches))
memory = plan.temp_size_in_bytes / 2**30
print(f'memory beyond weights and optimizer state: {memory:.1f} GiB')+ batch 512: 718,714 tokens/s (1.06x), windows within 0.0%
memory beyond weights and optimizer state: 7.4 GiB
在批量大小 512 下,激活显存约占 GPU \(24\text{ GiB}\) 的三分之一,吞吐量提高数个百分点(2 跨不同批量大小分离了每步固定开销与每词元开销)。第三次剖析给出了批量大小 512 下的耗时拆解:
profile(step, windows(corpus, 512))wall clock 100.34 ms per step, device busy 100.33 ms (100%), matrix products 57%
11.62 ms 12% ampere_bf16_s1688gemm_bf16_128x128_ldg8_f2f_stages_3
10.78 ms 11% ampere_bf16_s16816gemm_bf16_128x64_ldg8_f2f_tn
7.45 ms 7% Kernel2<cutlass_80_tensorop_bf16_s16816gemm_relu_bf1
5.62 ms 6% triton_poi_fused__unsafe_view_mm_mul_silu_silu_backw
profile(step, windows(corpus, 512))wall clock 91.19 ms per step, device busy 90.91 ms (100%), matrix products 59%
14.54 ms 16% ampere_bf16_s1688gemm_bf16_64x128_sliced1x2_ldg8_f2f
11.90 ms 13% ampere_bf16_s1688gemm_bf16_128x128_ldg8_f2f_nn
8.36 ms 9% ampere_bf16_s1688gemm_bf16_128x128_ldg8_f2f_tn
6.72 ms 7% ampere_bf16_s1688gemm_bf16_128x128_ldg8_f2f_stages_3
设备在整个单步中始终满载:矩阵乘法(含融合注意力)占不到 60% 的时间,其余时间花在 RMS 规范化、SwiGLU、旋转位置编码以及 fp32/bf16 类型转换等融合的带宽受限内核上。
13.8.2.5 激活检查点
激活检查点(13.4.3 节)在前向传播时只保留每个块的输入,并在反向传播时重算其内部激活值,以此节省显存。由于批量大小 512 仅用掉三分之一 GPU 显存,此处并不需要检查点,开启它只会拖慢单步。我们可以用两种方式预测减速幅度:
- 按 FLOP 计数:重算前向传播将每词元的块算术量从 \(6\) 提高到 \(8\text{ FLOPs/param}\),预测保留无检查点吞吐量的 \(6/8 = 0.75\)。
- 按前向传播计时:下面我们在批量大小 512 下测量独立前向传播时间 \(t_{\text{fwd}}\),并计算 \(1 / (1 + t_{\text{fwd}} / t_{\text{step}})\)。
X512, _ = next(windows(corpus, 512)) # One minibatch of the last step
with torch.no_grad(), torch.autocast('cuda', torch.bfloat16):
t_forward = d2l.Benchmark(lambda: compiled(X512)).timeX512, _ = next(windows(corpus, 512)) # One minibatch of the last step
forward = nnx.jit_partial(lambda model, X: model(X), model16, graph=False)
t_forward = d2l.Benchmark(lambda: forward(X512)).time在批量大小 512 下比较 t_forward 与完整单步耗时 t_step,即可预测每个块的前向传播都被重算一次后保留的吞吐量比例 1 / (1 + t_forward / t_step):
t_step = 512 * 128 / results['+ batch 512'] # Seconds per step
print(f'forward pass {1e3 * t_forward:.1f} ms of a {1e3 * t_step:.1f} ms '
f'step: repeating it keeps at least {1 / (1 + t_forward / t_step):.2f} '
f'of the throughput')forward pass 30.8 ms of a 100.3 ms step: repeating it keeps at least 0.77 of the throughput
t_step = 512 * 128 / results['+ batch 512'] # Seconds per step
print(f'forward pass {1e3 * t_forward:.1f} ms of a {1e3 * t_step:.1f} ms '
f'step: repeating it keeps at least {1 / (1 + t_forward / t_step):.2f} '
f'of the throughput')forward pass 29.4 ms of a 91.2 ms step: repeating it keeps at least 0.76 of the throughput
两种估计彼此一致:前向传播约占单步的三分之一,因此重算一次应能保留至少四分之三的吞吐量(实际略高,因为嵌入与输出投影不做检查点)。下面我们用 Checkpointed 包装每个块,验证对数几率一致,并同时测量吞吐量(kept=False)与激活显存。
Checkpointed 调用 torch.utils.checkpoint.checkpoint。
Checkpointed 调用 nnx.remat。
class Checkpointed(nn.Module):
"""A module that keeps only its input for the backward pass."""
def __init__(self, module):
super().__init__()
self.module = module
def forward(self, X, **kwargs):
return checkpoint(self.module, X, use_reentrant=False, **kwargs)
remat = d2l.GPT(len(data.vocab), num_hiddens=512).to(device)
remat.load_state_dict(model.state_dict())
remat.blks = nn.ModuleList(Checkpointed(blk) for blk in remat.blks)
assert torch.allclose(remat(X), model(X), atol=1e-6)
step = make_step(remat, torch.compile(remat, dynamic=False,
mode='reduce-overhead'), bf16=True)
with torch.no_grad(), torch.autocast('cuda', torch.bfloat16):
forward = d2l.kernel_times(lambda: compiled(X512), steps=5) # Alone
torch.cuda.reset_peak_memory_stats()
start = torch.cuda.memory_allocated()
batches = windows(corpus, 512)
record('+ checkpointing', tokens_per_second(step, batches), kept=False)
memory = (torch.cuda.max_memory_allocated() - start) / 2**30
print(f'memory beyond weights and optimizer state: {memory:.1f} GiB')
def split(kernels):
"""Device ms per step of the matrix products and of all other kernels."""
products = sum(ms for name, ms in kernels.items()
if re.search(d2l.PRODUCT_KERNELS, name, re.I))
return np.array([products, sum(kernels.values()) - products])
alone = split(forward)
added = (split(d2l.kernel_times(lambda: step(*next(batches)), steps=5))
- split(profiles['+ batch 512']))
print(f'forward pass alone: products {alone[0]:4.1f} ms, other kernels '
f'{alone[1]:4.1f} ms\nadded to the step: products {added[0]:4.1f} ms, '
f'other kernels {added[1]:4.1f} ms')+ checkpointing: 556,390 tokens/s (0.85x), windows within 0.0%
memory beyond weights and optimizer state: 3.2 GiB
forward pass alone: products 17.4 ms, other kernels 13.4 ms
added to the step: products 14.5 ms, other kernels 3.1 ms
class Checkpointed(nnx.Module):
"""A module that keeps only its input for the backward pass."""
def __init__(self, module):
self.module = module
def __call__(self, X, **kwargs):
return nnx.remat(lambda module, X, kwargs: module(X, **kwargs))(
self.module, X, kwargs)
remat = FusedGPT(len(data.vocab), num_hiddens=512,
rngs=nnx.Rngs(d2l.get_key()))
nnx.update(remat, nnx.state(model16, nnx.Param))
remat.blks = nnx.List(Checkpointed(blk) for blk in remat.blks)
d2l.to_bf16(remat)
assert jnp.allclose(remat(X), model16(X), atol=1e-6)
optimizer = nnx.Optimizer(remat, adamw, wrt=nnx.Param)
step = nnx.jit_partial(train_step, remat, optimizer, graph=False)
batches = windows(corpus, 512)
plan = step.lower(*next(batches)).compile().memory_analysis()
record('+ checkpointing', tokens_per_second(step, batches), kept=False)
memory = plan.temp_size_in_bytes / 2**30
print(f'memory beyond weights and optimizer state: {memory:.1f} GiB')+ checkpointing: 565,754 tokens/s (0.79x), windows within 0.0%
memory beyond weights and optimizer state: 2.6 GiB
激活检查点将激活显存削减约三分之二,同时保留的吞吐量高于独立前向计时所做的预测。
吞吐量降至 \(0.85\times\)(高于 \(0.77\times\) 下界)。正如内核拆分所示,重算块矩阵乘法增加了 \(14\text{ ms}\)(接近包含输出投影在内的全部前向乘法耗时 \(17\text{ ms}\)),而重算非矩阵乘法内核却只增加了 \(3\text{ ms}\) 而非 \(13\text{ ms}\):Inductor 将重算的逐元素操作直接融合进了消费它们的反向内核中,使它们的重算几乎不产生额外访存流量。
吞吐量降至 \(0.79\times\)(高于 \(0.76\times\) 下界),因为 XLA 同样将重算的逐元素工作融合进了反向传播(3)。
当模型或批量大小否则会超出设备显存时,激活检查点不可或缺;但这里显存充裕,因此在后续配置中我们不启用它。
13.8.3 数据并行
我们最快的单 GPU 单步仍让机器里其余三块 RTX 4090 闲置。在多块 GPU 上运行之前,我们先用 13.5.4 节 的代价模型预测数据并行的加速比。
13.8.3.1 预测加速比
在数据并行(13.5 节)中,\(k\) 块 GPU 各自持有一份模型副本,在自己的小批量上计算梯度,并通过分成 \(c\) 个桶、总大小为 \(S\) 字节的全归约对梯度求和:
\[ t_{\textrm{compute}}(B/k) + c\,\alpha + \frac{2(k-1)}{k}\,S\,\beta_{\textrm{link}}. \]
在我们这台不支持点对点访问的 PCIe 机器上,GPU 传输经由主机内存中转,总线带宽大约为 \(2.4\text{ GB/s}\)(13.6 节),即 \(\beta_{\textrm{link}} \approx 0.42\text{ ns/byte}\)。在弱扩展下(固定每 GPU 批量大小),每桶延迟 \(c\,\alpha\) 不到一毫秒,相对数十毫秒的单步时间可以忽略,于是无重叠时的单步时间简化为:
\[t_{\textrm{step}}(k) \approx t_{\textrm{step}}(1) + t_{\textrm{allreduce}}(k), \tag{13.8.1}\]
对应吞吐量倍数为 \(k\, t_{\textrm{step}}(1) / (t_{\textrm{step}}(1) + t_{\textrm{allreduce}}(k))\)。仅当 \(t_{\textrm{allreduce}}(2) < t_{\textrm{step}}(1)\) 时,增加第二块 GPU 才能提升吞吐量。
对于 1,900 万参数的 GPT,fp32 梯度占 \(S = 76\text{ MB}\),由此得到两块 GPU 上 \(t_{\textrm{allreduce}}(2) \approx S\beta_{\textrm{link}} \approx 31\text{ ms}\),四块 GPU 上 \(t_{\textrm{allreduce}}(4) \approx 1.5\,S\beta_{\textrm{link}} \approx 47\text{ ms}\):
- 每 GPU 批量 64 的编译版 fp32(\(t_{\textrm{step}}(1) \approx 22\text{ ms}\)):全归约比单步本身还长。式 13.8.1 预测 2 块 GPU 上反而变慢(\(\sim 0.85\times\)),4 块 GPU 也只有 \(\sim 1.3\times\)。
- 每 GPU 批量 512 的编译版 bf16(\(t_{\textrm{step}}(1) \approx 90\text{--}100\text{ ms}\)):单步远长于全归约,预测 2 块 GPU 达 \(\sim 1.5\times\),4 块 GPU 达 \(2.6\text{--}2.7\times\)。
因为框架会将梯度全归约桶与反向传播重叠(图 13.6.1),式 13.8.1 通常是加速比的下界,高出该下界的余量衡量了有多少通信被隐藏在了反向计算背后。不过这并非绝对保证:NCCL 的复制内核会与反向传播争用同一块 GPU(13.6.2 节),而这种争用可能吃掉这部分余量。
13.8.3.2 实测加速比
data_parallel(k, bf16, batch_size) 在 \(k\) 块 GPU 上测量训练吞吐量,同时在同一组 GPU 上测量 \(76\text{ MB}\) 梯度缓冲区的独立全归约时间。
DDP_GPT = r'''
import json, sys, torch
from torch.nn.parallel import DistributedDataParallel as DDP
from d2l import torch as d2l
rank, k, device = d2l.init_distributed()
bf16, batch_size = sys.argv[1] == 'bf16', int(sys.argv[2])
torch.set_float32_matmul_precision('high')
torch._inductor.config.compile_threads = 1 # k processes compile at once
data = d2l.WikiText103(batch_size, 128)
corpus = torch.tensor(data.train, device=device)
model = DDP(d2l.GPT(len(data.vocab), num_hiddens=512).to(device))
step = d2l.make_step(model, torch.compile(model, dynamic=False), bf16)
batches = d2l.windows(corpus, batch_size)
seconds = d2l.Benchmark(lambda: step(*next(batches)), 20, 50).time
grads = torch.zeros(d2l.num_params(model), device=device)
allreduce = d2l.Benchmark(lambda: torch.distributed.all_reduce(grads),
repeats=10).time
if rank == 0:
print(json.dumps({'speed': k * batch_size * 128 / seconds,
'allreduce': allreduce}))
torch.distributed.destroy_process_group()
'''
# The CUDA graphs of the compiled steps above hold memory on GPU 0, which
# the process of rank 0 needs: reset the compiler and return the memory
torch.compiler.reset()
torch.cuda.empty_cache()
def data_parallel(k, bf16, batch_size):
"""Tokens per second on k GPUs, and seconds per allreduce of all
gradients."""
r = d2l.torchrun(DDP_GPT, k, 'bf16' if bf16 else 'fp32', batch_size)[0]
return r['speed'], r['allreduce']def data_parallel(k, bf16, batch_size):
"""Tokens per second on k GPUs, and seconds per allreduce of all
gradients."""
mesh = jax.make_mesh((k,), ('data',), devices=jax.devices()[:k],
# Auto: the compiler places intermediate results
axis_types=(jax.sharding.AxisType.Auto,))
copy, split = NamedSharding(mesh, P()), NamedSharding(mesh, P('data'))
net = (FusedGPT if bf16 else d2l.GPT)(len(data.vocab), num_hiddens=512,
rngs=nnx.Rngs(d2l.get_key()))
net = d2l.to_bf16(net) if bf16 else net
optimizer = nnx.Optimizer(net, adamw, wrt=nnx.Param)
nnx.update((net, optimizer),
jax.device_put(nnx.state((net, optimizer)), copy))
step = nnx.jit_partial(train_step, net, optimizer, graph=False)
batches = windows(jax.device_put(corpus, copy), k * batch_size,
sharding=split)
speed, _ = tokens_per_second(step, batches)
grads = jnp.zeros((k, num_params), device=split) # All gradients per GPU
psum = jax.jit(jax.shard_map(lambda g: jax.lax.psum(g, 'data'),
mesh=mesh, in_specs=P('data'),
out_specs=P('data')))
return speed, d2l.Benchmark(lambda: psum(grads), repeats=10).time现在我们对短的 fp32 单步(batch_size=64)和长的 bf16 单步(batch_size=512)在 \(k \in \{1, 2, 4\}\) 块 GPU 上运行 data_parallel,将无重叠预测 式 13.8.1 与实测加速比作对照:
for bf16, batch_size in ((False, 64), (True, 512)):
tokens = batch_size * 128 # Per GPU and step
one, _ = data_parallel(1, bf16, batch_size)
print(f'{"bf16" if bf16 else "fp32"}, batch {batch_size} per GPU: '
f'{one:,.0f} tokens/s on one GPU')
for k in (2, 4):
if k <= d2l.num_gpus():
speed, allreduce = data_parallel(k, bf16, batch_size)
predicted = k * tokens / (tokens / one + allreduce)
print(f' {k} GPUs: allreduce {1e3 * allreduce:3.0f} ms, '
f'speedup predicted {predicted / one:.2f}x, '
f'measured {speed / one:.2f}x')fp32, batch 64 per GPU: 364,947 tokens/s on one GPU
2 GPUs: allreduce 31 ms, speedup predicted 0.83x, measured 0.91x
4 GPUs: allreduce 48 ms, speedup predicted 1.27x, measured 1.36x
bf16, batch 512 per GPU: 662,971 tokens/s on one GPU
2 GPUs: allreduce 31 ms, speedup predicted 1.52x, measured 1.63x
4 GPUs: allreduce 48 ms, speedup predicted 2.69x, measured 2.92x
for bf16, batch_size in ((False, 64), (True, 512)):
tokens = batch_size * 128 # Per GPU and step
one, _ = data_parallel(1, bf16, batch_size)
print(f'{"bf16" if bf16 else "fp32"}, batch {batch_size} per GPU: '
f'{one:,.0f} tokens/s on one GPU')
for k in (2, 4):
if k <= d2l.num_gpus():
speed, allreduce = data_parallel(k, bf16, batch_size)
predicted = k * tokens / (tokens / one + allreduce)
print(f' {k} GPUs: allreduce {1e3 * allreduce:3.0f} ms, '
f'speedup predicted {predicted / one:.2f}x, '
f'measured {speed / one:.2f}x')fp32, batch 64 per GPU: 343,542 tokens/s on one GPU
2 GPUs: allreduce 31 ms, speedup predicted 0.87x, measured 0.89x
4 GPUs: allreduce 48 ms, speedup predicted 1.33x, measured 1.43x
bf16, batch 512 per GPU: 718,085 tokens/s on one GPU
2 GPUs: allreduce 31 ms, speedup predicted 1.50x, measured 1.71x
4 GPUs: allreduce 48 ms, speedup predicted 2.62x, measured 3.22x
独立全归约在 2 块 GPU 上耗时 \(31\text{ ms}\),在 4 块 GPU 上耗时 \(48\text{ ms}\),与我们的链路速率估计误差在一毫秒以内。两条方向相反的预测双双应验:在批量 64 下,2 块 GPU 慢于 1 块 GPU,4 块 GPU 增益不足 \(1.5\times\);而在 bf16 批量 512 下,4 块 GPU 达到单 GPU 吞吐量的大约 \(3\times\)(本节所有单项改动中最大的加速),且通信重叠将实测加速比推高到了无重叠下界 式 13.8.1 之上。(在单向 \(900\text{ GB/s}\) 的 NVLink 机器上,\(76\text{ MB}\) 全归约耗时不到一毫秒,即便批量 64 也能近乎线性扩展。)
13.8.4 结果
下面我们并排汇总全部单 GPU 优化,验证最终单步仍能正常训练模型,并核算剩余时间的去向。
13.8.4.1 累积对比
下表按顺序汇总了各单 GPU 配置。每行的 step 比值相对上一行测得,total 为相对基线的累积加速比,而激活检查点作为未保留分支列在分隔线下方。TFLOP/s 按每参数每词元 \(6\text{ FLOPs}\) 将吞吐量换算为算术速率,MFU 则除以 RTX 4090 的 \(165.2\text{ TFLOP/s}\) bf16 峰值(模型浮点运算利用率,model FLOPs utilization,Chowdhery 等 (2022年);1 补充了注意力分数的 FLOPs)。
flops = 6 * num_params # Per token, without the attention scores
peak = {'tf32': 82.6e12, 'bf16': 165.2e12} # FLOP/s of the RTX 4090
print(f'{"configuration":18}{"tokens/s":>10}{"step":>7}{"total":>7}'
f'{"TFLOP/s":>9}{"MFU":>6}')
first = previous = next(iter(results.values()))
for name, speed in results.items():
print(f'{name:18}{speed:10,.0f}{speed / previous:6.2f}x'
f'{speed / first:6.2f}x{speed * flops / 1e12:9.1f}'
f'{speed * flops / peak["bf16"]:6.0%}')
previous = speed
print('-' * 57)
for name, speed in branches.items(): # Measured on top of the last row
print(f'{name:18}{speed:10,.0f}{speed / previous:6.2f}x{"":7}'
f'{speed * flops / 1e12:9.1f}{speed * flops / peak["bf16"]:6.0%}'
' (not kept)')configuration tokens/s step total TFLOP/s MFU
baseline 317,736 1.00x 1.00x 36.2 22%
+ compile 368,688 1.16x 1.16x 42.1 25%
+ bf16 643,350 1.74x 2.02x 73.4 44%
+ batch 512 653,141 1.02x 2.06x 74.5 45%
---------------------------------------------------------
+ checkpointing 556,390 0.85x 63.5 38% (not kept)
flops = 6 * num_params # Per token, without the attention scores
peak = {'tf32': 82.6e12, 'bf16': 165.2e12} # FLOP/s of the RTX 4090
print(f'{"configuration":18}{"tokens/s":>10}{"step":>7}{"total":>7}'
f'{"TFLOP/s":>9}{"MFU":>6}')
first = previous = next(iter(results.values()))
for name, speed in results.items():
print(f'{name:18}{speed:10,.0f}{speed / previous:6.2f}x'
f'{speed / first:6.2f}x{speed * flops / 1e12:9.1f}'
f'{speed * flops / peak["bf16"]:6.0%}')
previous = speed
print('-' * 57)
for name, speed in branches.items(): # Measured on top of the last row
print(f'{name:18}{speed:10,.0f}{speed / previous:6.2f}x{"":7}'
f'{speed * flops / 1e12:9.1f}{speed * flops / peak["bf16"]:6.0%}'
' (not kept)')configuration tokens/s step total TFLOP/s MFU
baseline 340,062 1.00x 1.00x 38.8 23%
+ jit_partial 343,869 1.01x 1.01x 39.2 24%
+ bf16 499,090 1.45x 1.47x 56.9 34%
+ fused attention 675,436 1.35x 1.99x 77.0 47%
+ batch 512 718,714 1.06x 2.11x 82.0 50%
---------------------------------------------------------
+ checkpointing 565,754 0.79x 64.5 39% (not kept)
累积来看,单 GPU 优化将训练吞吐量翻了一番,达到 RTX 4090 bf16 峰值的约 50%。几乎全部收益都来自加速矩阵乘法(bf16)与减少其周围的访存流量(内核融合),而消除主机开销与增大小批量各自贡献了几个百分点,与剖析预测完全吻合。
请注意,每项加速比既取决于它在优化序列中的位置(7),也取决于硬件配比:在更快的 GPU 上(或更小的模型上),设备执行更短,消除主机派发的影响会大得多。
13.8.4.2 训练校验
如果某项优化悄悄破坏了训练,再高的吞吐量也毫无意义。我们用两个初始化完全相同的模型(一个使用基线单步,另一个使用最终编译版 bf16 单步)在完全相同的 200 个 512 窗口小批量(\(\sim 13\text{M}\) 词元)上进行训练来验证正确性,并采用 50 步线性学习率预热以防止 AdamW 后期损失尖峰(11.2 节)。我们检查两个模型在最后 20 步平均损失以及验证损失(d2l.lm_perplexity,见 9.3 节)上的差异均不超过 \(0.15\text{ nats/byte}\),且两者均优于 11.2 节 中 \(2.45\text{ nats/byte}\) 的二元语法基线。
learner = d2l.GPT(len(data.vocab), num_hiddens=512).to(device)
reference = d2l.GPT(len(data.vocab), num_hiddens=512).to(device)
reference.load_state_dict(learner.state_dict()) # One initialization
steps = {'baseline': make_step(reference, warmup=50),
'final': make_step(learner, torch.compile(
learner, dynamic=False, mode='reduce-overhead'), bf16=True,
warmup=50)}
batches = windows(corpus, 512)
minibatches = [next(batches) for _ in range(200)] # The same for both
losses = {name: torch.stack([step(X, Y).detach()
for X, Y in minibatches]).tolist()
for name, step in steps.items()}
validation = {name: math.log(d2l.lm_perplexity(net, data.val_dataloader()))
for name, net in (('baseline', reference), ('final', learner))}learner = d2l.to_bf16(FusedGPT(len(data.vocab), num_hiddens=512,
rngs=nnx.Rngs(d2l.get_key())))
reference = d2l.GPT(len(data.vocab), num_hiddens=512,
rngs=nnx.Rngs(d2l.get_key()))
nnx.update(reference, nnx.state(learner, nnx.Param)) # One initialization
# The learning rate rises linearly to 1e-3 over the first 50 steps
warm = optax.adamw(optax.linear_schedule(1e-3 / 50, 1e-3, 49),
weight_decay=0.01)
reference_optimizer = nnx.Optimizer(reference, warm, wrt=nnx.Param)
steps = {'baseline': lambda X, Y: jit_step(reference, reference_optimizer,
X, Y),
'final': nnx.jit_partial(train_step, learner, nnx.Optimizer(
learner, warm, wrt=nnx.Param), graph=False)}
batches = windows(corpus, 512)
minibatches = [next(batches) for _ in range(200)] # The same for both
losses = {name: jnp.stack([step(X, Y) for X, Y in minibatches]).tolist()
for name, step in steps.items()}
validation = {name: math.log(d2l.lm_perplexity(net, data.val_dataloader()))
for name, net in (('baseline', reference), ('final', learner))}下面我们对比第 1、50、100 和 200 步的训练损失轨迹,以及最后 20 步均值(late)与验证对数困惑度(validation),断言两次运行均优于 \(2.45\text{ nats/byte}\) 的二元语法阈值且彼此相差不超过 \(0.15\text{ nats/byte}\):
checkpoints = (1, 50, 100, 200)
late = {name: np.mean(curve[-20:]) for name, curve in losses.items()}
print(f'{"loss at step":14}' + ''.join(f'{i:>7}' for i in checkpoints)
+ f'{"mean of last 20":>17}{"validation":>12}')
for name, curve in losses.items():
print(f'{name:14}' + ''.join(f'{curve[i - 1]:7.2f}' for i in checkpoints)
+ f'{late[name]:17.2f}{validation[name]:12.2f}')
assert validation[name] < 2.45 # Better than the bigram model
for values in (late, validation): # The final step trains like the baseline
assert abs(values['baseline'] - values['final']) < 0.15loss at step 1 50 100 200 mean of last 20 validation
baseline 5.66 2.52 2.03 1.49 1.52 1.47
final 5.66 2.51 2.06 1.50 1.53 1.47
checkpoints = (1, 50, 100, 200)
late = {name: np.mean(curve[-20:]) for name, curve in losses.items()}
print(f'{"loss at step":14}' + ''.join(f'{i:>7}' for i in checkpoints)
+ f'{"mean of last 20":>17}{"validation":>12}')
for name, curve in losses.items():
print(f'{name:14}' + ''.join(f'{curve[i - 1]:7.2f}' for i in checkpoints)
+ f'{late[name]:17.2f}{validation[name]:12.2f}')
assert validation[name] < 2.45 # Better than the bigram model
for values in (late, validation): # The final step trains like the baseline
assert abs(values['baseline'] - values['final']) < 0.15loss at step 1 50 100 200 mean of last 20 validation
baseline 5.59 2.60 2.16 1.64 1.68 1.62
final 5.59 2.60 2.16 1.64 1.69 1.62
两条曲线都从 \(\log 256 \approx 5.55\) 起步,在全部 200 步中紧密贴合,最终达到几乎相同的验证损失且远低于二元语法阈值。不过请注意,批量 512 下的 200 步(\(13\text{M}\) 词元)结束时的损失高于 11.2 节 中批量 64 下 1,000 步余弦衰减(\(8\text{M}\) 词元)的损失:原始词元吞吐量并不等同于达到目标损失所需的时间(5)。
13.8.4.3 最终单步的时间核算
最后,account 将基线与最终剖析结果归一化为每 \(8{,}192\) 个词元的毫秒数,将总挂钟时间与理想峰值算术时间、实际矩阵乘法内核时间以及非矩阵乘法内核时间逐项对照。
def account(kernels, tokens, speed):
"""Milliseconds per 8,192 tokens of a step of `tokens` tokens that runs
at `speed` tokens/s: the step, its matrix products, and all its other
kernels."""
per_step = 8192 / tokens # Steps per 8,192 tokens
products = per_step * sum( # Kernel names as in d2l.show_profile
ms for name, ms in kernels.items()
if re.search(d2l.PRODUCT_KERNELS, name, re.I))
other = per_step * sum(kernels.values()) - products
return 1e3 * 8192 / speed, products, other
print(f'{"ms per 8,192 tokens":24}{"step":>6}{"at peak":>9}'
f'{"products":>10}{"other":>7}')
for name, tokens, fmt in (('baseline', 64 * 128, 'tf32'),
('+ batch 512', 512 * 128, 'bf16')):
wall, products, other = account(profiles[name], tokens, results[name])
arithmetic = 1e3 * 8192 * flops / peak[fmt] # At the peak of the format
print(f'{name + " (" + fmt + ")":24}{wall:6.1f}{arithmetic:9.1f}'
f'{products:10.1f}{other:7.1f}')ms per 8,192 tokens step at peak products other
baseline (tf32) 25.8 11.3 15.6 8.8
+ batch 512 (bf16) 12.5 5.7 7.1 5.4
def account(kernels, tokens, speed):
"""Milliseconds per 8,192 tokens of a step of `tokens` tokens that runs
at `speed` tokens/s: the step, its matrix products, and all its other
kernels."""
per_step = 8192 / tokens # Steps per 8,192 tokens
products = per_step * sum( # Kernel names as in d2l.show_profile
ms for name, ms in kernels.items()
if re.search(d2l.PRODUCT_KERNELS, name, re.I))
other = per_step * sum(kernels.values()) - products
return 1e3 * 8192 / speed, products, other
print(f'{"ms per 8,192 tokens":24}{"step":>6}{"at peak":>9}'
f'{"products":>10}{"other":>7}')
for name, tokens, fmt in (('baseline', 64 * 128, 'tf32'),
('+ batch 512', 512 * 128, 'bf16')):
wall, products, other = account(profiles[name], tokens, results[name])
arithmetic = 1e3 * 8192 * flops / peak[fmt] # At the peak of the format
print(f'{name + " (" + fmt + ")":24}{wall:6.1f}{arithmetic:9.1f}'
f'{products:10.1f}{other:7.1f}')ms per 8,192 tokens step at peak products other
baseline (tf32) 24.1 11.3 15.3 8.3
+ batch 512 (bf16) 11.4 5.7 6.7 4.7
每 \(8{,}192\) 个词元,最终单步约有 \(7\text{ ms}\) 花在矩阵乘法上(达到 \(5.7\text{ ms}\) bf16 理想峰值的 80% 以上),另有 \(5\text{ ms}\) 花在其间的带宽受限内核上——这是一个典型的 Roofline 分裂格局,其中张量缩并完成了超过 99% 的 FLOP,却只占约 60% 的时间 (Ivanov 等 2021年)。由于单靠更快的算术(如 fp8)或单靠消除非矩阵乘法访存流量都无法把按 \(7\text{ ms}\) 与 \(5\text{ ms}\) 切分的单步再减半,想要再获 \(2\times\) 加速,两者缺一不可。
13.8.5 小结
内核剖析能够在施加优化前定位训练步的瓶颈并界定每项候选优化的收益上界:减少主机派发最多省去设备空闲时间,内核融合最多省去非矩阵乘法设备时间,而当矩阵乘法占单步比例 \(f\) 时,将张量核心精度吞吐量翻倍带来的加速比介于 \(1/(1 - f/2)\) 与 \(2\) 之间。由于消除一个瓶颈会改变单步其余部分的占比,各项优化都必须验证数值等价性并累积测量。在单块 RTX 4090 上,我们 1,900 万参数的 GPT 单步速度翻倍,达到 45–50% MFU,几乎全部归功于 bf16 矩阵乘法与内核融合,使最终单步在接近峰值的矩阵缩并与带宽受限内核之间大致呈 60/40 分裂。最后,数据并行代价模型 \(t_{\textrm{step}}(1) + t_{\textrm{allreduce}}(k)\) 同时准确预测了短 fp32 单步在两块 GPU 上的变慢(\(22\text{ ms}\) 单步对比 \(31\text{ ms}\) PCIe 全归约),以及批量 512 bf16 单步在四块 GPU 上大约 \(3\times\) 的加速(\(90\text{--}100\text{ ms}\) 单步对比 \(48\text{ ms}\) 全归约)。
13.8.6 练习
- [code] 模型浮点运算利用率。13.8.1 节 中的 GPT 共有 \(L = 6\) 个宽度 \(d = 512\) 的块,上下文长度为 \(T = 128\)。忽略 SwiGLU 取整差异,每个块在矩阵乘法中持有 \(12d^2\) 个权重,训练大约每权重每词元消耗 \(6\text{ FLOPs}\)。
- 注意力分数乘积 \(\mathbf{Q}\mathbf{K}^\top\) 与值聚合是无权重的矩阵乘法。计算它们每词元每块的训练 FLOP(将反向传播取为前向传播的两倍,并计入被掩码的条目)。证明它们与权重 FLOP 之比为 \(T/(6d)\),并计算 \(T = 128\) 与 \(T = 1{,}024\) 时的比值。
- 在计入注意力 FLOP 的情况下,重新计算累积表中的
TFLOP/s与MFU列,同时计算各配置占其自身数值格式峰值(bf16 为 \(165\text{ TFLOP/s}\),tf32 为 \(83\text{ TFLOP/s}\))的比例。 - 举出 13.8.2 节 中理论模型 FLOP 与硬件实际执行 FLOP 不一致的两个配置或内核,并说明各自偏差的方向。
- [code] 单步的固定开销。将批量大小为 \(B\) 个窗口时的 bf16 单步时间建模为 \(t(B) = a + bB\),其中 \(a\) 为每步固定开销,\(b\) 为每窗口开销。
- 测量 \(B = 32, 64, 128, 256, 512\) 时的单步时间,用最小二乘法拟合 \(a\) 与 \(b\),并报告 \(a\) 在 \(B = 64\) 单步中的占比。
- 正文估计 AdamW 更新与 fp32/bf16 权重转换耗时 \(\sim 0.75\text{ ms/step}\)。这能解释 \(a\) 的多大比例?找出其他与 \(B\) 无关的工作,并与 \(B = 32\) 时的剖析结果核对。
- 用你的线性拟合预测 \(B = 1{,}024\) 与 \(B = 2{,}048\) 时的吞吐量,检查它们是否放得进 \(24\text{ GiB}\) GPU 显存,并实测能放得下的配置。
- [code] 重算的代价。13.8.2 节 中的激活检查点同时跑赢了 FLOP 计数估计与独立前向计时估计。
- 用
d2l.kernel_times分别剖析独立前向传播与带检查点的单步。将检查点新增的内核与独立前向内核逐一对照:哪些原样重现,哪些被融合进了反向内核? - 单独计时六个块的前向传播(不含嵌入层与输出层),并重新计算吞吐量下界。
- 仅每隔一个块启用检查点:运行前先根据测量结果预测吞吐量与显存,再实测并比较。
- 用
- [code] 因果性闸门。假设一个有缺陷的注意力内核悄悄忽略了因果掩码。
- 解释为何如果基线和待测学习器都使用了这一有缺陷的内核,13.8.4 节 中的训练损失、验证窗口损失以及 \(2.45\text{ nats/byte}\) 二元语法阈值全都无法揪出这一缺陷。
- 编写一项测试:扰动小批量中每条序列的最后一个输入词元,并验证所有更早位置的对数几率在数值容差内保持不变。在
learner以及一个去掉因果掩码的副本上运行该测试。
- 吞吐量与达到目标的时间。9.8 节 的模型估计,以批量大小 \(b\) 训练达到目标损失需要 \(E(b) = E_{\min}(1 + b / b_{\textrm{noise}})\) 个训练样本,其中 \(b_{\textrm{noise}}\) 为梯度噪声尺度。
- [code] 宽度 256。当
num_hiddens=256时,d2l.GPT与 11.2 节 中训练的架构完全一致。 - [code] 改动的顺序。累积表中的每项加速比都取决于其之前已施加的优化。
- 利用基线剖析和 13.8.2.3 节 中的上界,预测将 bf16 直接施加在未编译基线上的加速比。
- 实测该加速比,并与你的预测及累积表中的
+ bf16行作对比。接着在 bf16 之上施加编译(表中的第二行),并借助内核剖析解释两个比值为何发生变化。