页面简介
正文摘录
在 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 # 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') PyTorchJAX import json import os import random import sys import json import re import subprocess import sys from jax.sharding import NamedSharding, PartitionSpec as P 13.6.1 生产级数据并行 13.6.1.1 执行模型 所有现代框架都采用两种单程序多数据(SPMD)设计之一来驱动 \(k\) 块 GPU: 多进程(\(k\) 份副本 + 集合通信库):启动器开启 \(k\) 个独立的 Python 进程——每块 GPU 一个,各自拥有 \(\{0, \ldots, k-1\}\) 中的进程编号(rank)以及独立的 CPU 线程——并通过 NCCL 同步梯度。每个进程内部可以运行任意 Python 代码。 编译器自动切分的单程序:用户编写单设备单步代码,并在设备网格上标注输入的分片方式;编译器自动切分计算并插入、调度集合通信操作 (Xu 等 2021年)。 PyTorchJAX PyTorch 采用多进程设计:torchrun 启动 \(k\) 个进程,由 DistributedDataParallel(DDP)包装模型。由于笔记本本身是单进程,我们的辅助函数 torchrun 会把自包含脚本写入临时文件,运行 torchrun --standalone --nproc-per-node=k,再解析每个 rank 的 JSON 输出。 JAX 采用编译器切分设计:nnx.jit 编译单设备训练步,将复制的参数(P())与按批量分片的输入(P('data'))放在一起时,Shardy/GSPMD 切分器会自动插入梯度全归约。 PyTorch 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)。 图 13.6.1: 上:全归约等待整个反向传播结束。下:梯度被分组成桶,反向传播一生成某个桶,它的全归约就立即启动。只有最后一个桶在反向传播结束后运行,而前面的桶也只有在每次全归约于反向传播仍在运行时完成才能被隐藏。 桶大小在单次调用延迟 \(\alpha\) 与重叠程度之间权衡:桶太小会多次支付 \(\alpha\),而单个巨型桶则要等到反向传播完全结束才能启动。在理想的桶模型重叠假设下——假设 GPU 间链路足够快,能在下一个桶填满前完成当前桶,且通信不会拖慢并发的反向内核——除最后一个桶之外,所有桶都被隐藏在反向传播背后。 PyTorchJAX 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(为 第 20 章 (英文版) 使用 #@save 保存),并统计其梯度字节数 \(S\)(fp32 下为 45 MB): PyTorchJAX 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: PyTorch 我们还计算 DDP 在发起全归约之前按逆序打包出的 1 MiB 与 25 MiB 梯度桶 buckets。 PyTorchJAX 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 图像上的数据并行训练步: PyTorchJAX TRAIN_DDP 用 DDP 包装 resnet18,并在各进程间给 train_step 计时(支持可选的 model.no_sync() 与内核剖析)。 setup 在 'data' 网格上复制模型和数据集,train_step 在分片的小批量索引 idx 上运行经 JIT 编译的 SGD 更新。 PyTorch 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() ''' JAX 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 miniba