Sign in

Distributed

Distributed data-parallel training

Data-parallel training with several synchronised workers: gradient averaging as in DDP, and local SGD with periodic parameter averaging.

Overview

One worker reads a batch, computes a gradient and takes a step. To go faster, give several workers a copy of the model and a different slice of the data each. They all compute a gradient at the same time. The gradients are then averaged and every worker takes the same step, so the copies never drift apart. Mathematically this equals one worker with a batch as large as all of theirs together. A looser variant lets the workers take a few steps alone and averages their models now and then.

A short history

Data-parallel training spreads each step over several workers that hold copies of one model. Jeffrey Dean and colleagues at Google described large scale distributed training of deep networks in 2012. Goyal and colleagues at Facebook showed in 2017 how to train with very large synchronised batches by scaling the learning rate with the batch size. Local SGD with periodic averaging was analysed by Sebastian Stich in 2018 and is the idea behind federated averaging. DDP stands for DistributedDataParallel, the PyTorch module for synchronised multi-GPU training.

How it works

  1. shard_indices shuffles the rows with a seed all workers share and deals them out, so each worker gets an equal slice, called a shard.
  2. Every worker starts from the same copy of the parameters, called a replica.
  3. In each step, every worker computes a gradient on a batch from its own shard, at the same time as the others.
  4. In sync_gradients mode, all_reduce_mean averages the gradients and every replica takes the same step with that average.
  5. In local_sgd mode, each worker steps with its own gradient, and every local_steps steps the replicas' parameters are averaged.
  6. replicas_in_sync checks that all workers hold the same parameters. fit returns one final set.

Watch out for

  • The effective batch is num_workers times batch_size, so each epoch has fewer steps. Keeping the single-worker learning rate then usually trains more slowly per epoch.
  • If workers used different seeds for the shuffle, their shards would overlap and leave gaps, and some rows would never be seen.
  • Shards are padded by repeating a few rows so all have equal length, so those rows count slightly more in that epoch.
  • Local SGD lets replicas drift between averagings. With many local steps or very different shards, the averaged model can be worse than any of the replicas.
  • Here the workers are threads in one process and the all-reduce is an in-memory average. The algorithm is real, but this small version shows no hardware speed-up and has no network or fault tolerance.

Use cases

When to use it

To understand, test or prototype the logic of distributed training before moving to a real backend: how data is sharded, why the effective batch grows with the number of workers, and what keeping replicas in sync means.

In industry

Large language and vision models
Models trained on billions of examples are fitted on many GPUs at once, each computing gradients on its own shard, with the gradients averaged every step.
Mobile and privacy-sensitive data
In federated learning, phones train locally for several steps and send back parameters to be averaged, which is local SGD with the data kept on the device.
Speech and recommendation
Teams with fixed training deadlines add workers to shorten each retraining run, accepting that the effective batch grows with the number of workers.

Choosing it: what must hold

  • A dataset and model large enough that one device is the bottleneck.
  • Several GPUs or machines with fast links between them.
  • A learning rate retuned for the larger effective batch.
  • Data that can be sharded evenly, with all workers sharing a seed.

When to choose something else

IfUse instead
The model trains in acceptable time on one deviceThe single-process trainer lesson
The batch does not fit in memory but there is only one deviceGradient accumulation in the trainer lesson
Communication between workers is slow or costlyThe local SGD mode of this lesson, which synchronises only every few steps

Math foundations

  1. A worker's gradient

    gr=1b∑i∈Br∇θ ℓi(θ)g_r = \frac{1}{b} \sum_{i \in \mathcal{B}_r} \nabla_{\theta}\, \ell_i(\theta)

    Worker rr averages the gradient over its own batch of bb samples, using its replica of the parameters.

  2. All-reduce: average over workers

    gˉ=1W∑r=1Wgr\bar{g} = \frac{1}{W} \sum_{r=1}^{W} g_r

    The workers' gradients are combined into one. In a real cluster this is a network operation, here it is an in-memory mean.

  3. The synchronous step

    θ←θ−η gˉ\theta \leftarrow \theta - \eta\, \bar{g}

    Every replica applies the same update. Since they started equal and move equally, they stay identical.

  4. Why it equals one large batch

    gˉ=1Wb∑r=1W∑i∈Br∇θ ℓi(θ)\bar{g} = \frac{1}{W b} \sum_{r=1}^{W} \sum_{i \in \mathcal{B}_r} \nabla_{\theta}\, \ell_i(\theta)

    Substituting the first formula into the second gives the average over all WbW b samples. WW workers with batch bb take exactly the step of one worker with batch WbW b.

  5. Local SGD

    θr←θr−η gr    (H times),thenθr←1W∑s=1Wθs    for all r\theta_r \leftarrow \theta_r - \eta\, g_r \;\; (H \text{ times}), \qquad \text{then} \quad \theta_r \leftarrow \frac{1}{W} \sum_{s=1}^{W} \theta_s \;\; \text{for all } r

    Each worker follows its own gradient for HH steps, then all replicas are replaced by their average. Less communication, at the price of a slightly different path.

  6. Steps per epoch

    S=⌈⌈n/W⌉b⌉S = \left\lceil \frac{\lceil n / W \rceil}{b} \right\rceil

    Each worker's shard has ⌈n/W⌉\lceil n / W \rceil rows and is walked in batches of bb. More workers mean fewer, larger steps per epoch.

Symbols

WW
num_workers
bb
batch_size per worker
Br\mathcal{B}_r
batch of worker r in the current step
grg_r
gradient computed by worker r
gˉ\bar{g}
gradient averaged over the workers
θ, θr\theta,\, \theta_r
the parameters, and the replica held by worker r
η\eta
learning rate
HH
local_steps between two parameter averagings
nn
number of training rows
SS
optimizer steps per epoch

Worked by hand

Train on n=512n = 512 rows with W=4W = 4 workers and b=16b = 16. In one step the four workers compute gradients 2, 4, 3 and 3 for a parameter with value 1, and η=0.1\eta = 0.1.

⌈5124⌉=128 rows per shard,S=⌈12816⌉=8\left\lceil \frac{512}{4} \right\rceil = 128 \text{ rows per shard}, \qquad S = \left\lceil \frac{128}{16} \right\rceil = 8
Wb=4×16=64 samples per stepW b = 4 \times 16 = 64 \text{ samples per step}
gˉ=2+4+3+34=3\bar{g} = \frac{2 + 4 + 3 + 3}{4} = 3
θ←1−0.1×3=0.7\theta \leftarrow 1 - 0.1 \times 3 = 0.7

Each epoch has 8 steps on an effective batch of 64. One worker with batch 16 would take 32 smaller steps over the same data. All four replicas now hold 0.7.

Visual example

Loading the example.

Try this

  • Press Step and read the table: each worker has its own batch and its own gradient, and all replicas take the same step.
  • Switch to local_sgd with local_steps at 4: the replicas drift apart for four steps and are pulled back together.
  • Raise num_workers and check the steps per epoch against S in the readout.

Code sample

import numpy as np
from impl import DistributedTrainer, linear_regression_grad
from config import DistributedConfig

rng = np.random.default_rng(0)
X = rng.normal(size=(512, 3))
y = X @ np.array([1.0, -2.0, 0.5]) + 0.3

trainer = DistributedTrainer(DistributedConfig(num_workers=4, batch_size=16, epochs=20, lr=0.1))
params = trainer.fit({"w": np.zeros(3), "b": np.zeros(1)}, linear_regression_grad, X, y)
print(params["w"], params["b"])                       # close to [1, -2, 0.5] and [0.3]
print(trainer.replicas_in_sync(), trainer.history["loss"][-1])
Read the implementation (137 lines)
"""Data-parallel distributed training, at toy scale: several workers, each with a model replica and a shard
of the data, kept in step by averaging gradients (synchronous SGD, the DDP scheme) or parameters (local SGD).

NumPy and the standard library only. The workers are THREADS in one process, not GPUs or machines, and the
"all-reduce" is a plain average in memory. What is real is the algorithm: the sharding of the data, the
per-worker gradient computation running concurrently, the reduction, and replicas that stay identical. The
tests check the defining property, that W workers with batch b take exactly the steps of one worker with
batch W * b.

A model is described by a dict of parameter arrays and a function
    grad_fn(params, X, y) -> (mean loss over the batch, dict of gradients with the same keys)
"""
from __future__ import annotations

from concurrent.futures import ThreadPoolExecutor
from typing import Callable

import numpy as np

try:
    from .config import DistributedConfig
except ImportError:  # run from the template's own folder
    from config import DistributedConfig


def shard_indices(n: int, num_workers: int, epoch: int = 0, seed: int = 0, shuffle: bool = True) -> list[np.ndarray]:
    """Split the rows 0..n-1 between the workers for one epoch.

    The (optionally shuffled) index list is padded by wrapping around until its length is a multiple of
    num_workers, then worker r takes every num_workers-th index starting at r. So the shards have equal
    size, they are disjoint apart from the few padded rows, and every row is seen by some worker. All
    workers must use the same seed and epoch, which is how they agree on the split without talking.
    """
    order = np.random.default_rng(seed + epoch).permutation(n) if shuffle else np.arange(n)
    total = -(-n // num_workers) * num_workers
    order = np.concatenate([order, order[: total - n]])
    return [order[rank::num_workers] for rank in range(num_workers)]


def all_reduce_mean(trees: list[dict]) -> dict:
    """Average a list of {name: array} dicts key by key. With gradients this is the all-reduce of
    synchronous SGD; with parameters it is the model averaging of local SGD."""
    return {name: sum(tree[name] for tree in trees) / len(trees) for name in trees[0]}


def linear_regression_grad(params: dict, X: np.ndarray, y: np.ndarray) -> tuple[float, dict]:
    """Mean squared error of y_hat = X @ w + b. params: "w" (d,), "b" (1,). X: (n, d), y: (n,)."""
    error = X @ params["w"] + params["b"][0] - y
    return float((error**2).mean()), {"w": 2.0 * X.T @ error / len(y), "b": np.array([2.0 * error.mean()])}


def softmax_regression_grad(params: dict, X: np.ndarray, y: np.ndarray) -> tuple[float, dict]:
    """Cross-entropy of a linear classifier. params: "W" (d, k), "b" (k,). X: (n, d), y: (n,) int labels."""
    logits = X @ params["W"] + params["b"]
    logits = logits - logits.max(axis=1, keepdims=True)              # stable softmax
    proba = np.exp(logits)
    proba /= proba.sum(axis=1, keepdims=True)
    rows = np.arange(len(y))
    loss = float(-np.log(proba[rows, y]).mean())
    delta = proba
    delta[rows, y] -= 1.0                                            # d loss / d logits, times n
    return loss, {"W": X.T @ delta / len(y), "b": delta.mean(axis=0)}


class DistributedTrainer:
    """Train with several workers that stay synchronised.

    After `fit`:
        replicas_  list of num_workers parameter dicts, one per worker
        history    {"loss": mean worker loss per epoch, "steps": optimizer steps per worker,
                    "syncs": number of all-reduce rounds}
    """

    def __init__(self, config: DistributedConfig | None = None) -> None:
        self.config = config or DistributedConfig()
        self.replicas_: list[dict] = []
        self.history: dict = {}

    def replicas_in_sync(self, atol: float = 0.0) -> bool:
        """True when every worker holds the same parameters (to within atol)."""
        first = self.replicas_[0]
        return all(np.allclose(replica[name], first[name], rtol=0.0, atol=atol)
                   for replica in self.replicas_[1:] for name in first)

    def fit(self, params: dict, grad_fn: Callable, X, y) -> dict:
        """Train and return the final parameters (a new dict; `params` is not modified).

        params:  initial parameters, {name: float array}. Every worker starts from a copy.
        grad_fn: function(params, X_batch, y_batch) -> (loss, grads).
        X: (n, ...), y: (n, ...).
        """
        cfg = self.config
        X, y = np.asarray(X), np.asarray(y)
        if len(X) != len(y):
            raise ValueError(f"X has {len(X)} rows, y has {len(y)}")
        workers = range(cfg.num_workers)
        self.replicas_ = [{name: np.array(value, dtype=float) for name, value in params.items()} for _ in workers]
        self.history = {"loss": [], "steps": 0, "syncs": 0}

        def local_gradient(job):
            """What one worker does in a step: a gradient on its own batch with its own replica."""
            rank, batch = job
            return grad_fn(self.replicas_[rank], X[batch], y[batch])

        def synchronise() -> None:
            """Average the replicas' parameters and give every worker the result."""
            mean = all_reduce_mean(self.replicas_)
            for replica in self.replicas_:
                for name in replica:
                    replica[name][...] = mean[name]
            self.history["syncs"] += 1

        with ThreadPoolExecutor(max_workers=cfg.num_workers) as pool:
            for epoch in range(cfg.epochs):
                shards = shard_indices(len(X), cfg.num_workers, epoch, cfg.seed, cfg.shuffle)
                losses = []
                for start in range(0, len(shards[0]), cfg.batch_size):
                    jobs = [(rank, shards[rank][start: start + cfg.batch_size]) for rank in workers]
                    results = list(pool.map(local_gradient, jobs))       # the workers compute concurrently
                    losses.append(float(np.mean([loss for loss, _ in results])))
                    self.history["steps"] += 1
                    if cfg.mode == "sync_gradients":
                        grads = all_reduce_mean([g for _, g in results])  # one gradient for everybody
                        self.history["syncs"] += 1
                        for replica in self.replicas_:
                            for name in replica:
                                replica[name] -= cfg.lr * grads[name]
                    else:
                        for replica, (_, grads) in zip(self.replicas_, results):
                            for name in replica:                          # each worker follows its own gradient
                                replica[name] -= cfg.lr * grads[name]
                        if self.history["steps"] % cfg.local_steps == 0:
                            synchronise()
                self.history["loss"].append(float(np.mean(losses)))
        if cfg.mode == "local_sgd" and not self.replicas_in_sync():
            synchronise()  # end on a common model
        return {name: value.copy() for name, value in self.replicas_[0].items()}
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Run DistributedTrainer(DistributedConfig(num_workers=4, batch_size=16, epochs=20, lr=0.1)).fit(params, linear_regression_grad, X, y) on the template's README data and read replicas_in_sync() and history. Then set mode="local_sgd" with local_steps 4 and 32, and compare the final loss and history["syncs"].

Check on learning

  1. Going from 1 worker to 8 with the same per-worker batch and learning rate, the loss after one epoch is worse. Nothing is broken. Why?
    A way to think about it

    Count the optimizer steps per epoch in each case. Then ask what a larger learning rate would do, given that the averaged gradient is less noisy.

  2. Why must every worker use the same seed and epoch number when sharding the data?
    A way to think about it

    Each worker computes the full shuffled order by itself and takes every WW-th row. Check what happens to that scheme if the orders differ.

  3. In synchronous mode the replicas are always identical. Why keep WW copies at all, instead of one shared set of parameters?
    A way to think about it

    On real hardware each worker is a separate device or machine with its own memory. Ask what a worker needs to have locally to compute a gradient.

  4. Local SGD with local_steps 1 and local SGD with local_steps 100: which is closer to synchronous training, and what does the other one gain and risk?
    A way to think about it

    With one local step, compare averaging the parameters after a step with averaging the gradients before it. Then think about communication cost and drift.

  5. One worker's shard happens to hold mostly one class. How does that affect synchronous gradient averaging compared with local SGD?
    A way to think about it

    In one case the odd gradient is diluted at every step. In the other the worker follows it alone for a while before anyone corrects it.