Data Parallelism in Practice

Dive into Deep Learning · §13.6

Distributed Data Parallel (DDP) in Practice: Bucketing and Overlap
multi-process vs. compiler SPMD · gradient bucketing · backward overlap · BatchNorm semantics · scaling & SM contention

From Toy LeNet to Compute-Heavy ResNet-18

Motivation

  • Why LeNet stalled in §13.5: One Python thread dispatched sequentially to both GPUs (k \cdot h_{\textrm{step}}), and the allreduce waited until backward() finished.
  • Production DDP remedies: Spawns 1 process per GPU (torchrun), launching bucketed allreduces during backward().
  • ResNet-18 benchmark (64 \times 64, b=256): Keeps each RTX 4090 busy for \sim 100\text{ ms/step} across 11.2\text{M} params (S = 45\text{ MB}), exposing true communication overlap.

Multi-Process SPMD: One Python Process per GPU

Execution Models

  • Multi-Process SPMD (torchrun + DDP): Spawns k independent Python processes (1 per GPU); autograd hooks fire asynchronous NCCL bucket allreduces during backward().

How Production DDP Fixes the Hand-Written Loop

PyTorch DDP

  • Parallel host dispatch (1 \cdot h_{\textrm{step}}): Each of the k torchrun ranks drives its own GPU concurrently, eliminating the k \cdot h_{\textrm{step}} single-thread bottleneck.
  • Ring/Tree NCCL collectives: Replaces the O(kS) hub-bottlenecked star gather/scatter with bandwidth-optimal \frac{2(k-1)}{k}S NCCL collectives.
  • Pipelined backward hooks: Fires asynchronous allreduces on 25\text{ MiB} reverse-order buckets while earlier layers are still backpropagating.

One Process per GPU with torchrun and DDP

Multi-Process Workflow

torchrun --standalone --nproc-per-node=k spawns k processes; each binds to its assigned GPU via LOCAL_RANK and wraps the model in DDP:

rank, k, device = d2l.init_distributed()   # join the NCCL process group
model = d2l.resnet18(10).to(device)
model = DDP(model, device_ids=[device])    # broadcasts weights from rank 0
for s in range(len(y) // (k * b)):         # rank r takes slice (s*k + r)*b
    i = perm[(s * k + rank) * b:][:b]      # disjoint shard of global batch k*b
    F.cross_entropy(model(X[i]), y[i]).backward()  # hooks launch bucket allreduces
    opt.step(); opt.zero_grad(set_to_none=True)

DDP broadcasts initial parameters and buffers from rank 0 at construction time and registers autograd hooks on every parameter to fire bucketed NCCL allreduces during backward().

Overlapping Bucketed Allreduces with Backpropagation

Communication Overlap

  • Reverse-order gradient production: Backpropagation computes gradients from the final output layer back toward the first input layer.
  • Pipelining communication and compute: Packing gradients into buckets of 25\text{--}30\text{ MiB} in reverse parameter order lets each bucket’s allreduce run on a separate communication stream while earlier layers are still backpropagating.

The Bucket Size Trade-Off and the Ideal Bucket Model

Bucket Model

t_{\textrm{exposed (ideal)}} \;=\; \frac{2(k-1)}{k}\, S_{\textrm{last\_bucket}}\, \beta_{\textrm{link}}

  • Tiny buckets (c \gg 1) vs. 1 giant bucket (c = 1): Tiny buckets pay latency c\alpha dozens of times; one giant bucket waits until the entire backward pass finishes.
  • 25–30 MiB sweet spot: Under ideal overlap (fast links, zero SM contention), every bucket except the final bucket S_{\textrm{last}} is hidden behind backpropagation.

Reverse-Order Bucketing in PyTorch DDP (1 & 25 MiB)

DDP Buckets

PyTorch DDP closes the first bucket at 1\text{ MiB} (so communication starts almost immediately) and subsequent buckets at bucket_cap_mb = 25 (25\text{ MiB} = 26.2\text{ MB}):

  • ResNet-18 bucket layout (S = 44.7\text{ MB} total): Walking reversed(list(net.parameters())) forms three buckets of 9.4\text{ MB}, 26.2\text{ MB}, and 9.0\text{ MB} (a single 9.4\text{ MB} late-stage Conv2d weight tensor overshoots the 1\text{ MiB} first cap on its own).
  • Ideal overlap prediction: If the first two buckets (9.4 and 26.2\text{ MB}) finish behind backpropagation, only the final S_{\textrm{last}} = 9.0\text{ MB} bucket (holding the earliest layers, computed last) remains exposed, cutting exposed communication by 5\times.

One-Step Check: Per-Shard BatchNorm in PyTorch DDP

BatchNorm Semantics

Unlike LeNet, ResNet-18 contains BatchNorm2d layers. Comparing one 2-GPU DDP step on 256 images against (a) one GPU on all 256 images and (b) one GPU accumulating two 128-image halves reveals what BatchNorm2d computes:

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
  • Local per-shard statistics by default: PyTorch DDP normalizes each GPU’s 128-image shard using its own local mean and variance, matching the two accumulated halves to 10^{-7} while differing from global 256-image BatchNorm by \sim 6\% of the update.

Local BatchNorm vs. SyncBatchNorm Trade-Offs

Synchronizing Statistics

When does per-shard BatchNorm matter, and what does synchronizing it cost?

  • When local BatchNorm works well: When the per-GPU shard size b = B/k is large (b \ge 32\text{--}64 images/GPU), per-shard means and variances are low-variance estimates and avoid any forward-pass communication barrier.
  • When nn.SyncBatchNorm is needed: In object detection or segmentation with tiny per-GPU batches (b = 1\text{--}4 high-resolution images/GPU), local statistics are too noisy; nn.SyncBatchNorm.convert_sync_batchnorm(model) inserts an allreduce at every BatchNorm layer during the forward and backward passes (adding dozens of latency-bound \alpha synchronization points).

Silent Data-Sharding Bugs in Distributed Training

Practical Pitfalls

  • Bug 1 (identical shards across ranks): Omitting rank in the slice offset (or sharding indices with P()) makes all k GPUs compute on the exact same b examples, wasting k-1 GPUs.
  • Bug 2 (unseeded per-rank shuffles): Independent random permutations sample examples with replacement across ranks instead of partitioning the epoch.
  • Step-1 defense: Assert that minibatch checksums differ across ranks while sharing the epoch seed.

Bounding Exposed Communication: No Overlap vs. Bucket

Paper Predictions

First, we measure \beta_{\textrm{link}} on a bare 256\text{ MB} NCCL allreduce (\sim 2.4\text{ GB/s} bus bandwidth, or \beta_{\textrm{link}} \approx 0.42\text{ ns/B}) and compute our two theoretical bounds on exposed communication t_{\textrm{step}}(k) - t_{\textrm{step}}(1) under weak scaling:

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)
  • Two clear predictions: Without overlap, exposed communication should be \sim 18\text{ ms} (k=2) and \sim 28\text{ ms} (k=4); with ideal bucket overlap, only the last bucket/buffer should be exposed (4\text{--}8\text{ ms} at k=2, 5\text{--}12\text{ ms} at k=4).

Weak Scaling on Four GPUs: 3.1–3.3× Throughput

Weak Scaling Measured

Fixing the per-GPU batch size at b = 256 images/GPU across k \in \{1, 2, 4\} GPUs measures weak-scaling throughput and exposed communication t_{\textrm{step}}(k) - t_{\textrm{step}}(1):

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

Four GPUs achieve 3.1\text{--}3.3\times single-GPU throughput (77\text{--}83\% scaling efficiency), and the measured exposed communication matches the no-overlap prediction (\sim 18\text{ ms} at k=2, \sim 28\text{ ms} at k=4) rather than the ideal bucket model.

Strong Scaling on Four GPUs: Shrinking Compute Share

Strong Scaling Measured

Strong scaling at a fixed global batch B = 512 (b = 512/k per GPU), k \in \{1, 2, 4\}:

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%
  • Why strong scaling drops off faster at k = 4: At k = 4, each GPU processes only 128 images (halving local backward compute time relative to b = 256), while the 45\text{ MB} gradient allreduce volume \frac{2(k-1)}{k}S = 1.5\,S stays full-sized.

Why Did Overlap Hide So Little? Profiling GPU 0

Testing Bucket Assumptions

To discover why exposed communication matched the no-overlap formula even though buckets launched during backward(), we profile GPU 0 across three runs: (1) 1 GPU, (2) 2 GPUs without communication (no_sync / shard_map), and (3) 2 GPUs with full communication:

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

Assumption 3 of the bucket model failed: While NCCL’s communication kernels overlap in time with backpropagation, the backward compute kernels running alongside NCCL slow down by 8\text{--}13\text{ ms}, clawing back most of the time saved by overlap.

SM Contention From Host-Staged NCCL Copy Kernels

Transport Bottleneck

Why does running an NCCL allreduce slow down concurrent convolution kernels on our workstation?

  • How NCCL moves data without peer-to-peer (P2P): Because our consumer RTX 4090s lack NVLink and PCIe P2P, NCCL stages every chunk through shared host DRAM (SHM) by running dedicated GPU SM kernels that read/write over PCIe and sum chunks on the SMs.
  • Resource contention: Those NCCL SM kernels compete directly with backward convolution and GEMM kernels for Streaming Multiprocessors and DRAM memory bandwidth.
bus bandwidth 2.44 GB/s by default, 11.53 GB/s with the copy engines (4.7x)

Offloading host-staged copies to DMA copy engines (NCCL_SHM_USE_CUDA_MEMCPY=1) boosts bare allreduce bandwidth 4\text{--}5\times, but deadlocks PyTorch DDP when overlapped with backward compute; always verify transport flags on the actual training loop.

Concept Check: Bucketing, BatchNorm, and Scaling

Check Your Understanding

Test your grasp of production data parallelism with three diagnostic questions:

  1. In what parameter order does DDP pack gradients into buckets, and why would packing them in forward layer order (1, 2, \ldots, L) defeat communication overlap?
  2. On our four RTX 4090s, weak scaling at b = 256 images/GPU gave E(4) = t_1 / t_{\textrm{step}}(4) \approx 80\% efficiency (t_1 \approx 100\text{ ms} compute + 28\text{ ms} exposed allreduce). If we accumulate gradients over a = 5 micro-batches of 256 images per GPU before running the allreduce (model.no_sync() on the first 4 micro-batches), what does the weak-scaling efficiency E(4) become?
  3. When you run a one-step check comparing 2-GPU training against 1-GPU training on a network with BatchNorm, which single-GPU reference does default DDP match?

Answers:

  1. Reverse parameter order (L, L-1, \ldots, 1): Because backward() produces gradients from layer L back to layer 1. A forward-ordered bucket containing layer 1 could not launch until the very end of backward().
  2. \mathbf{E(4) \approx 95\%}: Local compute grows 5\times to 5 \times 100 = 500\text{ ms} while the single allreduce stays at 28\text{ ms}, giving E(4) = \frac{500}{500 + 28} \approx 94.7\% (at the cost of a 5\times larger global batch B = 5 \times 4 \times 256 = 5{,}120).
  3. DDP uses per-shard statistics by default (matching 1 GPU accumulating two B/2 halves).

Summary: Production Data Parallelism and Overlap

Key Takeaways

  • SPMD Execution: torchrun + DDP (k processes) eliminates the single-thread k \cdot h_{\textrm{step}} bottleneck.
  • Reverse-Order Bucketing: Packing gradients into 25\text{--}30\text{ MiB} reverse-order buckets pipelines NCCL allreduces with backpropagation.
  • Verification & Contention: Always run a 1-step check (catching BatchNorm and sharding bugs) and profile SM contention on host-staged PCIe links.