import json
import os
import random
import sys13.6 数据并行实践
在 13.5 节 中,我们手写的数据并行循环在两块 GPU 上把 LeNet 拖慢了,原因有二:单个 Python 线程按顺序向两块 GPU 派发内核,且全归约要等到整个反向传播结束才开始,尽管最后几层的梯度早已就绪。
生产级数据并行工具消除了这两个瓶颈:它们要么为每块 GPU 运行一个独立主机进程,要么将单个分片程序编译到所有 GPU 上;同时把梯度归组为桶(bucket),反向传播期间每个桶一填满就立即启动全归约。为了测试梯度交换究竟能在多大程度上隐藏在反向计算背后,我们从 LeNet 转向 \(64 \times 64\) Fashion-MNIST 图像上的 ResNet-18(每张图像 2.2G 次乘加运算,相对其 45 MB 梯度每字节约 300 次训练 FLOP,每个 256 张图像的单步可让一块 RTX 4090 忙碌 ~100 ms)。我们通过单步校验验证并行单步的计算结果,并在一、二、四块 GPU 上测量弱扩展与强扩展,与我们的代价模型对照。
# JAX and NCCL read these settings once, when they start, so this cell runs
# before the imports. XLA overlaps a collective with computation only when
# its latency-hiding scheduler is on. The 'vmm' allocator reserves nothing
# up front and maps each array into one contiguous range, where JAX's
# default allocator reserves most of every GPU at start-up and carves every
# array out of that block: one step below needs about 10 GB in one piece
# after many smaller arrays have come and gone, and a later cell starts a
# second JAX process on the same GPUs.
# On GPUs without peer-to-peer access, such as ours, set
# NCCL_LOCAL_REGISTER=0 in the environment before starting: NCCL's buffer
# registration fails there and prints a warning at every collective.
import os
os.environ.setdefault('XLA_PYTHON_CLIENT_ALLOCATOR', 'vmm')
os.environ['XLA_FLAGS'] = (os.environ.get('XLA_FLAGS', '') +
' --xla_gpu_enable_latency_hiding_scheduler=true')import json
import re
import subprocess
import sys
from jax.sharding import NamedSharding, PartitionSpec as P13.6.1 生产级数据并行
13.6.1.1 执行模型
所有现代框架都采用两种单程序多数据(SPMD)设计之一来驱动 \(k\) 块 GPU:
- 多进程(\(k\) 份副本 + 集合通信库):启动器开启 \(k\) 个独立的 Python 进程——每块 GPU 一个,各自拥有 \(\{0, \ldots, k-1\}\) 中的进程编号(rank)以及独立的 CPU 线程——并通过 NCCL 同步梯度。每个进程内部可以运行任意 Python 代码。
- 编译器自动切分的单程序:用户编写单设备单步代码,并在设备网格上标注输入的分片方式;编译器自动切分计算并插入、调度集合通信操作 (Xu 等 2021年)。
PyTorch 采用多进程设计:torchrun 启动 \(k\) 个进程,由 DistributedDataParallel(DDP)包装模型。由于笔记本本身是单进程,我们的辅助函数 torchrun 会把自包含脚本写入临时文件,运行 torchrun --standalone --nproc-per-node=k,再解析每个 rank 的 JSON 输出。
JAX 采用编译器切分设计:nnx.jit 编译单设备训练步,将复制的参数(P())与按批量分片的输入(P('data'))放在一起时,Shardy/GSPMD 切分器会自动插入梯度全归约。
import glob
import subprocess
import tempfile
def torchrun(script, nproc, *args, env=None):
"""Run Python source in nproc processes; return their JSON lines."""
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, 'script.py')
with open(path, 'w') as f:
f.write(script)
launcher = os.path.join(os.path.dirname(sys.executable), 'torchrun')
# Each process prints to a file of its own (--redirects 1), so that
# the lines of different processes cannot interleave
run = subprocess.run(
[launcher, '--standalone', f'--nproc-per-node={nproc}',
'--log-dir', tmp, '--redirects', '1', path, *map(str, args)],
capture_output=True, text=True, env={**os.environ, **(env or {})})
if run.returncode != 0:
raise RuntimeError(run.stderr[-3000:])
logs = sorted(glob.glob(f'{tmp}/*/attempt_0/*/stdout.log'),
key=lambda log: int(log.split(os.sep)[-2])) # By rank
return [json.loads(line) for log in logs for line in open(log)
if line.startswith('{')]
def init_distributed():
"""Join the process group of torchrun; return the rank, the number of
processes, and the GPU of this process."""
device = torch.device('cuda', int(os.environ['LOCAL_RANK']))
torch.cuda.set_device(device)
torch.distributed.init_process_group('nccl', device_id=device)
return (torch.distributed.get_rank(), torch.distributed.get_world_size(),
device)13.6.1.2 将通信与反向传播重叠
生产框架按层的逆序(即反向传播生成梯度的顺序)将梯度打包成数十兆字节大小的桶,并在每个桶的最后一个梯度就绪时立即发起异步全归约 (Li 等 2020年)(图 13.6.1)。
桶大小在单次调用延迟 \(\alpha\) 与重叠程度之间权衡:桶太小会多次支付 \(\alpha\),而单个巨型桶则要等到反向传播完全结束才能启动。在理想的桶模型重叠假设下——假设 GPU 间链路足够快,能在下一个桶填满前完成当前桶,且通信不会拖慢并发的反向内核——除最后一个桶之外,所有桶都被隐藏在反向传播背后。
DDP 在 1 MiB 处封口第一个桶,后续桶在 25 MiB(bucket_cap_mb)处封口。对于 ResNet-18 的 45 MB 梯度,DDP 形成三个桶,大小分别约为 9、26 和 9 MB(最后的 9 MB 桶装的是最靠前、最后才算完的层)。
XLA 将梯度全归约合并至 30 MiB 阈值(--xla_gpu_all_reduce_combine_threshold_bytes),把 ResNet-18 的 45 MB 梯度打包为两对异步的 all-reduce-start / all-reduce-done,与反向计算并发调度。
13.6.1.3 训练步
我们定义 7.4 节 中的小图像 ResNet-18(为 第 32 章 (英文版) 使用 #@save 保存),并统计其梯度字节数 \(S\)(fp32 下为 45 MB):
def resnet18(num_classes, in_channels=1):
"""ResNet-18 for small images: a 3x3 stem without max-pooling, He
initialization."""
def stage(num_channels, first=False):
return [d2l.Residual(num_channels, use_1x1conv=not first,
strides=1 if first else 2),
d2l.Residual(num_channels)]
net = nn.Sequential(
# No stem bias: the batch normalization after the conv removes it
nn.Conv2d(in_channels, 64, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(64), nn.ReLU(),
*stage(64, first=True), *stage(128), *stage(256), *stage(512),
nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(512, num_classes))
with torch.no_grad(): # Create the lazy parameters of the blocks
net.eval()(torch.zeros(1, in_channels, 32, 32))
for m in net.modules(): # He initialization, zero biases
if isinstance(m, (nn.Conv2d, nn.Linear)):
nn.init.kaiming_normal_(m.weight, nonlinearity='relu')
if m.bias is not None:
nn.init.zeros_(m.bias)
return net.train()def resnet18(num_classes, in_channels=1, *, rngs):
"""ResNet-18 for small images: a 3x3 stem without max-pooling, He
initialization."""
he = nnx.initializers.variance_scaling(2.0, 'fan_in', 'normal')
def stage(num_channels, in_channels, first=False):
return [d2l.Residual(num_channels, use_1x1conv=not first,
strides=1 if first else 2,
in_channels=in_channels, rngs=rngs),
d2l.Residual(num_channels, in_channels=num_channels,
rngs=rngs)]
return nnx.Sequential(
# No stem bias: the batch normalization after the conv removes it.
# Running averages decay 0.9, two-pass variance
nnx.Conv(in_channels, 64, (3, 3), padding='same', use_bias=False,
kernel_init=he, rngs=rngs),
nnx.BatchNorm(64, momentum=0.9, use_fast_variance=False, rngs=rngs),
nnx.relu,
*stage(64, 64, first=True), *stage(128, 64), *stage(256, 128),
*stage(512, 256),
lambda X: X.mean(axis=(1, 2)), # Global average pooling
nnx.Linear(512, num_classes, kernel_init=he, rngs=rngs))接下来,我们加载 Fashion-MNIST,并计算 ResNet-18 的参数量 num_params 与 fp32 梯度体积 S:
我们还计算 DDP 在发起全归约之前按逆序打包出的 1 MiB 与 25 MiB 梯度桶 buckets。
d2l.FashionMNIST() # Download once, before any process runs
net = resnet18(10)
num_params = d2l.num_params(net)
S = 4 * num_params # Gradient bytes in fp32
# DDP's buckets: the gradients in the order in which the backward pass
# produces them, the reverse of the parameters', the first bucket closed
# at 1 MiB and every later one at 25 MiB
buckets, size = [], 0
for p in reversed(list(net.parameters())):
size += 4 * p.numel()
if size >= (25 if buckets else 1) * 2**20:
buckets, size = buckets + [size], 0
buckets += [size] if size else []
last_bucket = buckets[-1] # Bytes of the bucket sent last
print(f'{num_params / 1e6:.1f}M parameters, S = {S / 1e6:.0f} MB in buckets '
f'of {", ".join(f"{b / 1e6:.1f}" for b in buckets)} MB')11.2M parameters, S = 45 MB in buckets of 9.5, 26.5, 8.7 MB
data = d2l.FashionMNIST()
X_train = jax.image.resize(data.train[0][..., None] / np.float32(255),
(len(data.train[0]), 64, 64, 1), 'bilinear')
y_train = jnp.asarray(data.train[1], jnp.int32)
num_params = d2l.num_params(resnet18(10, rngs=nnx.Rngs(d2l.get_key())))
S = 4 * num_params # Gradient bytes in fp32
print(f'{num_params / 1e6:.1f}M parameters, S = {S / 1e6:.0f} MB')11.2M parameters, S = 45 MB
现在定义 \(64 \times 64\) Fashion-MNIST 图像上的数据并行训练步:
TRAIN_DDP 用 DDP 包装 resnet18,并在各进程间给 train_step 计时(支持可选的 model.no_sync() 与内核剖析)。
setup 在 'data' 网格上复制模型和数据集,train_step 在分片的小批量索引 idx 上运行经 JIT 编译的 SGD 更新。
TRAIN_DDP = r'''
import contextlib, json, sys, torch
import torch.distributed as dist
from torch.nn import functional as F
from torch.nn.parallel import DistributedDataParallel as DDP
from d2l import torch as d2l
rank, k, device = d2l.init_distributed()
torch.backends.cudnn.benchmark = True # Tune convolutions for fixed shapes
# b examples per GPU and step; sync=0 skips the gradient allreduce, and
# profile=1 also reports the device time per step of NCCL and other kernels
b, num_steps, seed, sync, profile = map(int, sys.argv[1:])
torch.manual_seed(seed) # The same permutations everywhere
data = d2l.FashionMNIST().train # A copy on every GPU, at 64 x 64
X = F.interpolate(data.data.to(device)[:, None] / 255, 64, mode='bilinear')
y = data.targets.to(device)
model = DDP(d2l.resnet18(10).to(device), device_ids=[device])
opt = torch.optim.SGD(model.parameters(), lr=0.1)
def minibatches():
"""This process's b examples of every global minibatch of k * b."""
while True:
perm = torch.randperm(len(y), device=device)
for s in range(len(y) // (k * b)):
yield perm[(s * k + rank) * b:][:b]
def train_step(i):
opt.zero_grad(set_to_none=True)
# Under no_sync, which must enclose the forward pass as well, each GPU
# keeps its own gradient
with model.no_sync() if not sync else contextlib.nullcontext():
F.cross_entropy(model(X[i]), y[i]).backward()
opt.step()
batches = minibatches()
t = d2l.Benchmark(lambda: train_step(next(batches)), warmup=10,
repeats=num_steps).time
result = {'rank': rank, 'step_time': t}
if profile:
kernels = d2l.kernel_times(lambda: train_step(next(batches)))
result['comm'] = sum(ms for name, ms in kernels.items() if 'nccl' in name)
result['compute'] = sum(kernels.values()) - result['comm']
print(json.dumps(result))
dist.destroy_process_group()
'''def setup(k, key):
"""ResNet-18 with SGD and the training set, replicated on k GPUs."""
mesh = jax.make_mesh((k,), ('data',), devices=jax.devices()[:k],
axis_types=(jax.sharding.AxisType.Auto,))
replicated = NamedSharding(mesh, P())
model = resnet18(10, rngs=nnx.Rngs(key))
opt = nnx.Optimizer(model, optax.sgd(0.1), wrt=nnx.Param)
for m in (model, opt):
nnx.update(m, jax.device_put(nnx.state(m), replicated))
return mesh, model, opt, jax.device_put((X_train, y_train), replicated)
def minibatches(mesh, batch_size):
"""Indices of random minibatches, split across the GPUs of the mesh."""
rng, n = np.random.default_rng(), len(y_train)
while True:
perm = rng.permutation(n)
for i in range(0, n - batch_size + 1, batch_size):
yield jax.device_put(perm[i:i + batch_size],
NamedSharding(mesh, P('data')))
@nnx.jit
def train_step(model, opt, X, y, idx):
"""One SGD step on the examples idx, written for a single device."""
def loss_fn(model):
return optax.softmax_cross_entropy_with_integer_labels(
model(X[idx]), y[idx]).mean()
loss, grads = nnx.value_and_grad(loss_fn)(model)
opt.update(model, grads)
return loss13.6.1.4 单步校验
与 LeNet 不同,ResNet-18 包含批量规范化(7.3 节),它用小批量均值和方差对每个通道做规范化。当一个 256 样本的小批量被切分到两块 GPU 上时,每块 GPU 是用各自 128 样本分片的本地统计量做规范化(与单 GPU 上累积两个 128 样本微批量等价),还是跨卡同步全局 256 样本的统计量?让我们把双 GPU 更新与这两种单 GPU 参考结果分别对照。
CHECK_DDP = r'''
import copy, json, sys, torch
import torch.distributed as dist
from torch.nn import functional as F
from torch.nn.parallel import DistributedDataParallel as DDP
from d2l import torch as d2l
rank, k, device = d2l.init_distributed()
torch.backends.cudnn.allow_tf32 = False # Full fp32 convolutions
torch.manual_seed(int(sys.argv[1])) # The same model and data everywhere
X = torch.rand(256, 1, 64, 64, device=device)
y = torch.randint(0, 10, (256,), device=device)
model = d2l.resnet18(10).to(device)
ref = copy.deepcopy(model) # An unwrapped copy for one GPU
def update(net, shards):
"""Parameter change of one SGD step on the mean loss over the shards."""
before = [p.detach().clone() for p in net.parameters()]
for X_j, y_j in shards:
(F.cross_entropy(net(X_j), y_j) / len(shards)).backward()
with torch.no_grad():
for p, b in zip(net.parameters(), before):
p -= 0.1 * p.grad
return [p.detach() - b for p, b in zip(net.parameters(), before)]
ddp = update(DDP(model, device_ids=[device]),
[(X.chunk(k)[rank], y.chunk(k)[rank])])
if rank == 0:
gap = lambda u: max((a - b).abs().max().item() for a, b in zip(ddp, u))
halves = update(copy.deepcopy(ref), list(zip(X.chunk(k), y.chunk(k))))
print(json.dumps({'largest': max(u.abs().max().item() for u in ddp),
'full': gap(update(ref, [(X, y)])),
'halves': gap(halves)}))
dist.destroy_process_group()
'''
if d2l.num_gpus() >= 2:
r = d2l.torchrun(CHECK_DDP, 2, random.getrandbits(32))[0]
print(f"largest update {r['largest']:.1e}\n"
f"largest difference from one GPU on all 256: {r['full']:.1e}\n"
f"largest difference from one GPU on two accumulated halves: "
f"{r['halves']:.1e}")largest update 1.7e-02
largest difference from one GPU on all 256: 1.0e-03
largest difference from one GPU on two accumulated halves: 1.2e-07
key = d2l.get_key() # One initialization for every step
idx = np.random.default_rng().permutation(len(y_train))[:256]
def update(k, idx):
"""Parameter change of one step on k GPUs on the examples idx."""
mesh, model, opt, (X, y) = setup(k, key)
before = jax.tree.map(np.asarray, nnx.state(model, nnx.Param))
train_step(model, opt, X, y,
jax.device_put(idx, NamedSharding(mesh, P('data'))))
return jax.tree.leaves(jax.tree.map(lambda p, b: np.asarray(p) - b,
nnx.state(model, nnx.Param), before))
with jax.default_matmul_precision('highest'): # Full fp32 convolutions
two = update(min(2, jax.device_count()), idx)
full = update(1, idx)
# For SGD, the mean of the steps on the two halves is the step on
# their accumulated gradients
halves = [(a + b) / 2 for a, b in zip(*(update(1, half)
for half in np.split(idx, 2)))]
gap = lambda u: max(np.abs(a - b).max() for a, b in zip(two, u))
print(f'largest update {max(np.abs(u).max() for u in two):.1e}\n'
f'largest difference from one GPU on all 256: {gap(full):.1e}\n'
f'largest difference from one GPU on two accumulated halves: '
f'{gap(halves):.1e}')largest update 2.4e-02
largest difference from one GPU on all 256: 2.5e-05
largest difference from one GPU on two accumulated halves: 1.7e-02
默认情况下,PyTorch DDP 使用每卡各自的分片统计量做规范化——与两半累积的结果吻合至 ~\(10^{-7}\),而与整批统计量相差百分之几(转换为 nn.SyncBatchNorm 可以同步全局统计量,但代价是增加额外集合通信;见 4)。
由于批量轴在 Auto 模式下沿 'data' 网格轴分片,XLA 切分器会在整个小批量上全局计算批量规范化的均值与方差——与单 GPU 的 256 样本单步吻合,并在两个大梯度缓冲区之外插入用于逐通道批量规范化统计量的小型全归约:
def allreduce_megabytes(compiled):
"""Megabytes of fp32 results of each allreduce in a compiled program,
in the order in which the program runs them."""
sizes = []
for line in compiled.as_text().splitlines():
# A synchronous all-reduce, or the -done half of an asynchronous
# pair, whose result type lists the summed arrays only
if re.search(r' all-reduce(-done)?\(', line):
result = line.split(' = ')[1].split(' all-reduce')[0]
sizes.append(sum(4 * math.prod(map(int, dims.split(',')))
for dims in re.findall(r'f32\[([\d,]+)\]',
result)) / 1e6)
return sizes在多 GPU 网格上编译 train_step 并调用 allreduce_megabytes,可以看到两个大梯度全归约(big,最后一个缓冲区记为 last_bucket)以及若干逐通道批量规范化的小全归约:
mesh, model, opt, (X, y) = setup(jax.device_count(), d2l.get_key())
idx = next(minibatches(mesh, 256 * mesh.size))
compiled = train_step.lower(model, opt, X, y, idx).compile()
sizes = allreduce_megabytes(compiled) # One entry per allreduce
big = [m for m in sizes if m > 1] # Gradient buffers, above 1 MB
last_bucket = 1e6 * big[-1] # Bytes of the buffer sent last
print(f'{len(sizes)} allreduces: {len(big)} of '
f'{" and ".join(f"{m:.1f}" for m in big)} MB, the other '
f'{len(sizes) - len(big)} of {sum(sizes) - sum(big):.2f} MB together')76 allreduces: 2 of 25.8 and 18.9 MB, the other 74 of 0.10 MB together
13.6.2 四块 GPU 上的扩展性
现在我们在 \(k \in \{1, 2, 4\}\) 块 GPU 上测量弱扩展(每 GPU 256 样本)和强扩展(全局 512 样本)。
def step_time(k, b, num_steps=50):
"""Seconds per DDP step on k GPUs with b examples per GPU."""
ranks = d2l.torchrun(TRAIN_DDP, k, b, num_steps, random.getrandbits(32),
1, 0) # Allreduce the gradients, no profile
return max(r['step_time'] for r in ranks)def stepper(k, b):
"""One data-parallel step on k GPUs with b examples per GPU, as a
function without arguments."""
mesh, model, opt, (X, y) = setup(k, d2l.get_key())
batches = minibatches(mesh, k * b)
return lambda: train_step(model, opt, X, y, next(batches))
def step_time(k, b, num_steps=50):
"""Seconds per data-parallel step on k GPUs with b examples per GPU."""
return d2l.Benchmark(stepper(k, b), warmup=10, repeats=num_steps).time首先,我们通过 NCCL 在裸 256 MB 全归约上测量 \(\beta_\textrm{link}\),并对比弱扩展下暴露通信时间 \(t_{\textrm{step}}(k) - t_{\textrm{step}}(1)\) 的两种预测:
- 无重叠:整个 \(S = 45\) MB 的环形全归约全部暴露(\(\frac{2(k-1)}{k} S \beta_\textrm{link}\))。
- 完全分桶重叠:只有最后一个桶/缓冲区(\(last\_bucket\))在反向传播结束后暴露出来。
ALLREDUCE = r'''
import json, torch
import torch.distributed as dist
from d2l import torch as d2l
_, _, device = d2l.init_distributed()
x = torch.zeros(2**26, device=device) # 64M floats: 256 MB
t = d2l.Benchmark(lambda: dist.all_reduce(x), repeats=10).time
print(json.dumps({'beta_link': t / x.nbytes})) # Each GPU sends S at k = 2
dist.destroy_process_group()
'''
def allreduce_beta(env=None):
"""beta_link of a bare 256 MB allreduce on two GPUs: the seconds
per byte that each GPU sends."""
return max(r['beta_link'] for r in d2l.torchrun(ALLREDUCE, 2, env=env))ALLREDUCE = r'''
import json, jax
from jax import numpy as jnp
from jax.sharding import NamedSharding, PartitionSpec as P
from d2l import jax as d2l
mesh = jax.make_mesh((2,), ('data',), devices=jax.devices()[:2])
x = jnp.zeros((2, 2**26), device=NamedSharding(mesh, P('data'))) # 256 MB
psum = jax.jit(jax.shard_map(lambda x: jax.lax.psum(x, 'data'), mesh=mesh,
in_specs=P('data'), out_specs=P('data')))
t = d2l.Benchmark(lambda: psum(x), repeats=10).time
print(json.dumps({'beta_link': t / (x.nbytes / mesh.size)})) # S per GPU
'''
def allreduce_beta(env=None):
"""beta_link of a bare 256 MB allreduce on two GPUs: the seconds
per byte that each GPU sends."""
run = subprocess.run([sys.executable, '-c', ALLREDUCE], check=True,
capture_output=True, text=True,
env={**os.environ, **(env or {})})
return json.loads(run.stdout.splitlines()[-1])['beta_link']调用 allreduce_beta() 得到实测链路代价 beta_link,据此计算 \(k \in \{2, 4\}\) 块 GPU 在无重叠(\(2(k-1)S\beta_\textrm{link}/k\))与完全重叠(last_bucket)两种模型下的 exposed[k]:
if d2l.num_gpus() >= 2:
beta_link = allreduce_beta()
print(f'bus bandwidth = {1e-9 / beta_link:.2f} GB/s '
f'(beta_link = {1e9 * beta_link:.2f} ns/byte)')
exposed = {} # Predicted exposed seconds per step
for k in (2, 4):
ring = 2 * (k - 1) / k # Bytes that each GPU sends, per byte of S
exposed[k] = (ring * S * beta_link, ring * last_bucket * beta_link)
print(f'k={k}: exposed {1e3 * exposed[k][0]:.0f} ms without overlap '
f'({ring:.1f} S beta_link), {1e3 * exposed[k][1]:.0f} ms with '
f'full overlap (last bucket)')bus bandwidth = 2.44 GB/s (beta_link = 0.41 ns/byte)
k=2: exposed 18 ms without overlap (1.0 S beta_link), 4 ms with full overlap (last bucket)
k=4: exposed 27 ms without overlap (1.5 S beta_link), 5 ms with full overlap (last bucket)
if d2l.num_gpus() >= 2:
beta_link = allreduce_beta()
print(f'bus bandwidth = {1e-9 / beta_link:.2f} GB/s '
f'(beta_link = {1e9 * beta_link:.2f} ns/byte)')
exposed = {} # Predicted exposed seconds per step
for k in (2, 4):
ring = 2 * (k - 1) / k # Bytes that each GPU sends, per byte of S
exposed[k] = (ring * S * beta_link, ring * last_bucket * beta_link)
print(f'k={k}: exposed {1e3 * exposed[k][0]:.0f} ms without overlap '
f'({ring:.1f} S beta_link), {1e3 * exposed[k][1]:.0f} ms with '
f'full overlap (last bucket)')bus bandwidth = 2.43 GB/s (beta_link = 0.41 ns/byte)
k=2: exposed 18 ms without overlap (1.0 S beta_link), 8 ms with full overlap (last bucket)
k=4: exposed 28 ms without overlap (1.5 S beta_link), 12 ms with full overlap (last bucket)
接着我们在 \(k \in \{1, 2, 4\}\) 块 GPU 上以每 GPU 256 样本做弱扩展基准测试(step_time(k, 256)),并将实测吞吐量、扩展效率及暴露开销 weak[k] - weak[1] 与两种预测对比:
ks = [k for k in (1, 2, 4) if k <= d2l.num_gpus()]
weak = {k: step_time(k, 256) for k in ks}
for k in ks:
print(f'{k} GPU(s): {k * 256 / weak[k]:5.0f} examples/s, speedup '
f'{k * weak[1] / weak[k]:.2f}, efficiency {weak[1] / weak[k]:.0%}')
if k > 1: # Predicted: the one-GPU step plus the exposed communication
none, full = (weak[1] / (weak[1] + e) for e in exposed[k])
print(f'{"":10s}predicted {none:.0%} without overlap, {full:.0%} '
f'with full overlap; exposed {1e3 * (weak[k] - weak[1]):.0f} ms')1 GPU(s): 2285 examples/s, speedup 1.00, efficiency 100%
2 GPU(s): 4039 examples/s, speedup 1.77, efficiency 88%
predicted 86% without overlap, 97% with full overlap; exposed 15 ms
4 GPU(s): 7573 examples/s, speedup 3.31, efficiency 83%
predicted 80% without overlap, 95% with full overlap; exposed 23 ms
ks = [k for k in (1, 2, 4) if k <= d2l.num_gpus()]
weak = {k: step_time(k, 256) for k in ks}
for k in ks:
print(f'{k} GPU(s): {k * 256 / weak[k]:5.0f} examples/s, speedup '
f'{k * weak[1] / weak[k]:.2f}, efficiency {weak[1] / weak[k]:.0%}')
if k > 1: # Predicted: the one-GPU step plus the exposed communication
none, full = (weak[1] / (weak[1] + e) for e in exposed[k])
print(f'{"":10s}predicted {none:.0%} without overlap, {full:.0%} '
f'with full overlap; exposed {1e3 * (weak[k] - weak[1]):.0f} ms')1 GPU(s): 2555 examples/s, speedup 1.00, efficiency 100%
2 GPU(s): 4275 examples/s, speedup 1.67, efficiency 84%
predicted 84% without overlap, 93% with full overlap; exposed 20 ms
4 GPU(s): 7859 examples/s, speedup 3.08, efficiency 77%
predicted 78% without overlap, 90% with full overlap; exposed 30 ms
在 ~2.4 GB/s 总线带宽下,45 MB 的无重叠全归约在两块 GPU 上耗时 ~18 ms,在四块 GPU 上耗时 ~28 ms。在我们的弱扩展实测中,四块 GPU 达到了单块 GPU 吞吐量的 \(3.1\text{--}3.3\times\)(扩展效率 77–83%)——与无重叠预测高度吻合,远低于理想完全重叠桶模型的预期。
在强扩展下(固定全局批量 512 个样本,因此 \(k\) 块 GPU 每块只处理 \(512/k\) 个样本,而通信量保持不变),\(k = 4\) 时的效率进一步下降:
strong = {k: step_time(k, 512 // k) for k in ks}
for k in ks:
print(f'{k} GPU(s), {512 // k} examples each: speedup '
f'{strong[1] / strong[k]:.2f}, efficiency '
f'{strong[1] / strong[k] / k:.0%}')
d2l.plot(ks, [ks, [k * weak[1] / weak[k] for k in ks],
[strong[1] / strong[k] for k in ks]], 'GPUs', 'speedup',
legend=['linear', 'weak (256 per GPU)', 'strong (512 in all)'],
fmts=('k:', '-o', '--s'))1 GPU(s), 512 examples each: speedup 1.00, efficiency 100%
2 GPU(s), 256 examples each: speedup 1.78, efficiency 89%
4 GPU(s), 128 examples each: speedup 2.81, efficiency 70%
strong = {k: step_time(k, 512 // k) for k in ks}
for k in ks:
print(f'{k} GPU(s), {512 // k} examples each: speedup '
f'{strong[1] / strong[k]:.2f}, efficiency '
f'{strong[1] / strong[k] / k:.0%}')
d2l.plot(ks, [ks, [k * weak[1] / weak[k] for k in ks],
[strong[1] / strong[k] for k in ks]], 'GPUs', 'speedup',
legend=['linear', 'weak (256 per GPU)', 'strong (512 in all)'],
fmts=('k:', '-o', '--s'))1 GPU(s), 512 examples each: speedup 1.00, efficiency 100%
2 GPU(s), 256 examples each: speedup 1.70, efficiency 85%
4 GPU(s), 128 examples each: speedup 2.55, efficiency 64%
13.6.2.1 桶模型的隐含假设
为什么重叠隐藏的通信时间如此之少?桶模型暗含三条假设:(1)每个桶的全归约在反向传播期间启动;(2)NCCL 以其裸基准速率运行;(3)NCCL 与反向计算内核并发运行时不会拖慢后者。我们在三种配置下剖析 GPU 0——1 块 GPU、2 块 GPU 不通信、2 块 GPU 开启通信——来逐一检验这三条假设:
def profile_step(k, b, communicate=True):
"""Seconds per DDP step on k GPUs with b examples per GPU, and device
milliseconds per step on GPU 0 of computation and of NCCL's kernels;
without communication, every GPU steps on its own shard's gradient."""
ranks = d2l.torchrun(TRAIN_DDP, k, b, 50, random.getrandbits(32),
int(communicate), 1)
return (max(r['step_time'] for r in ranks), ranks[0]['compute'],
ranks[0]['comm'])def local_stepper(k, b):
"""The step of `stepper` without communication: inside shard_map every
GPU sees only its shard, normalizes it with the shard's own batch
statistics, and steps on its own shard's gradient."""
mesh, model, opt, (X, y) = setup(k, d2l.get_key())
batches = minibatches(mesh, k * b)
graphdef, state = nnx.split((model, opt))
def local(state, X, y, idx):
model, opt = nnx.merge(graphdef, state)
train_step(model, opt, X, y, idx)
return nnx.state((model, opt))
# With check_vma=False autodiff adds no sum over the GPUs, and the
# copies, which then drift apart, are returned as if they were equal
local = jax.jit(jax.shard_map(local, mesh=mesh, check_vma=False,
in_specs=(P(), P(), P(), P('data')),
out_specs=P()))
def step():
nonlocal state
state = local(state, X, y, next(batches))
return state
return step
def profile_step(k, b, communicate=True):
"""Seconds per step on k GPUs with b examples per GPU, and device
milliseconds per step on GPU 0 of computation and of NCCL's kernels:
the two gradient allreduces and the small allreduces of the batch
normalization statistics."""
step = stepper(k, b) if communicate else local_stepper(k, b)
t = d2l.Benchmark(step, warmup=10, repeats=50).time
kernels = d2l.kernel_times(step)
comm = sum(ms for name, ms in kernels.items() if 'nccl' in name.lower())
return t, sum(kernels.values()) - comm, comm在每 GPU \(b = 256\) 个样本下,对这三种配置(单 GPU、双 GPU 无梯度同步、双 GPU 开启全归约)运行 profile_step,即可把挂钟单步时间拆分为设备计算时间与 NCCL 内核时间:
if d2l.num_gpus() >= 2:
for k, communicate in ((1, True), (2, False), (2, True)):
t, compute, comm = profile_step(k, 256, communicate)
name = f'{k} GPU' + ('s' if k > 1 else '') + (
'' if communicate else ' without communication')
print(f'{name + ":":30s}{1e3 * t:6.1f} ms per step; GPU 0 computes '
f'{compute:6.1f} ms, communicates {comm:5.1f} ms')1 GPU: 112.1 ms per step; GPU 0 computes 111.9 ms, communicates 0.0 ms
2 GPUs without communication: 111.9 ms per step; GPU 0 computes 111.5 ms, communicates 0.0 ms
2 GPUs: 126.8 ms per step; GPU 0 computes 124.6 ms, communicates 20.0 ms
if d2l.num_gpus() >= 2:
for k, communicate in ((1, True), (2, False), (2, True)):
t, compute, comm = profile_step(k, 256, communicate)
name = f'{k} GPU' + ('s' if k > 1 else '') + (
'' if communicate else ' without communication')
print(f'{name + ":":30s}{1e3 * t:6.1f} ms per step; GPU 0 computes '
f'{compute:6.1f} ms, communicates {comm:5.1f} ms')1 GPU: 100.3 ms per step; GPU 0 computes 100.1 ms, communicates 0.0 ms
2 GPUs without communication: 100.6 ms per step; GPU 0 computes 100.0 ms, communicates 0.0 ms
2 GPUs: 119.1 ms per step; GPU 0 computes 107.8 ms, communicates 21.0 ms
双 GPU 不通信时的单步速度与单 GPU 完全相同,而且 NCCL 内核运行时间为 20–22 ms(与 18 ms 的裸基准相符)。真正失效的是第三条假设:当 NCCL 与反向传播并发运行时,计算内核本身变慢了 8–13 ms。在不支持点对点访问的 GPU 上,NCCL 使用自身的 GPU SM 内核经由主机内存复制数据,这些内核会占用本可用于反向传播的流式多处理器与显存带宽。
NCCL 2.28–2.30 中存在一个未写入文档的标志(NCCL_SHM_USE_CUDA_MEMCPY=1),在裸微基准中可以将这些经主机内存的复制卸载到 GPU 的 DMA 复制引擎:
然而当全归约与反向计算重叠时,同一个标志会导致 DDP 死锁。
if d2l.num_gpus() >= 2:
# An undocumented parameter of NCCL's transport through host memory. It
# exists in NCCL 2.28.9 (bundled with PyTorch 2.11) and 2.30.4 (with
# jaxlib 0.12); the library of NCCL 2.31.2 no longer contains it
beta_ce = allreduce_beta({'NCCL_SHM_USE_CUDA_MEMCPY': '1'})
print(f'bus bandwidth {1e-9 / beta_link:.2f} GB/s by default, '
f'{1e-9 / beta_ce:.2f} GB/s with the copy engines '
f'({beta_link / beta_ce:.1f}x)')bus bandwidth 2.44 GB/s by default, 11.53 GB/s with the copy engines (4.7x)
if d2l.num_gpus() >= 2:
# An undocumented parameter of NCCL's transport through host memory. It
# exists in NCCL 2.28.9 (bundled with PyTorch 2.11) and 2.30.4 (with
# jaxlib 0.12); the library of NCCL 2.31.2 no longer contains it
beta_ce = allreduce_beta({'NCCL_SHM_USE_CUDA_MEMCPY': '1'})
print(f'bus bandwidth {1e-9 / beta_link:.2f} GB/s by default, '
f'{1e-9 / beta_ce:.2f} GB/s with the copy engines '
f'({beta_link / beta_ce:.1f}x)')bus bandwidth 2.43 GB/s by default, 10.98 GB/s with the copy engines (4.5x)
在通过 NVLink 互联的数据中心 GPU 上(单向 450–900 GB/s,见 13.2.4.2 节),ResNet-18 的 45 MB 全归约耗时远低于一毫秒,几乎呈线性扩展。不过,即便扩展近乎理想,数据并行仍然在每张卡上复制全部 \(16N\) 字节的参数与优化器状态;13.7 节 将把这部分状态跨 GPU 分片。
13.6.3 小结
生产级数据并行要么通过 NCCL 同步的 \(k\) 个独立进程驱动 \(k\) 块 GPU,要么通过单个编译器切分的程序驱动,并将梯度分组为 25–30 MiB 的桶以使全归约与反向传播重叠。与单 GPU 参考对照的单步校验能揭示批量规范化究竟使用的是分片本地统计量,还是经额外集合通信得到的全局统计量。在我们的四块 RTX 4090(以 2.4 GB/s 总线带宽经主机内存通信)上,弱扩展下四块 GPU 可提供单卡 \(3.1\text{--}3.3\times\) 的吞吐量,而内核剖析表明,主机中转 NCCL 内核引发的 SM 争用吞噬了通信与反向计算重叠所省下的大部分时间。
13.6.4 练习
- [code] 切分数据。在
TRAIN_DDP中,进程 rank \(r\) 在第 \(s\) 步从共享随机排列中取出起始位置为 \((sk + r)b\) 的切片。- 从该偏移中移除
rank,使每个进程拿到相同的 \(b\) 个样本。预测 \(k = 2\) 时step_time与平均梯度的表现,并通过在每个 rank 上打印小批量校验和加以验证。 - 恢复偏移,但给每个 rank 分配不同的随机种子。小批量切分的哪项性质会因此丧失?
- 设计一个轻量级运行时断言,在第一步就能捕获各 rank 数据分片相同的错误。
- 从该偏移中移除
- 弱扩展外推。假设 \(k\) 块 GPU 上一步的耗时等于单 GPU 时间 \(t_1\) 加上与环形流量 \(2(k-1)S/k\) 成正比的暴露通信时间。
- 用单个常数表示弱扩展效率 \(E(k) = t_1 / t_{\textrm{step}}(k)\),根据实测 \(E(2)\) 校准该常数,并将其对 \(E(4)\) 的预测与 13.6.2 节 中的实测值作比较。
- 若每块 GPU 对 \(a\) 个 256 样本微批量做梯度累积(仅在最后一个微批量通信),求能将 \(E(4)\) 提升至 95% 的最小 \(a\),并说明全局批量大小如何变化。
- [code] 桶大小。● 对分桶重叠(图 13.6.1)建模:假设耗时 \(t_b\) 的反向传播在时刻 \(i\,t_b/n\)(\(i = 1, \ldots, n\))依次释放 \(n\) 个等大的桶,每个桶的全归约串行耗时 \(\alpha + \tau/n\),其中 \(\tau = S\,\beta_\textrm{link}\)。
- 证明反向传播结束后暴露在外的通信时间为 \[t_{\textrm{exposed}}(n) = \max\Bigl(\alpha + \frac{\tau}{n},\; n\alpha + \tau - \frac{n-1}{n}\,t_b\Bigr), \tag{13.6.1}\] 并分别求 \(\tau < t_b\) 与 \(\tau > t_b\) 时的最优 \(n\)。
- 在 \(k = 2\) 时将
DDP中的bucket_cap_mb从 1 MB 扫描到 100 MB,并将实测暴露通信时间与模型预测作比较。
- [code] 同步批量规范化。● 13.6.1 节 的单步校验表明,DDP 默认使用本地统计量对各分片做规范化。
- 在用
DDP包装之前,用nn.SyncBatchNorm.convert_sync_batchnorm转换CHECK_DDP中的model并重做校验。此时它与哪一种单 GPU 参考吻合? - 统计
SyncBatchNorm每步新增的集合通信次数,测量 \(k = 2\) 与 \(k = 4\) 时的step_time,并解释为何其耗时超过其字节量乘以 \(\beta_\textrm{link}\)。
- 在用
- [code] 切分数据。在
minibatches中,索引使用P('data')放置。- 改用
P()放置索引,使每块 GPU 都收到全部索引。预测编译后的train_step包含哪些集合通信,以及step_time(2, 256)与step_time(1, 256)相比如何,然后检验这两点。 - 恢复
P('data'),并在train_step内将X[idx]约束为NamedSharding(mesh, P(None, 'data')),从而沿图像高度跨 GPU 切分。对于 \(3 \times 3\) 卷积,相邻 GPU 必须交换哪些边界值?编译后的 HLO 中会出现哪种集合通信?
- 改用
- 弱扩展外推。假设 \(k\) 块 GPU 上一步的耗时等于单 GPU 时间 \(t_1\) 加上与环形流量 \(2(k-1)S/k\) 成正比的暴露通信时间。
- 用单个常数表示弱扩展效率 \(E(k) = t_1 / t_{\textrm{step}}(k)\),根据实测 \(E(2)\) 校准该常数,并将其对 \(E(4)\) 的预测与 13.6.2 节 中的实测值作比较。
- 若每块 GPU 对 \(a\) 个 256 样本微批量做梯度累积(仅在最后一个微批量通信),求能将 \(E(4)\) 提升至 95% 的最小 \(a\),并说明全局批量大小如何变化。
- [code] 桶大小。● 对分桶重叠(图 13.6.1)建模:假设耗时 \(t_b\) 的反向传播在时刻 \(i\,t_b/n\)(\(i = 1, \ldots, n\))依次释放 \(n\) 个等大的桶,每个桶的全归约串行耗时 \(\alpha + \tau/n\),其中 \(\tau = S\,\beta_\textrm{link}\)。
- 证明反向传播结束后暴露在外的通信时间为 \[t_{\textrm{exposed}}(n) = \max\Bigl(\alpha + \frac{\tau}{n},\; n\alpha + \tau - \frac{n-1}{n}\,t_b\Bigr),\] 并分别求 \(\tau < t_b\) 与 \(\tau > t_b\) 时的最优 \(n\)。
- 在独立进程中将
--xla_gpu_all_reduce_combine_threshold_bytes从 1 MB 扫描到 100 MB,统计所得梯度全归约次数,并将实测暴露通信时间与模型预测作比较。
- [code] 批量规范化统计量。● 在带有
Auto网格轴的nnx.jit下,批量规范化会跨所有 GPU 计算全局统计量。- 根据
resnet18中BatchNorm层的数量以及前向与反向传播,解释allreduce_megabytes(compiled)中的 74 次小全归约。 - 在编译前调用
model.eval(),使BatchNorm改用滑动平均而非批量统计量,验证这些小全归约随之消失,并测量它们在 \(k = 1, 2, 4\) 时耗费多少单步时间。
- 根据