Skip to main content
© 2026 ePowerAI. All rights reserved.
CoursesContact
eAI
CoursesContact
Week 10: Large-Batch and Distributed Training
Adv. Optimization
01Week 1: Optimality Conditions Revisited
02Week 2: Lagrangian Duality in Depth
03Week 3: KKT and Sensitivity
04Week 4: LP, QP, and Conic Form
05Week 5: Semidefinite Programming
06Week 6: Interior-Point Methods
07Week 7: Proximal Methods and ADMM
08Week 8: Newton and Quasi-Newton
09Week 9: Variance Reduction
10Week 10: Large-Batch and Distributed Training
11Week 11: Automatic Differentiation
12Week 12: Sharpness and SAM
13Week 13: Landscapes and Implicit Bias
14Week 14: Capstone — Structure Meets Scale
Week 10· Adv. Optimization· Second-order & scale20 min read

Week 10: Large-Batch and Distributed Training

✦Learning Outcomes
  • Describe data-parallel SGDStochastic Gradient Descent: each worker computes local gradients, then all-reduce averages them
  • Explain the communication vs compute trade-off
  • State the linear learning rate scaling rule and its limitations
  • List stability failure modes of large-batch training
◆Prerequisites

Background: Week 9 (finite-sum structure, gradient variance). Intermediate Optim Weeks 6–7 (SGD, minibatching, momentum). Familiarity with the idea that minibatch gradient variance scales as O(1/B)O(1/B)O(1/B).

Later weeks: Large-batch sharpness behaviour connects directly to SAMSharpness-Aware Minimization (Week 12). The data-parallel pattern is the "scale path" entry in the Week 14 capstone.

Minibatch as Parallelism#

A minibatch of size BBB provides a gradient estimator:

g^B=1B∑i∈B∇fi(x)\hat{g}_B = \frac{1}{B}\sum_{i \in \mathcal{B}} \nabla f_i(x)g^​B​=B1​∑i∈B​∇fi​(x)

where B\mathcal{B}B is a random subset of {1,…,n}\{1, \ldots, n\}{1,…,n} of size BBB. The variance of this estimator is:

Var⁡(g^B)=1B⋅n−Bn−1⋅σ2≈σ2B\operatorname{Var}(\hat{g}_B) = \frac{1}{B} \cdot \frac{n - B}{n - 1} \cdot \sigma^2 \approx \frac{\sigma^2}{B}Var(g^​B​)=B1​⋅n−1n−B​⋅σ2≈Bσ2​

for B≪nB \ll nB≪n, where σ2\sigma^2σ2 is the per-example gradient variance. The variance falls as 1/B1/B1/B, but the computational cost rises as BBB — a classic trade-off.

In a data-parallel setup with KKK workers, each worker processes a local minibatch of size BlocalB_{\text{local}}Blocal​ and computes a local gradient. The global batch size is B=K⋅BlocalB = K \cdot B_{\text{local}}B=K⋅Blocal​, and the gradient is the average of the KKK local gradients. Workers operate independently on disjoint data shards — no model-level synchronisation during the forward/backward passes.

Data Parallel Loop#

Each iteration of data-parallel SGD:

  1. Broadcast: The current model parameters xxx are sent from the parameter server (or replicated via all-gather) to all KKK workers.
  2. Local forward/backward: Each worker kkk samples a minibatch of size BlocalB_{\text{local}}Blocal​, computes the local gradient g^k=1Blocal∑i∈Bk∇fi(x)\hat{g}_k = \frac{1}{B_{\text{local}}}\sum_{i \in \mathcal{B}_k} \nabla f_i(x)g^​k​=Blocal​1​∑i∈Bk​​∇fi​(x).
  3. All-reduce: Workers collectively sum (or average) their gradients. The all-reduce primitive computes ∑k=1Kg^k\sum_{k=1}^K \hat{g}_k∑k=1K​g^​k​ and makes it available to every worker.
  4. Update: Each worker computes the global gradient g^=1K∑kg^k\hat{g} = \frac{1}{K}\sum_k \hat{g}_kg^​=K1​∑k​g^​k​ and applies the optimiser step x←x−ηg^x \leftarrow x - \eta \hat{g}x←x−ηg^​ (or communicates the averaged gradient to a parameter server).

The all-reduce operation (e.g., ring all-reduce) is the communication bottleneck. For a gradient vector of size ddd (number of parameters), the communication time per iteration is roughly 2(K−1)d/K2(K-1)d/K2(K−1)d/K worth of data transfer per worker in a bandwidth-optimal ring reduce. With K=8K = 8K=8 workers and d=107d = 10^7d=107 (40 MB per gradient), this is about 80 MB per worker per step — a few milliseconds on high-bandwidth interconnects (NVLink, InfiniBand), tens of milliseconds on Ethernet.

Learning Rate Scaling Folklore#

Linear scaling rule: If you multiply the batch size by rrr (by adding workers), multiply the learning rate by rrr to maintain the same expected parameter update per step:

ηnew=r⋅ηold\eta_{\text{new}} = r \cdot \eta_{\text{old}}ηnew​=r⋅ηold​

Why it sometimes works. The expected gradient is the same regardless of BBB: E[g^B]=∇f(x)\mathbb{E}[\hat{g}_B] = \nabla f(x)E[g^​B​]=∇f(x). The total displacement after one step with batch BBB and learning rate η\etaη is −ηg^B-\eta \hat{g}_B−ηg^​B​. If you use B′=rBB' = rBB′=rB and η′=rη\eta' = r\etaη′=rη, the expected displacement per step scales as rrr, but the variance scales as (rη)2⋅(σ2/rB)=rη2σ2/B(r\eta)^2 \cdot (\sigma^2/rB) = r \eta^2 \sigma^2 / B(rη)2⋅(σ2/rB)=rη2σ2/B — variance grows linearly with rrr.

When it breaks:

  • Large rrr causes instability: The variance increase can cause the iterates to diverge early in training before the gradient shrinks.
  • The noise is beneficial: SGDStochastic Gradient Descent noise helps escape sharp minima (Week 12). Reducing noise by increasing batch size can lead to worse generalisation.
  • Warmup is essential: Starting with the full scaled learning rate can cause immediate divergence. A linear warmup (gradually increasing η\etaη from a small value) is standard practice.

The linear scaling rule is a heuristic, not a theorem. It is a starting point; hyperparameter tuning (warmup duration, momentum correction, gradient clipping) is nearly always needed.

Generalization Gap Stories#

A consistent empirical finding: large-batch training often produces models with worse test accuracy than small-batch training, even when the training loss is matched. This "generalisation gap" has several proposed explanations:

  1. Sharp minima hypothesis: Large batches produce lower-variance gradients, which converge to sharper minima — points where the loss increases rapidly in some directions. Small-batch SGD noise helps escape these sharp regions and land in flatter minima that generalise better (Week 12).

  2. Effective learning rate: For a fixed total number of epochs, larger batches mean fewer parameter updates (fewer iterations). The model sees fewer noisy gradient evaluations, effectively exploring less of the loss landscape.

  3. Regularisation effect of noise: SGDStochastic Gradient Descent noise acts as implicit regularisation, similar to dropout or weight decay. Reducing noise by scaling the batch removes this regularisation.

Counterpoint. Subsequent work has shown that with careful training recipes (longer training, adjusted regularisation, SAMSharpness-Aware Minimization), large-batch models can match small-batch generalisation. The "generalisation gap" is not a law of nature but a failure of naive scaling — it signals that the optimisation procedure (not just the batch size) must be adapted.

What This Course Does Not Cover#

Distributed training beyond data parallelism is a rich field that this course only gestures at:

  • Model parallelism: Different layers of the network reside on different workers (pipeline parallelism). Used when a single model is too large for one GPU.
  • Tensor parallelism: Individual matrix multiplications are split across workers.
  • ZeRO / FSDP: Sharding optimiser states, gradients, and parameters to reduce per-GPU memory.
  • Gradient compression: Quantisation and sparsification to reduce all-reduce communication volume.

These are implementation concerns, not optimisation theory — they belong to systems for ML, not an optimisation curriculum. The conceptual takeaway: data-parallel scaling is mathematically clean (averaging independent gradient estimates) until communication cost or generalisation intervenes.

Exercise · Fill in the blank

If you double the number of workers while keeping each worker's local batch size unchanged, the global batch size ____.

Question 1 of 3

What is the purpose of an all-reduce operation in data-parallel training?

To broadcast model parameters to all workers
To sum or average gradients across all workers
To reduce the learning rate
To shuffle the dataset

Browser lab#

Simulate KKK workers each producing a noisy gradient estimate. Demonstrate that the variance of the averaged gradient falls as 1/K1/K1/K, and that the expected gradient is unbiased regardless of KKK.

python · runs in browser
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(123)
d = 100  # dimensional
true_grad = np.random.randn(d)

# Generate K workers, each with noisy gradient: true + noise
def simulate_workers(K, noise_std=1.0, n_trials=2000):
    estimates = np.zeros((n_trials, d))
    for t in range(n_trials):
        grads = np.array([true_grad + noise_std * np.random.randn(d) for _ in range(K)])
        estimates[t] = grads.mean(axis=0)
    # Variance of averaged gradient (averaged over dimensions and trials)
    var = np.mean(np.var(estimates, axis=0))
    bias = np.linalg.norm(estimates.mean(axis=0) - true_grad)
    return var, bias

K_values = [1, 2, 4, 8, 16, 32, 64]
variances = []
biases = []

for K in K_values:
    var, bias = simulate_workers(K, noise_std=1.0)
    variances.append(var)
    biases.append(bias)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

ax1.loglog(K_values, variances, "bo-", markersize=6, label="Empirical variance")
ax1.loglog(K_values, [variances[0]/k for k in K_values], "r--", linewidth=1, label=r"$\propto 1/K$ (theory)")
ax1.set_xlabel("Number of workers $K$")
ax1.set_ylabel("Variance of averaged gradient")
ax1.set_title("Gradient variance vs $K$")
ax1.legend()
ax1.grid(True, alpha=0.3)

ax2.plot(K_values, biases, "go-", markersize=6)
ax2.axhline(0, color="gray", linestyle="--", alpha=0.5)
ax2.set_xlabel("Number of workers $K$")
ax2.set_ylabel("$\|\|\mathbb{E}[\hat{g}] - \\nabla f\|\|$")
ax2.set_title("Bias of averaged gradient vs $K$ (unbiased)")
ax2.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

print("K    | Variance       | Bias")
print("-" * 35)
for K, var, bias in zip(K_values, variances, biases):
    print(f"{K:3d}  | {var:.6f}       | {bias:.6f}")
← Previous
Week 9: Variance Reduction
Next →
Week 11: Automatic Differentiation
On this page
  • Minibatch as Parallelism
  • Data Parallel Loop
  • Learning Rate Scaling Folklore
  • Generalization Gap Stories
  • What This Course Does Not Cover
  • Browser lab