页面简介
正文摘录
The multi-GPU sections of Chapter 13 trained a ResNet and a GPT on the four GPUs of one machine by giving every GPU a copy of the model, and worked out how splitting the training state among the GPUs makes room for a model that no single GPU holds. Models that people fine-tune for real work are often larger still. A language model with 7 billion parameters, trained with Adam, needs about 112 GB for its weights, gradients, and optimizer state before it stores a single activation. That is more than the 80 GB of an H100, and training such a model from scratch on one GPU would take years. How do we spread the state and the work of one training run over many accelerators, possibly in many machines, so that it computes the same result in less time? Every answer partitions something: the batch, the training state, the layers, or the sequence. Each partition adds communication, and every added worker is one more place where the run can fail. We therefore start from a measured single-device baseline and add the simplest technique that removes an observed memory or throughput limit. We order the techniques by the limit each removes, map them to the libraries that implement them as of November 2026, and end with the practices that keep a run of several weeks alive. 27.6.1 Forms of Parallelism 27.6.1.1 The Scaling Ladder Each technique below removes a limit of the one before it and adds communication, so we adopt them in order, the rungs of a scaling ladder (Figure 27.6.1). Figure 27.6.1: A practical scaling ladder progresses from one accelerator to replication, sharding, and composed parallelism. One accelerator establishes the reference: loss curve, tokens or examples per second, peak memory, and a checkpoint you can trust. Data parallelism (DDP) replicates the model on every GPU, feeds each a different slice of the batch, and averages gradients after every backward pass. It is the right choice whenever model, gradients, and optimizer state fit on one device. Fully sharded data parallelism (FSDP), stage 3 of the ZeRO family, shards parameters, gradients, and optimizer state across GPUs and gathers each layer only while it is being used (Section 13.7.1). It divides the per-device state memory by the number of GPUs and communicates about 1.5 times as much as DDP. Tensor, pipeline, context, and expert parallelism split individual layers, groups of consecutive layers, the sequence dimension, and the experts of a mixture of experts (Section 11.7), respectively. Large systems compose several of these, because no single axis scales far enough on its own. In PyTorch, DDP and FSDP need a launcher and a wrapper: torchrun --standalone --nproc-per-node=4 train.py Inside train.py, DistributedDataParallel(model) applies DDP and fully_shard(model) from torch.distributed.fsdp applies FSDP. This API, known as FSDP2, stores each sharded parameter as a DTensor, and PyTorch recommends it over the older FullyShardedDataParallel wrapper. In JAX, arrays carry a NamedSharding over a mesh of devices, and jax.jit compiles the collectives that these placements imply (Section 13.6). Tensor parallelism exchanges activations inside every layer, while pipeline parallelism sends activations only at stage boundaries. In the Hugging Face Ultra-Scale Playbook, based on more than 4,000 runs on up to 512 GPUs, stretching tensor parallelism from one 8-GPU node to two typically cost about 43% of throughput, while stretching pipeline parallelism the same way cost 14% when each step had few microbatches. Keep tensor parallelism inside a node, where NVLink carries its traffic, and map the highest-volume collectives to the fastest links. One identity holds on every rung. The batch size that the optimizer sees is \[ B_{\textrm{global}} = B_{\textrm{device}} \cdot N_{\textrm{ranks}} \cdot N_{\textrm{accumulation}}, \tag{27.6.1}\] the per-device batch times the number of data-parallel ranks times the number of microbatches accumulated per optimizer step. Changing the number of GPUs without adjusting the per-device batch size or the learning rate therefore changes the optimization problem. Two further rules concern the data: distributed samplers must not duplicate examples, and evaluation must aggregate metrics with the right denominators. Violating either is the usual reason a multi-GPU run reports a different accuracy. 27.6.1.2 Training Memory Most jobs outgrow one GPU because the training state does not fit, so the first calculation is a memory budget (Figure 27.6.2). Figure 27.6.2: Sharding, checkpointing, accumulation, and offload reduce different memory terms and introduce different costs. Peak training memory is the sum of parameters, gradients, optimizer state, activations, communication buffers, and allocator overhead. For a model with 7 billion parameters trained in BF16 with Adam, the parameters and gradients take 14 GB each and Adam’s two FP32 moments take 56 GB. The FP32 master copy of the parameters that mixed-precision training keeps adds 28 GB, for a total of 112 GB, or 16 bytes per parameter. The toy model below omits that 28 GB master copy (leaving \(14 + 14 + 56 = 84\text{ GiB}\) of model state when reusing the GB figures as GiB) and adds 18 GiB of activations and 5 GiB of temporary buffers (\(107\text{ GiB}\) in total). It is crude, but it ranks the strategies correctly, and it needs no GPU to run: terms_gib = {"parameters": 14.0, "gradients": 14.0, "optimizer": 56.0, "activations": 18.0, "temporary": 5.0} def per_device_gib(world_size=1, shard_state=False, ckpt_activations=False): divisor = world_size if shard_state else 1 state = sum(terms_gib[k] / divisor for k in ("parameters", "gradients", "optimizer")) activations = terms_gib["activations"] * (0.35 if ckpt_activations else 1) return state + activations + terms_gib["temporary"] for label, cfg in [("1 GPU, plain", (1, False, False)), ("8 GPU DDP + ckpt", (8, False, True)), ("8 GPU FSDP + ckpt", (8, True, True))]: print(f"{label:>20s}: {per_device_gib(*cfg):6.1f} GiB/device") 1 GPU, plain: 107.0 GiB/device 8 GPU DDP + ckpt: 95.3 GiB/device 8 GPU FSDP + ckpt: 21.8 GiB/device Plain training needs 107 GiB, more than an 80 GB H100 holds. DDP with activation checkpointing still needs 95 GiB on every GPU: it replicates the 84 GiB of state, and only the activations shrink. FSDP with checkpointing on eight GPUs divides the state by eight and needs 22 GiB per device. Each standard memory technique changes a different term of the sum at a different cost. Mixed precision reduces the bytes used by selected tensors and operations. Gradient accumulation runs a smaller microbatch per step while keeping the global batch of Equation 27.6.1, which reduces activation memory but not model state. Activation checkpointing recomputes selected activations during backpropagation; its memory savings and compute overhead depend on which activations it keeps. CPU or NVMe offload, such as DeepSpeed’s ZeRO-Offload, moves state out of device memory and adds host-device transfers to every step. LoRA and QLoRA train small low-rank adapters instead of all weights, which removes most gradients and optimizer state; QLoRA also stores the frozen weights in 4 bits, so a 7B model can be fine-tuned on one 16 GB card. Combine techniques deliberately: individually sensible optimizations can interfere with compilation, overlap, or numerics. 27.6.2 Software Libraries Beyond one node, few people write these techniques by hand. Libraries implement them, and the choice among them follows mostly from the scale of the job. The projects below were maintained and widely used as of November 2026; this layer changes quickly, so check a project’s recent releases before adopting it. PyTorch built-ins. Besides DDP and FSDP2, PyTorch has tensor- and context-parallel APIs built on DTensor and a pipeline-parallel API, torch.distributed.pipelining. Its documentation still marks them as experimental or alpha. Most higher-level tools below generate calls to these primitives. Hugging Face stack. accelerate launches the same script on DDP, FSDP2, or DeepSpeed, selected by a configuration file rather than by code changes; transformers.Trainer sits on top of it; peft implements LoRA and QLoRA; and trl provides trainers for supervised fine-tuning, DPO, and GRPO-style reinforcement learning. This stack covers most fine-tuning jobs on one node or a small cluster. DeepSpeed. ZeRO stages 1–3 (sharding the optimizer state, then the gradients, then the parameters) plus CPU and NVMe offload. ZeRO introduced the sharding that FSDP2 now provides natively, and FSDP2 can also offload state to CPU memory. DeepSpeed remains the usual choice when a job offloads to NVMe or when another framework builds on it. Megatron Core and TorchTitan. Libraries for large-scale pretraining. NVIDIA’s Megatron Core implements tensor, pipeline, context, and expert parallelism with FP8 and FP4 training; Megatron-LM is its reference training stack. TorchTitan is the PyTorch-native counterpart: a compact reference stack that composes FSDP2 with tensor, pipeline, context, and expert parallelism, with model definitions that include Llama 3 405B and DeepSeek-V3 and published measurements on up to 512 GPUs. Both suit models that need several forms of parallelism at once. Fine-tuning front ends. Unsloth began with fast single-GPU LoRA and QLoRA through fused kernels and now also covers full fine-tuning, GRPO, and multiple GPUs; its gains depend on model, sequence length, and hardware. Axolotl drives full and parameter-efficient fine-tunes on one or several nodes from one YAML file, with FSDP2 and DeepSpeed backends. LLaMA-Factory covers a similar range with a web interface. The PyTorch team’s torchtune stopped active development in 2025. JAX. MaxText is the reference stack for pretraining and post-training on TPUs and GPUs. Marin, which trains with Levanter, records its training runs from raw data to the final model, failed experiments included, and publishes the code, data pipelines, and logs so t