页面简介
正文摘录
In Section 13.5, our hand-written data-parallel loop slowed LeNet down on two GPUs for two reasons: a single Python thread dispatched kernels to both GPUs sequentially, and the allreduce waited until the entire backward pass had finished even though the last layers’ gradients were ready much earlier. Production data-parallel tools eliminate both bottlenecks: they either run one host process per GPU or compile a single sharded program across all GPUs, and they group gradients into buckets whose allreduces start as soon as each bucket fills during the backward pass. To test how much of the gradient exchange can be hidden behind backward compute, we move from LeNet to ResNet-18 on \(64 \times 64\) Fashion-MNIST images (2.2G multiply-adds per image, ~300 training FLOPs per byte of its 45 MB gradient, keeping one RTX 4090 busy for ~100 ms per 256-image step). We verify what the parallel step computes via a one-step check and measure weak and strong scaling across one, two, and four GPUs against our cost model. 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 Production Data Parallelism 13.6.1.1 The Execution Model Every modern framework drives \(k\) GPUs using one of two single program, multiple data (SPMD) designs: Multi-process (\(k\) copies + collective library): A launcher starts \(k\) independent Python processes—one per GPU, each with its own rank in \(\{0, \ldots, k-1\}\) and its own CPU thread—that synchronize gradients through NCCL. Any Python code can run inside each process. Compiler-partitioned single program: The user writes a single-device step and annotates the sharding of its inputs on a device mesh; the compiler partitions the computation and inserts and schedules the collective operations automatically (Xu et al. 2021). PyTorchJAX PyTorch uses the multi-process design: torchrun launches \(k\) processes and DistributedDataParallel (DDP) wraps the model. Because a notebook is a single process, our helper torchrun writes a self-contained script to a temporary file, runs torchrun --standalone --nproc-per-node=k, and parses the JSON output of each rank. JAX uses the compiler-partitioned design: nnx.jit compiles a single-device training step, and placing replicated parameters (P()) alongside a batch-sharded input (P('data')) causes the Shardy/GSPMD partitioner to insert the gradient allreduce automatically. 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 Overlapping Communication with the Backward Pass Production frameworks pack gradients into buckets of a few tens of megabytes in reverse layer order (the order in which backpropagation produces them) and launch each bucket’s asynchronous allreduce as soon as its last gradient is ready (Li et al. 2020) (Figure 13.6.1). Figure 13.6.1: Top: the allreduce waits for the whole backward pass. Bottom: the gradients are grouped into buckets, and each bucket’s allreduce starts as soon as the backward pass has produced it. Only the last bucket runs after the backward pass has ended, and the earlier ones are hidden only if each allreduce finishes while the backward pass is still running. Bucket size trades off per-call latency \(\alpha\) against overlap: tiny buckets pay \(\alpha\) many times, while a single giant bucket cannot start until the backward pass finishes. Under the ideal bucket model of overlap—assuming inter-GPU links are fast enough to finish each bucket before the next fills and that communication does not slow down concurrent backward kernels—every bucket except the last is hidden behind the backward pass. PyTorchJAX DDP closes the first bucket at 1 MiB and subsequent buckets at 25 MiB (bucket_cap_mb). For ResNet-18’s 45 MB of gradients, DDP forms three buckets of ~9, 26, and 9 MB (the final 9 MB bucket holds the early layers, computed last). XLA combines gradient allreduces up to a 30 MiB threshold (--xla_gpu_all_reduce_combine_threshold_bytes), packing ResNet-18’s 45 MB of gradients into two asynchronous all-reduce-start / all-reduce-done pairs scheduled concurrently with backward compute. 13.6.1.3 The Training Step We define the small-image ResNet-18 of Section 7.4 (#@saved for Chapter 20) and count its gradient bytes \(S\) (45 MB in fp32): 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)) Next, we load Fashion-MNIST and compute ResNet-18’s parameter count num_params and fp32 gradient volume S: PyTorch We also compute the reverse-order 1 MiB and 25 MiB gradient buckets that DDP packs before launching allreduces. 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 We now define the data-parallel training step on \(64 \times 64\) Fashion-MNIST images: PyTorchJAX TRAIN_DDP wraps resnet18 in DDP and times train