import os
import time
# 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.5 从零开始实现多 GPU 训练
到目前为止,我们的每次训练都只用了一块 GPU,尽管构建工作站上装有四块。利用全部 \(k\) 块 GPU 最简单的方法是数据并行:给每块 GPU 分配一份完整的模型副本和每个小批量的 \(1/k\),通过全归约(allreduce)跨 GPU 对所得梯度求和,然后在每张卡上应用相同的参数更新。
在我们的工作站上,GPU 间通信经由 PCIe 4.0 通过主机内存(DRAM)中转(13.2.4.2 节),每条链路的标称上限为 32 GB/s——大约比单卡 1 TB/s 的板载显存慢 \(30\times\)。只有当第二块 GPU 分担的计算耗时超过它所增加的梯度交换(以及主机派发开销)耗时,它才能缩短单步时间。本节中,我们手动实现数据并行,推导集合通信库所使用的环形全归约(ring allreduce)算法,并构建一个由单独测得的常数来预测多 GPU 单步时间的代价模型。我们在 Fashion-MNIST 上的 LeNet 模型上检验这一模型,它极短的单步耗时能清楚暴露固定的主机与通信开销。
import time
from functools import partial
from jax.flatten_util import ravel_pytree
from jax.sharding import NamedSharding, PartitionSpec as P在 PyTorch 中,我们还启用 tf32 矩阵乘法和 cuDNN 卷积自动调优,使固定形状的内核以其稳态速度运行:
torch.set_float32_matmul_precision('high')
torch.backends.cudnn.benchmark = True # Time convolution algorithms per shape13.5.1 三种切分方式
模型及其小批量可以通过三种基本方式跨设备划分(图 13.5.1):
- 数据并行在每台设备上复制完整模型,将小批量跨设备切分,并在每步对梯度求和一次。只要模型能放进单块 GPU,它就适用,但每台设备仍须保存全部 \(16N\) 字节的 fp32 Adam 训练状态(13.4 节)。
- 流水线并行将层堆叠跨设备切分,在阶段边界前向传递激活值、反向传递梯度(1)。
- 张量并行将单个权重矩阵跨设备切分(正如 2012 年将 AlexNet 切分到两块 3 GB GPU 上 (Krizhevsky 等 2012年)),每层需要通信数次(13.7 节 中的 3)。
13.5.2 手动实现数据并行
在 \(k\) 台设备上执行一步数据并行包含四个阶段(图 13.5.2):将小批量切分为 \(k\) 个等大的分片;在各自设备上计算对应分片的梯度;通过全归约对这 \(k\) 份梯度求和,使每台设备都持有总和;在每台设备上应用完全相同的参数更新。由于所有副本都从相同的参数出发并执行相同的更新,它们始终保持同步,无需再次复制权重。
13.5.2.1 模型与数据
我们将 LeNet(6.6 节,采用 ReLU 激活与 He 初始化)写成一个显式接收参数张量列表的函数,这样每一次跨设备复制都清晰可见。它的 61,706 个 fp32 参数仅占 247 KB,而 60,000 张 Fashion-MNIST 训练图像仅占 188 MB——小到足以在每块 GPU 上都保留一份数据集副本,从而确保主机数据加载绝不会混入计时结果。
def new_params():
"""LeNet's parameters on the CPU: He-initialized weights, zero biases."""
params = []
for shape in [(6, 1, 5, 5), (16, 6, 5, 5), (120, 400), (84, 120),
(10, 84)]:
fan_in = math.prod(shape[1:])
params += [torch.randn(shape) * math.sqrt(2 / fan_in),
torch.zeros(shape[0])]
return params
def lenet(params, X):
W1, b1, W2, b2, W3, b3, W4, b4, W5, b5 = params
H = F.avg_pool2d(F.relu(F.conv2d(X, W1, b1, padding=2)), 2)
H = F.avg_pool2d(F.relu(F.conv2d(H, W2, b2)), 2).flatten(1)
H = F.relu(F.linear(H, W3, b3))
H = F.relu(F.linear(H, W4, b4))
return F.linear(H, W5, b5)
def to_device(split, device):
"""A whole Fashion-MNIST split on `device`: images in [0, 1], labels."""
return split.data.to(device).unsqueeze(1) / 255, split.targets.to(device)def new_params(key):
"""LeNet's parameters: He-initialized weights, zero biases."""
shapes = [(5, 5, 1, 6), (5, 5, 6, 16), (400, 120), (120, 84), (84, 10)]
params = []
for key, shape in zip(jax.random.split(key, len(shapes)), shapes):
fan_in = math.prod(shape[:-1])
params += [jax.random.normal(key, shape) * math.sqrt(2 / fan_in),
jnp.zeros(shape[-1])]
return params
def lenet(params, X):
W1, b1, W2, b2, W3, b3, W4, b4, W5, b5 = params
conv = lambda X, W, padding: jax.lax.conv_general_dilated(
X, W, (1, 1), padding, dimension_numbers=('NHWC', 'HWIO', 'NHWC'))
pool = lambda X: nnx.avg_pool(X, (2, 2), strides=(2, 2))
H = pool(jax.nn.relu(conv(X, W1, ((2, 2), (2, 2))) + b1))
H = pool(jax.nn.relu(conv(H, W2, 'VALID') + b2)).reshape(X.shape[0], -1)
H = jax.nn.relu(H @ W3 + b3)
H = jax.nn.relu(H @ W4 + b4)
return H @ W5 + b5
def to_device(split, sharding):
"""A whole Fashion-MNIST split placed by `sharding`: images in [0, 1],
labels."""
X, y = split
return jax.device_put((X[..., None] / np.float32(255),
y.astype(np.int32)), sharding)我们首先确认至少有两块可用 GPU,将 Fashion-MNIST 训练集复制到两台设备上(train_data),并为下文所有实验生成一份共享的初始参数 base:
assert d2l.num_gpus() >= 2, 'This section needs two GPUs'
data = d2l.FashionMNIST()
devices = [d2l.try_gpu(i) for i in range(2)]
train_data = [to_device(data.train, d) for d in devices] # A copy each
test_data = to_device(data.val, devices[0])
base = new_params() # One initialization for every run below
print(f'{sum(p.numel() for p in base)} parameters in {len(base)} tensors; '
f'images {tuple(train_data[0][0].shape)} on each of 2 devices')61706 parameters in 10 tensors; images (60000, 1, 28, 28) on each of 2 devices
assert jax.device_count() >= 2, 'This section needs two GPUs'
data = d2l.FashionMNIST()
meshes = [jax.make_mesh((k,), ('data',), devices=jax.devices()[:k])
for k in (1, 2)]
train_data = [to_device(data.train, NamedSharding(mesh, P()))
for mesh in meshes] # A copy on every device of each mesh
test_data = (data.val[0][..., None] / np.float32(255),
data.val[1].astype(np.int32))
base = new_params(d2l.get_key()) # One initialization for every run
print(f'{sum(p.size for p in base)} parameters in {len(base)} tensors; '
f'images {train_data[1][0].shape} on each of 2 devices')61706 parameters in 10 tensors; images (60000, 28, 28, 1) on each of 2 devices
在 JAX 中,多设备数组通过 NamedSharding 与 PartitionSpec 放置在具名设备网格(mesh)上(P('data') 将最外层维度沿 'data' 网格轴分片;P() 将完整数组复制到每台设备)。
13.5.2.2 广播与全归约
广播(broadcast)在初始时将参数一次性复制到每台设备;全归约(allreduce)对每台设备上的一个张量求和,并将总和保留在每台设备上。
我们编写一个简单的星形(star)全归约:由设备 0 收集并累加所有张量,再将总和复制回去。
我们使用 jax.shard_map 配合 jax.lax.psum(底层委派给 NCCL)。
def broadcast(params, device):
"""A copy of every tensor in `params` on `device`, ready for autograd."""
return [p.to(device, copy=True).requires_grad_() for p in params]
def allreduce(data):
"""Sum the tensors in `data`, one per device, onto every device."""
for i in range(1, len(data)): # Star: collect and add on device 0 ...
data[0] += data[i].to(data[0].device)
for i in range(1, len(data)): # ... then copy the sum back
data[i].copy_(data[0])def broadcast(params, mesh):
"""A copy of every array in `params` on every device of `mesh`."""
return jax.device_put(params, NamedSharding(mesh, P()))
@partial(jax.jit, static_argnames='mesh')
def allreduce(x, mesh):
"""Sum the rows of `x` (row j on device j); every device gets the sum."""
return jax.shard_map(lambda x_j: jax.lax.psum(x_j, 'data'), mesh=mesh,
in_specs=P('data'), out_specs=P('data'))(x)我们可以这样测试 allreduce:在设备 0 上放置 [1.0, 1.0],在设备 1 上放置 [2.0, 2.0],检查两台设备是否都收到按元素求和的结果 [3.0, 3.0]:
x = [torch.full((1, 2), i + 1.0, device=d) for i, d in enumerate(devices)]
print('before:', [x_j.tolist() for x_j in x])
allreduce(x)
print('after: ', [x_j.tolist() for x_j in x])before: [[[1.0, 1.0]], [[2.0, 2.0]]]
after: [[[3.0, 3.0]], [[3.0, 3.0]]]
x = jax.device_put(jnp.array([[1.0, 1.0], [2.0, 2.0]]),
NamedSharding(meshes[1], P('data')))
print('before:', x.tolist())
print('after: ', allreduce(x, meshes[1]).tolist())before: [[1.0, 1.0], [2.0, 2.0]]
after: [[3.0, 3.0], [3.0, 3.0]]
13.5.2.3 数据并行单步
当 \(k\) 个分片大小相等时,\(k\) 个分片平均损失梯度的均值等于完整小批量的梯度(2)。由于每次全归约调用无论消息大小如何都要支付固定延迟,我们将 LeNet 的 10 个梯度张量拼接成单个一维向量,每步只执行一次全归约。传入 communicate=False 会跳过全归约,便于我们单独测量纯设备计算时间。
def shard_grads(params, data, idx):
"""Gradient of the mean loss on each device's share of the minibatch
`idx` (example indices), as one flat vector per device."""
grads = []
for ps, (X, y), i in zip(params, data, idx.chunk(len(params))):
i = i.to(X.device, non_blocking=True) # Don't wait for the device
F.cross_entropy(lenet(ps, X[i]), y[i]).backward()
grads.append(torch.cat([p.grad.flatten() for p in ps]))
for p in ps:
p.grad = None # The next backward starts from zero
return grads
def train_step(params, data, idx, lr, communicate=True):
"""One data-parallel SGD step on the minibatch `idx`; without
communication, every device steps on its own shard's gradient."""
grads = shard_grads(params, data, idx)
if communicate:
allreduce(grads) # One message per device and step
with torch.no_grad():
for ps, g in zip(params, grads):
for p, g_p in zip(ps, g.split([p.numel() for p in ps])):
p -= lr / len(params) * g_p.view_as(p) # Mean of k gradsdef shard_grad(params, X, y, i):
"""Inside shard_map: the gradient of the mean loss on this device's
share `i` of the minibatch, as one flat vector."""
def loss(p):
return optax.softmax_cross_entropy_with_integer_labels(
lenet(p, X[i]), y[i]).mean()
own = jax.lax.pcast(params, 'data', to='varying') # This device's copy
return ravel_pytree(jax.grad(loss)(own))[0]
@partial(jax.jit, static_argnames=('mesh', 'communicate'))
def train_step(params, data, idx, lr, mesh, communicate=True):
"""One data-parallel SGD step on the minibatch `idx`; without
communication, every device steps on its own shard's gradient."""
unravel = ravel_pytree(params)[1]
def step(params, X, y, i):
g = shard_grad(params, X, y, i)
if communicate:
g = jax.lax.psum(g, 'data') # Allreduce
k = jax.lax.axis_size('data')
return jax.tree.map(lambda p, g_p: p - lr / k * g_p, params,
unravel(g))
out = P() if communicate else P('data') # Copies differ without the sum
return jax.shard_map(step, mesh=mesh, in_specs=(P(), P(), P(), P('data')),
out_specs=out)(params, *data, idx)13.5.2.4 单步校验
在开始任何计时之前,我们先验证两块 GPU 上的一步数据并行与单块 GPU 在相同 256 个样本上的一步更新结果一致(使用严格的 fp32 算术,避免 tf32 下的卷积算法差异掩盖诸如忘记除以 \(k\) 之类的错误)。
idx = torch.randperm(len(data.train))[:256]
updates = []
torch.set_float32_matmul_precision('highest') # True fp32 in matmuls ...
with torch.backends.cudnn.flags(enabled=True, allow_tf32=False): # ... convs
for k in (1, 2):
params = [broadcast(base, d) for d in devices[:k]]
train_step(params, train_data[:k], idx, lr=0.2)
updates.append([p.detach().cpu() - b
for p, b in zip(params[0], base)])
torch.set_float32_matmul_precision('high')
largest = max(u.abs().max() for u in updates[0])
diff = max((u1 - u2).abs().max() for u1, u2 in zip(*updates))
print(f'largest update {largest:.1e}, largest difference {diff:.1e}')largest update 2.4e-02, largest difference 3.0e-08
idx = np.random.default_rng().permutation(len(data.train[1]))[:256]
updates = []
with jax.default_matmul_precision('highest'): # True fp32
for mesh, data_k in zip(meshes, train_data):
i = jax.device_put(idx, NamedSharding(mesh, P('data')))
params = train_step(broadcast(base, mesh), data_k, i, 0.2, mesh)
updates.append([np.asarray(p) - np.asarray(b)
for p, b in zip(params, base)])
largest = max(np.abs(u).max() for u in updates[0])
diff = max(np.abs(u1 - u2).max() for u1, u2 in zip(*updates))
print(f'largest update {largest:.1e}, largest difference {diff:.1e}')largest update 1.9e-02, largest difference 3.0e-08
单 GPU 与双 GPU 的更新结果在 fp32 舍入误差(~\(10^{-7}\))范围内一致。
13.5.3 环形全归约
星形全归约将所有流量都经由设备 0 路由,迫使这一中心节点为大小为 \(S\) 的梯度发送和接收 \((k-1)S\) 字节。每增加一台设备,中心节点的负载就随之增长,而其余每台设备在每个方向上只需处理 \(S\) 字节(图 13.5.3,左)。
环形全归约 (Patarasuk 和 Yuan 2009年; Sergeev 和 Del Balso 2018年) 去除了中心节点。它将 \(k\) 台设备排成逻辑环并均匀分摊流量:把每台设备 \(S\) 字节的梯度切分为 \(k\) 个大小为 \(S/k\) 字节的块,执行两个各包含 \(k - 1\) 步的阶段(图 13.5.4):
- 归约散播:在 \(k - 1\) 步中的每一步,每台设备向其后继发送一个块,并将从前驱收到的块累加到本地副本中。经过 \(k - 1\) 步后,每台设备都持有一个互不相同的块的完整总和。
- 全收集:在接下来的 \(k - 1\) 步中,已完成的块沿环传递,直到每台设备都持有全部 \(k\) 个已求和的块。
每台设备在每个阶段发送 \((k-1)S/k\) 字节,总计为
\[ \frac{2(k-1)}{k}\, S \quad\textrm{bytes per device.} \tag{13.5.1}\]
当 \(k = 2\) 时,每台设备的通信量为 \(S\),而且无论环中加入多少台设备,每台设备的通信量都严格低于 \(2S\)。此外,这两个阶段还可以独立使用:分片训练(13.7 节)使用归约散播来划分求和后的梯度,并用全收集来组装分片权重。
我们用 NumPy 实现这一两阶段环形算法,同时记录每台设备上累加的块以及每台设备发送的总字节数 sent:
def ring_allreduce(xs):
"""Ring allreduce of the vectors xs, one per device; returns every
device's result and the bytes that each device sent."""
k = len(xs)
chunks = [np.array_split(x.copy(), k) for x in xs] # chunks[j][c]
sent = 0
for s in range(k - 1): # Reduce-scatter: add the received chunk
msgs = [chunks[j][(j - s) % k].copy() for j in range(k)]
for j, msg in enumerate(msgs):
chunks[(j + 1) % k][(j - s) % k] += msg
sent += msgs[0].nbytes
for s in range(k - 1): # All-gather: replace by the received chunk
msgs = [chunks[j][(j + 1 - s) % k].copy() for j in range(k)]
for j, msg in enumerate(msgs):
chunks[(j + 1) % k][(j + 1 - s) % k] = msg
sent += msgs[0].nbytes
return [np.concatenate(c) for c in chunks], sentdef ring_allreduce(xs):
"""Ring allreduce of the vectors xs, one per device; returns every
device's result and the bytes that each device sent."""
k = len(xs)
chunks = [np.array_split(x.copy(), k) for x in xs] # chunks[j][c]
sent = 0
for s in range(k - 1): # Reduce-scatter: add the received chunk
msgs = [chunks[j][(j - s) % k].copy() for j in range(k)]
for j, msg in enumerate(msgs):
chunks[(j + 1) % k][(j - s) % k] += msg
sent += msgs[0].nbytes
for s in range(k - 1): # All-gather: replace by the received chunk
msgs = [chunks[j][(j + 1 - s) % k].copy() for j in range(k)]
for j, msg in enumerate(msgs):
chunks[(j + 1) % k][(j + 1 - s) % k] = msg
sent += msgs[0].nbytes
return [np.concatenate(c) for c in chunks], sent在 \(k \in \{2, 4, 8, 16\}\) 台设备上用随机 1,024 维浮点向量测试 ring_allreduce,结果证实每台设备都收到精确总和,且发送量恰好为 \(2(k-1)S/k\) 字节:
rng = np.random.default_rng()
for k in (2, 4, 8, 16):
xs = [rng.standard_normal(1024, dtype=np.float32) for _ in range(k)]
results, sent = ring_allreduce(xs)
correct = all(np.allclose(r, sum(xs), atol=1e-5) for r in results)
print(f'k = {k:2d}: every device holds the sum: {correct}; '
f'sent per device: {sent / xs[0].nbytes:.2f} S')k = 2: every device holds the sum: True; sent per device: 1.00 S
k = 4: every device holds the sum: True; sent per device: 1.50 S
k = 8: every device holds the sum: True; sent per device: 1.75 S
k = 16: every device holds the sum: True; sent per device: 1.88 S
rng = np.random.default_rng()
for k in (2, 4, 8, 16):
xs = [rng.standard_normal(1024, dtype=np.float32) for _ in range(k)]
results, sent = ring_allreduce(xs)
correct = all(np.allclose(r, sum(xs), atol=1e-5) for r in results)
print(f'k = {k:2d}: every device holds the sum: {correct}; '
f'sent per device: {sent / xs[0].nbytes:.2f} S')k = 2: every device holds the sum: True; sent per device: 1.00 S
k = 4: every device holds the sum: True; sent per device: 1.50 S
k = 8: every device holds the sum: True; sent per device: 1.75 S
k = 16: every device holds the sum: True; sent per device: 1.88 S
尽管每台设备的传输字节数以 \(2S\) 为上界,环形算法需要执行 \(2(k-1)\) 次串行跳传,每一跳都要支付启动延迟。对于多 GPU 上的小消息,集合通信库会切换到深度为 \(\log_2 k\) 的树形算法(5)。
13.5.4 通信代价与扩展性
13.5.4.1 单步代价模型
使用延迟–带宽模型 (Hockney 1994年; Thakur 等 2005年),每次全归约调用都要支付固定启动延迟 \(\alpha\),加上每台设备每发送一字节的时间 \(\beta_{\textrm{link}}\)(全归约总线带宽的倒数)。在不重叠的情况下,\(k\) 台设备在全局批量为 \(B\) 且执行 \(c\) 次全归约调用时,单步耗时为
\[ t_{\textrm{step}}(k) \approx t_{\textrm{compute}}(B/k) + c\,\alpha + \frac{2(k-1)}{k}\,S\,\beta_{\textrm{link}}, \tag{13.5.2}\]
其中 \(k = 1\) 时 \(c = 0\)。只有满足 \(t_{\textrm{compute}}(B) - t_{\textrm{compute}}(B/2) > c\alpha + S\,\beta_{\textrm{link}}\),第二台设备才能缩短单步时间。
13.5.4.2 全归约的延迟与带宽
我们在两块 GPU 上用 1 个浮点数的全归约测量 \(\alpha\),用 \(2^{26}\) 个浮点数(268 MB)的全归约测量 \(\beta_{\textrm{link}}\):
def allreduce_time(n, devices, calls):
"""Seconds per allreduce of n floats per device."""
x = [torch.zeros(n, device=d) for d in devices]
return d2l.Benchmark(lambda: allreduce(x), warmup=10 * calls,
repeats=3 * calls, devices=devices).time
alpha = allreduce_time(1, devices, calls=100) # Our star: two copies in turn
n = 2**26 # 64M floats ...
S = 4 * n # ... 268 MB (256 MiB) per device
beta_link = (allreduce_time(n, devices, calls=3) - alpha) / S # s per byte
print(f'alpha = {1e6 * alpha:.0f} us, beta_link = {1e9 * beta_link:.2f} '
f'ns/byte (bus bandwidth {1e-9 / beta_link:.1f} GB/s)')alpha = 56 us, beta_link = 0.11 ns/byte (bus bandwidth 9.5 GB/s)
def allreduce_time(n, mesh, calls):
"""Seconds per allreduce of n floats per device."""
x = jnp.zeros((mesh.size, n), device=NamedSharding(mesh, P('data')))
return d2l.Benchmark(lambda: allreduce(x, mesh), repeats=calls).time
def program_time(m, mesh, calls=300):
"""Seconds per call of one compiled program that makes m allreduces of
one float, each on the result of the one before."""
def chain(x):
for _ in range(m): # Each allreduce waits for the last
x = jax.lax.pmean(x, 'data')
return x
f = jax.jit(jax.shard_map(chain, mesh=mesh, in_specs=P('data'),
out_specs=P('data')))
x = jnp.zeros((mesh.size, 1), device=NamedSharding(mesh, P('data')))
return d2l.Benchmark(lambda: f(x), warmup=10, repeats=calls).time
# The training step's psum runs inside a program that is dispatched anyway,
# so alpha is what each further allreduce adds to one program
alpha = (program_time(10, meshes[1]) - program_time(1, meshes[1])) / 9
n = 2**26 # 64M floats ...
S = 4 * n # ... 268 MB (256 MiB) per device
# Both calls dispatch a program of their own; their difference is the bytes
beta_link = (allreduce_time(n, meshes[1], calls=3)
- allreduce_time(1, meshes[1], calls=100)) / S # s per byte
print(f'alpha = {1e6 * alpha:.0f} us, beta_link = {1e9 * beta_link:.2f} '
f'ns/byte (bus bandwidth {1e-9 / beta_link:.1f} GB/s)')alpha = 25 us, beta_link = 0.41 ns/byte (bus bandwidth 2.4 GB/s)
为了检验 式 13.5.2 能否预测梯度融合的收益,我们将 LeNet 的 10 个梯度张量(共 \(S = 247\) KB)分别做全归约(\(c = 10\)),并与拼接成单个一维向量后的全归约(\(c = 1\))作对比,两者之差应当为 \(9\alpha\):
grads = [[torch.zeros_like(p, device=d) for p in base] for d in devices]
flat = [torch.cat([g.flatten() for g in G]) for G in grads]
def separately():
for g in zip(*grads): # One allreduce per tensor
allreduce(list(g))
n_bytes, c = flat[0].nbytes, len(base)
for name, f, calls in (('separately', separately, c),
('at once', lambda: allreduce(flat), 1)):
t = d2l.Benchmark(f, warmup=1000, repeats=300, devices=devices).time
print(f'{name:10s}: {1e6 * t:4.0f} us measured, '
f'{1e6 * (calls * alpha + n_bytes * beta_link):4.0f} us predicted')separately: 572 us measured, 587 us predicted
at once : 81 us measured, 82 us predicted
mesh = meshes[1]
sizes = [p.size for p in base]
flat = jnp.zeros((mesh.size, sum(sizes)), device=NamedSharding(mesh, P('data')))
n_bytes, c = flat.nbytes // mesh.size, len(base) # Bytes per device
def separately(g):
"""One psum per gradient tensor, each after the one before; without the
barrier, XLA would merge the ten into one allreduce."""
out = []
for g_i in jnp.split(g, np.cumsum(sizes)[:-1], axis=1):
if out:
g_i, _ = jax.lax.optimization_barrier((g_i, out[-1]))
out.append(jax.lax.psum(g_i, 'data'))
return jnp.concatenate(out, axis=1)
t = {}
for name, f in (('separately', separately),
('at once', lambda g: jax.lax.psum(g, 'data'))):
f = jax.jit(jax.shard_map(f, mesh=mesh, in_specs=P('data'),
out_specs=P('data')))
t[name] = d2l.Benchmark(lambda: f(flat), warmup=10, repeats=300).time
print(f'{name:10s}: {1e6 * t[name]:4.0f} us measured')
# Both programs are dispatched once and move the same bytes
print(f'difference: {1e6 * (t["separately"] - t["at once"]):4.0f} us '
f'measured, {1e6 * (c - 1) * alpha:4.0f} us predicted by {c - 1} alpha')separately: 524 us measured
at once : 287 us measured
difference: 236 us measured, 221 us predicted by 9 alpha
对于 247 KB 的梯度,多出的九次消息封装开销(\(9\alpha\))比传输里面所有字节还要耗时——这正是生产级数据并行库在通信前把小梯度打包成大桶的原因(13.6 节)。
13.5.4.3 单 GPU 与双 GPU 上的 LeNet
在两块 GPU 上运行 LeNet 之前,我们先剖析它在单块 GPU 上处理 256 个样本的小批量时的本地工作:
params = [broadcast(base, devices[0])]
step = lambda: train_step(params, train_data[:1], idx, 0.2, communicate=False)
t = d2l.Benchmark(step, warmup=500, repeats=150, devices=devices[:1]).time
d2l.show_profile(d2l.kernel_times(step, steps=100), 1e3 * t, rows=4)wall clock 2.91 ms per step, device busy 0.30 ms (10%), matrix products 43%
0.05 ms 16% Kernel<cutlass_tensorop_s1688dgrad_optimized_tf32_12
0.04 ms 12% implicit_convolve_sgemm<float, float, 128, 5, 5, 3,
0.03 ms 10% wgrad_alg0_engine<float, 128, 5, 5, 3, 3, 3, false,
0.03 ms 9% avg_pool2d_backward_out_cuda_frame<float, float, int
mesh, params = meshes[0], broadcast(base, meshes[0])
i = jax.device_put(idx, NamedSharding(mesh, P('data')))
step = lambda: train_step(params, train_data[0], i, 0.2, mesh,
communicate=False)
t = d2l.Benchmark(step, repeats=500).time
d2l.show_profile(d2l.kernel_times(step, steps=100), 1e3 * t, rows=4)wall clock 0.40 ms per step, device busy 0.17 ms (42%), matrix products 30%
0.02 ms 12% _5x_cudnn_ampere_scudnn_128x32_relu_small_nn_v1
0.02 ms 11% dgrad2d_alg1_1<float, 0, 6, 7, 5, 4, 5, false, true>
0.02 ms 10% implicit_convolve_sgemm<float, float, 128, 5, 5, 3,
0.01 ms 8% fft2d_r2c_32x32<float, false, 0u, false>
GPU 在单步的大部分时间里都处于空闲状态:批量大小为 256 时的 LeNet 属于开销受限,因此单步时间就等于主机派发时间 \(h_{\textrm{step}}\)。于是,在单块 GPU 上把批量从 256 减半到 128 几乎不改变单步时间,而用单个主机线程驱动两块 GPU 则大约需要 \(2 h_{\textrm{step}}\)(图 13.5.5):
params, t_local = [broadcast(base, d) for d in devices], {}
for k, b in ((1, 256), (1, 128), (2, 128)):
t_local[k, b] = d2l.Benchmark(
lambda: train_step(params[:k], train_data[:k], idx[:k * b], 0.2,
communicate=False),
warmup=500, repeats=150, devices=devices[:k]).time
print(f'{k} GPU(s), {b} examples each: {1e3 * t_local[k, b]:.2f} ms')1 GPU(s), 256 examples each: 2.91 ms
1 GPU(s), 128 examples each: 2.80 ms
2 GPU(s), 128 examples each: 5.60 ms
t_local = {}
for k, b in ((1, 256), (1, 128), (2, 128)):
mesh, data_k = meshes[k - 1], train_data[k - 1]
params = broadcast(base, mesh)
i = jax.device_put(idx[:k * b], NamedSharding(mesh, P('data')))
t_local[k, b] = d2l.Benchmark(lambda: train_step(
params, data_k, i, 0.2, mesh, communicate=False), repeats=500).time
print(f'{k} GPU(s), {b} examples each: {1e3 * t_local[k, b]:.2f} ms')1 GPU(s), 256 examples each: 0.37 ms
1 GPU(s), 128 examples each: 0.40 ms
2 GPU(s), 128 examples each: 0.76 ms
将单主机派发下界 \(k\,h_{\textrm{step}}\) 与设备计算时间 \(t_{\textrm{dev}}(B/k)\) 一并纳入考量,可以把 式 13.5.2 细化为
\[ t_{\textrm{step}}(k) \approx \max\bigl(k\,h_{\textrm{step}},\; t_{\textrm{dev}}(B/k)\bigr) + c\,\alpha + \frac{2(k-1)}{k}\,S\,\beta_{\textrm{link}}. \tag{13.5.3}\]
为了端到端检验这两种预测,我们编写训练循环 train,按 orders 中预先生成的样本排列运行每一轮,并返回平均单步时间(剔除第一轮)与验证准确率:
def train(params, train_data, test_data, orders, batch_size=256, lr=0.2):
"""Data-parallel SGD on the devices that hold `params` and `train_data`,
one epoch per example order; returns seconds per step, test accuracy."""
devices = [X.device for X, _ in train_data]
times = []
for order in orders:
t0 = time.perf_counter()
for idx in order.split(batch_size):
train_step(params, train_data, idx, lr)
for d in devices: # Wait until every device has finished
torch.cuda.synchronize(d)
times.append((time.perf_counter() - t0)
/ math.ceil(len(order) / batch_size))
X, y = test_data
with torch.no_grad():
acc = (lenet(params[0], X).argmax(1) == y).float().mean().item()
return sum(times[1:]) / (len(times) - 1), accdef train(params, train_data, test_data, mesh, orders, batch_size=256,
lr=0.2):
"""Data-parallel SGD on the devices of `mesh`, one epoch per example
order; returns seconds per step, test accuracy."""
times = []
for order in orders:
starts = range(0, len(order), batch_size)
batches = jax.device_put( # The epoch's minibatches, in one call
[order[s:s + batch_size] for s in starts],
NamedSharding(mesh, P('data')))
t0 = time.perf_counter()
for idx in batches:
params = train_step(params, train_data, idx, lr, mesh)
jax.block_until_ready(params)
times.append((time.perf_counter() - t0) / len(batches))
X, y = test_data
acc = float((jax.jit(lenet)(params, X).argmax(1) == y).mean())
return sum(times[1:]) / (len(times) - 1), acc现在我们在全局批量大小为 256 的设置下,于 \(k \in \{1, 2\}\) 块 GPU 上运行 train 共五轮,并将实测双 GPU 单步时间 t_step[2] 与朴素预测 式 13.5.2 及单派发器模型 式 13.5.3 进行对比:
orders, t_step = [torch.randperm(len(data.train)) for _ in range(5)], {}
for k in (1, 2):
params = [broadcast(base, d) for d in devices[:k]]
t_step[k], acc = train(params, train_data[:k], test_data, orders)
print(f'{k} GPU(s): {1e3 * t_step[k]:.2f} ms per step, '
f'test accuracy {acc:.2f}')
exchange = alpha + n_bytes * beta_link # One allreduce of the gradient
print(f'2 GPUs predicted: {1e3 * (t_local[1, 128] + exchange):.2f} ms per '
f'step by eq_dp_cost, {1e3 * (2 * t_step[1] + exchange):.2f} ms with '
f'one launcher')1 GPU(s): 2.88 ms per step, test accuracy 0.87
2 GPU(s): 5.69 ms per step, test accuracy 0.87
2 GPUs predicted: 2.88 ms per step by eq_dp_cost, 5.85 ms with one launcher
rng = np.random.default_rng()
orders, t_step = [rng.permutation(len(data.train[1])) for _ in range(5)], {}
for k, mesh, data_k in zip((1, 2), meshes, train_data):
t_step[k], acc = train(broadcast(base, mesh), data_k, test_data, mesh,
orders)
print(f'{k} GPU(s): {1e3 * t_step[k]:.2f} ms per step, '
f'test accuracy {acc:.2f}')
exchange = alpha + n_bytes * beta_link # One allreduce of the gradient
print(f'2 GPUs predicted: {1e3 * (t_local[1, 128] + exchange):.2f} ms per '
f'step by eq_dp_cost, {1e3 * (2 * t_step[1] + exchange):.2f} ms with '
f'one launcher')1 GPU(s): 0.37 ms per step, test accuracy 0.86
2 GPU(s): 0.89 ms per step, test accuracy 0.86
2 GPUs predicted: 0.52 ms per step by eq_dp_cost, 0.88 ms with one launcher
两次运行达到了相同的测试准确率,而且 式 13.5.3 准确预测了双 GPU 的变慢幅度:在批量为 256 时,LeNet 的梯度交换微乎其微(~0.1 ms),真正的瓶颈在于用单个主机派发器同时喂给两块 GPU。
13.5.4.4 强扩展、弱扩展与更大的小批量
多 GPU 基准测试遵循两种惯例之一:强扩展(strong scaling)在增大 \(k\) 时保持全局批量 \(B\) 不变(目标是更快完成同一步计算),而弱扩展(weak scaling)保持每块 GPU 的批量 \(b\) 不变,使全局批量按 \(kb\) 增长(目标是以样本/秒计实现 \(k\times\) 吞吐量,尽管更大的全局批量会改变优化动态,见 9.8 节)。强扩展对应阿姆达尔定律(Amdahl’s law)(Amdahl 1967年) 支配的区域:单步中无法并行的部分(此处为主机派发器与梯度交换)无论增加多少块 GPU 都会给加速比封顶。弱扩展对应古斯塔夫森定律(Gustafson’s law)(Gustafson 1988年) 支配的区域:当工作量随处理器数量同步增长时,串行部分占比相对缩小,吞吐量便能持续提升。
由 式 13.5.3 可知,当满足下式时,第二块 GPU 能提升弱扩展吞吐量(\(2\,t(1)/t(2) > 1\)):
\[ \max\bigl(2h_{\textrm{step}},\; t_{\textrm{dev}}(b)\bigr) + \alpha + S\,\beta_{\textrm{link}} \;<\; 2\max\bigl(h_{\textrm{step}},\; t_{\textrm{dev}}(b)\bigr). \]
当 \(t_{\textrm{dev}}(b) \le h_{\textrm{step}}\) 时,第二块 GPU 绝不会带来帮助;一旦 \(t_{\textrm{dev}}(b)\) 超过 \(2h_{\textrm{step}}\) 与交换时间,加速比就会趋近于 2。我们在每块 GPU 批量 \(b \in \{256, 4096, 32768\}\) 个样本上进行检验:
for b in (256, 4096, 32768): # Examples per GPU
batch = torch.randint(len(data.train), (2 * b,)) # With replacement
steps = [lambda k=k: train_step(params[:k], train_data[:k],
batch[:k * b], 0.2) for k in (1, 2)]
times = [[], []] # Three timed windows per k,
for w in range(3): # taken in turn for k = 1 and 2
for k in (1, 2):
params = [broadcast(base, d) for d in devices] # Equal replicas
times[k - 1].append(d2l.Benchmark(
steps[k - 1], warmup=10 if w == 0 else 0,
repeats=max(20, 2**18 // b), devices=devices[:k]).time)
t = np.median(times, axis=1)
t_dev = sum(d2l.kernel_times(steps[0]).values()) / 1e3
if b == 256: # The host sets this step's time (profile above)
h_step = t[0]
predicted = 2 * t[0] / (max(2 * h_step, t_dev) + exchange)
speedups = 2 * np.array(times[0]) / np.array(times[1])
print(f'b = {b:5d}: 1 GPU {1e3 * t[0]:6.2f} ms (device busy '
f'{1e3 * t_dev:5.2f} ms), 2 GPUs {1e3 * t[1]:6.2f} ms\n'
f' speedup {predicted:.2f} predicted, '
f'{2 * t[0] / t[1]:.2f} measured '
f'(windows {speedups.min():.2f} to {speedups.max():.2f})')b = 256: 1 GPU 2.83 ms (device busy 0.30 ms), 2 GPUs 5.83 ms
speedup 0.99 predicted, 0.97 measured (windows 0.92 to 0.98)
b = 4096: 1 GPU 3.01 ms (device busy 3.00 ms), 2 GPUs 6.11 ms
speedup 1.05 predicted, 0.99 measured (windows 0.98 to 0.99)
b = 32768: 1 GPU 25.26 ms (device busy 25.35 ms), 2 GPUs 25.53 ms
speedup 1.99 predicted, 1.98 measured (windows 1.98 to 1.98)
rng = np.random.default_rng()
for b in (256, 4096, 32768): # Examples per GPU
batch = rng.integers(len(data.train[1]), size=2 * b) # With replacement
steps = []
for k, mesh, data_k in zip((1, 2), meshes, train_data):
params = broadcast(base, mesh)
i = jax.device_put(batch[:k * b], NamedSharding(mesh, P('data')))
steps.append(partial(train_step, params, data_k, i, 0.2, mesh))
times = [[], []] # Three timed windows per k,
for w in range(3): # taken in turn for k = 1 and 2
for j, step in enumerate(steps):
times[j].append(d2l.Benchmark(
step, warmup=10 if w == 0 else 0,
repeats=max(20, 2**18 // b)).time)
t = np.median(times, axis=1)
t_dev = sum(d2l.kernel_times(steps[0]).values()) / 1e3
if b == 256: # The host sets this step's time (profile above)
h_step = t[0]
predicted = 2 * t[0] / (max(2 * h_step, t_dev) + exchange)
speedups = 2 * np.array(times[0]) / np.array(times[1])
print(f'b = {b:5d}: 1 GPU {1e3 * t[0]:6.2f} ms (device busy '
f'{1e3 * t_dev:5.2f} ms), 2 GPUs {1e3 * t[1]:6.2f} ms\n'
f' speedup {predicted:.2f} predicted, '
f'{2 * t[0] / t[1]:.2f} measured '
f'(windows {speedups.min():.2f} to {speedups.max():.2f})')b = 256: 1 GPU 0.41 ms (device busy 0.16 ms), 2 GPUs 0.97 ms
speedup 0.87 predicted, 0.84 measured (windows 0.83 to 0.87)
b = 4096: 1 GPU 1.75 ms (device busy 1.74 ms), 2 GPUs 1.99 ms
speedup 1.89 predicted, 1.76 measured (windows 1.72 to 1.80)
b = 32768: 1 GPU 14.29 ms (device busy 14.26 ms), 2 GPUs 14.50 ms
speedup 1.99 predicted, 1.97 measured (windows 1.96 to 1.97)
在 \(b = 256\) 时第二块 GPU 没有带来加速;在 \(b = 32{,}768\) 时,设备计算远超 \(2h_{\textrm{step}}\) 与 247 KB 梯度交换耗时,如预测般几乎将吞吐量翻倍。
13.5.5 小结
数据并行在 \(k\) 台设备上复制模型,每台设备在小批量的 \(1/k\) 上计算梯度,并在更新前通过全归约求和。环形全归约将求和分解为归约散播与全收集两个阶段,经过 \(2(k-1)\) 跳,每台设备发送 \(2(k-1)S/k < 2S\) 字节。我们的单步代价模型 式 13.5.3 结合了设备计算时间、单主机派发开销 \(k\,h_{\textrm{step}}\)、单次调用延迟 \(c\alpha\) 以及带宽代价 \(2(k-1)S\beta_{\textrm{link}}/k\),解释了为何拼接小梯度张量可省去 \(9\alpha\),以及为何只有当单卡设备计算超过主机派发与通信耗时,第二块 GPU 才能加速训练。
13.5.6 练习
- 数据并行与流水线并行对比。考虑由 \(L\) 个宽度为 \(d\) 的无偏置 fp32 线性层组成的堆叠,在两块 GPU 上以批量大小 \(B\) 训练。数据并行对所有权重梯度执行全归约;两阶段流水线并行(图 13.5.1)在每块 GPU 上放置 \(L/2\) 层,并跨切分边界前向发送 \(B \times d\) 激活值、反向发送梯度。
- 计算两种方案每步传输的字节数,在 \(L = 32, d = 4096, B = 256\) 时求值,并找出数据并行传输更少字节时 \((B, L, d)\) 需满足的条件。
- 当批量被切分为 \(m\) 个流水线微批量 (Huang 等 2019年) 时,推导两阶段流水线中每块 GPU 的气泡(空闲)比例,并计算 \(m = 1\) 与 \(m = 8\) 时的数值。
- 梯度归一化。比较在含 \(B\) 个样本的批量的 \(k\) 个分片上的两种数据并行梯度方案:方案 A 在每台设备上对单样本损失求和、跨设备对梯度求和后再除以 \(B\);方案 B 在每台设备上对单样本损失求平均,再对 \(k\) 台设备的梯度求平均。
- 证明当所有分片都恰好包含 \(B/k\) 个样本时,两种方案都给出精确的整批平均梯度。
- 对于按词元求平均损失的语言模型,假设两个分片分别包含 3,000 和 1,000 个词元。求出方案 B 赋予每个分片中单个词元的相对权重,并修改方案 B 使其在词元数不等时仍精确无误。
- 强扩展加速比。将分片计算时间建模为 \(t_{\textrm{compute}}(s) = t_0 + s\,t_1\) 并忽略 \(\alpha\),于是按 式 13.5.2,在固定全局批量 \(B\) 下有: \[t_{\textrm{step}}(k) = t_0 + \frac{B\,t_1}{k} + \frac{2(k-1)}{k}\,S\,\beta_{\textrm{link}}. \tag{13.5.4}\]
- 证明强扩展加速比 \(R(k) = t_{\textrm{step}}(1) / t_{\textrm{step}}(k) > 1\) 对某个 \(k > 1\) 成立,当且仅当它对所有 \(k > 1\) 均成立,并求 \(\lim_{k \to \infty} R(k)\)。
- 取 \(N = 11.2\)M 个 fp32 参数、\(t_0 = 2\) ms、\(t_1 = 0.2\) ms/样本及 \(B = 256\),计算总线带宽为 20 GB/s 与 5 GB/s 时的 \(R(2)\)、\(R(4)\) 和 \(\lim_{k \to \infty} R(k)\),并求产生任意加速所需的最小总线带宽。
- 当梯度改用 bf16 通信(\(S\) 减半)时,重新计算 5 GB/s 下的 \(R(4)\) 和 \(\lim_{k \to \infty} R(k)\)。
- [code] 手动实现环形全归约。●
- 对于 \(k\) 台各持 \(S\) 字节的设备,比较星形全归约与环形全归约的总移动字节数,以及最繁忙设备收发的字节数。预测全部 \(k\) 条双向链路并发工作与所有传输串行共享单条总线两种情形下的耗时比。
- 在 PyTorch 中使用
chunk和显式.to()复制实现ring_allreduce(data),在 \(k \in \{2, 3, 4\}\) 上与allreduce对照验证,并在 \(k = 2\) 和 \(k = 4\)、每设备 64M 浮点数下对两者进行基准测试。
- 全归约中的延迟。● 若传输 \(n\) 字节的一跳耗时为 \(\alpha_{\textrm{hop}} + n\,\beta_{\textrm{link}}\),则 \(2(k-1)\) 步环形全归约耗时为 \[t_{\textrm{ring}} = 2(k-1)\left(\alpha_{\textrm{hop}} + \frac{S}{k}\,\beta_{\textrm{link}}\right), \tag{13.5.5}\] 而二叉树全归约(以 \(2\log_2 k\) 步每步 \(S\) 字节向上求和再向下广播)耗时为 \[t_{\textrm{tree}} = 2\log_2 k \left(\alpha_{\textrm{hop}} + S\,\beta_{\textrm{link}}\right). \tag{13.5.6}\]
- 数据并行与流水线并行对比。考虑由 \(L\) 个宽度为 \(d\) 的无偏置 fp32 线性层组成的堆叠,在两块 GPU 上以批量大小 \(B\) 训练。数据并行对所有权重梯度执行全归约;两阶段流水线并行(图 13.5.1)在每块 GPU 上放置 \(L/2\) 层,并跨切分边界前向发送 \(B \times d\) 激活值、反向发送梯度。
- 计算两种方案每步传输的字节数,在 \(L = 32, d = 4096, B = 256\) 时求值,并找出数据并行传输更少字节时 \((B, L, d)\) 需满足的条件。
- 当批量被切分为 \(m\) 个流水线微批量 (Huang 等 2019年) 时,推导两阶段流水线中每块 GPU 的气泡(空闲)比例,并计算 \(m = 1\) 与 \(m = 8\) 时的数值。
- 梯度归一化。比较在含 \(B\) 个样本的批量的 \(k\) 个分片上的两种数据并行梯度方案:方案 A 在每台设备上对单样本损失求和、跨设备对梯度求和后再除以 \(B\);方案 B 在每台设备上对单样本损失求平均,再对 \(k\) 台设备的梯度求平均。
- 证明当所有分片都恰好包含 \(B/k\) 个样本时,两种方案都给出精确的整批平均梯度。
- 对于按词元求平均损失的语言模型,假设两个分片分别包含 3,000 和 1,000 个词元。求出方案 B 赋予每个分片中单个词元的相对权重,并修改方案 B 使其在词元数不等时仍精确无误。
- 强扩展加速比。将分片计算时间建模为 \(t_{\textrm{compute}}(s) = t_0 + s\,t_1\) 并忽略 \(\alpha\),于是按 式 13.5.2,在固定全局批量 \(B\) 下有: \[t_{\textrm{step}}(k) = t_0 + \frac{B\,t_1}{k} + \frac{2(k-1)}{k}\,S\,\beta_{\textrm{link}}.\]
- 证明强扩展加速比 \(R(k) = t_{\textrm{step}}(1) / t_{\textrm{step}}(k) > 1\) 对某个 \(k > 1\) 成立,当且仅当它对所有 \(k > 1\) 均成立,并求 \(\lim_{k \to \infty} R(k)\)。
- 取 \(N = 11.2\)M 个 fp32 参数、\(t_0 = 2\) ms、\(t_1 = 0.2\) ms/样本及 \(B = 256\),计算总线带宽为 20 GB/s 与 5 GB/s 时的 \(R(2)\)、\(R(4)\) 和 \(\lim_{k \to \infty} R(k)\),并求产生任意加速所需的最小总线带宽。
- 当梯度改用 bf16 通信(\(S\) 减半)时,重新计算 5 GB/s 下的 \(R(4)\) 和 \(\lim_{k \to \infty} R(k)\)。
- [code] 手动实现环形全归约。●
- 对于 \(k\) 台各持 \(S\) 字节的设备,比较星形全归约与环形全归约的总移动字节数,以及最繁忙设备收发的字节数。预测全部 \(k\) 条双向链路并发工作与所有传输串行共享单条总线两种情形下的耗时比。
- 在
jax.shard_map中使用jax.lax.ppermute和jax.lax.axis_index实现ring_allreduce,在 \(k \in \{2, 4\}\) 上与jax.lax.psum对照验证,并在每设备 64M 浮点数下进行基准测试。
- 全归约中的延迟。● 若传输 \(n\) 字节的一跳耗时为 \(\alpha_{\textrm{hop}} + n\,\beta_{\textrm{link}}\),则 \(2(k-1)\) 步环形全归约耗时为 \[t_{\textrm{ring}} = 2(k-1)\left(\alpha_{\textrm{hop}} + \frac{S}{k}\,\beta_{\textrm{link}}\right),\] 而二叉树全归约(以 \(2\log_2 k\) 步每步 \(S\) 字节向上求和再向下广播)耗时为 \[t_{\textrm{tree}} = 2\log_2 k \left(\alpha_{\textrm{hop}} + S\,\beta_{\textrm{link}}\right).\]