advanced28 min studyLesson 541 in Engineering

Replicated training: agree on the gradient and the update

Derive default DDP gradient averaging and identify the initialization, optimizer, and collective assumptions that keep replicas aligned.

On this page

What you’ll understand

  • Derive the gradient delivered by default DDP averaging.
  • Distinguish synchronized gradients from parameter broadcasts and data sharding.
  • State the conditions under which local optimizer updates preserve replica agreement.

Data parallel training runs a model replica on each worker while workers process different inputs. The useful invariant is more precise than “the GPUs stay synchronized”: corresponding parameters begin consistently, workers agree on the intended aggregate gradient, and compatible optimizer state transforms that gradient into the same next parameters. We use PyTorch 2.9 DistributedDataParallel with its default averaging behavior, a fixed participating process group, and no custom communication hook. Hooks, uneven-input join settings, or alternative algorithms can change the aggregation contract.

DDP synchronizes gradients rather than partitioning the objective

DDP does not choose which examples each worker receives. The input pipeline or sampler must establish the intended global batch, including duplicates, padding, and dropped examples. Each worker computes a local loss and its gradient at the current replica parameters. Under the stated default reducer, corresponding gradients are summed across the group and divided by the group size. Equal-size local mean losses therefore produce the global mean gradient for a separable per-example objective. Local sums instead produce an average of sums, which has a different scale from one global sum.

Identify the objective before adjusting the learning rate. A missing division and a deliberately changed global batch are different changes, even if either can be disguised by one learning-rate setting in a simple SGD experiment. Regularization terms, gradient clipping, momentum, and adaptive optimizer state make that disguise unreliable. Use small deterministic gradients to expose the reducer’s scale directly. Changing world size without revisiting local loss reduction can change the mathematical update while throughput and reported local losses still look reasonable.

gˉt=1W∑r=0W−1∇θLr,t(θt)\bar g_t=\frac1W\sum_{r=0}^{W-1}\nabla_\theta L_{r,t}(\theta_t)
W is the positive fixed process-group size, and Lr is the explicitly chosen local scalar loss. This is the default averaging contract assumed here, in exact arithmetic and without a custom hook, compression, or uneven-input divisor change. Gradient units follow the loss and parameter units.↔ Scroll wide equations horizontally.

Replica agreement includes optimizer and buffer state

Default initialization synchronization establishes matching model parameters when enabled; disabling that synchronization transfers responsibility to the application. During ordinary training, DDP does not repair arbitrary parameter divergence with a parameter broadcast after every optimizer step. Replicas remain aligned because they apply equivalent updates to matching state using the synchronized gradients. An optimizer restored differently on one worker, a rank-dependent clipping decision, or a scheduler advanced on only one worker can break this reasoning even when the reducer returned matching gradients.

Non-parameter buffers have a separate contract, including configured buffer broadcasts. Batch normalization statistics and stochastic model behavior also matter when comparing a distributed run with a single global-batch reference. A rank-local batch-dependent operation need not equal the same operation on concatenated inputs. Start an equivalence fixture with a separable deterministic model, then deliberately add such features with their intended semantics stated. Agreement among replicas and equivalence to a particular reference objective are related but distinct properties.

(θt+1,st+1)=U(θt,st,gˉt,ht)(\theta_{t+1},s_{t+1})=U(\theta_t,s_t,\bar g_t,h_t)
U denotes the same optimizer update on every rank, s optimizer state, and h the same hyperparameters and step-dependent settings. Identical inputs imply agreement in this mathematical model; floating-point kernels and nondeterminism can require tolerance-based comparison.↔ Scroll wide equations horizontally.

Treat participation and completion as correctness conditions

Every required collective must have matching participants, compatible tensors, and compatible order. A faster worker cannot safely decide to skip synchronization merely because its local loss is small. Likewise, a communication future being created does not mean the reduced buffer is already safe for an optimizer to consume or overwrite. Use the framework’s documented completion and stream dependencies. Log rank, step, tensor metadata, and the first mismatch when debugging, rather than infer correctness from workers reaching similar wall-clock timestamps.

The optimization lab isolates an update-scale consequence. Reset, explicitly set step size 0.1 and initial position two, predict the first iterate, then Step once. Compare a fresh Reset with step size 0.2 and initial position two explicitly set, again predicting before one Step. For its fixed objective x²/2, the iterates are 1.8 and 1.6. Doubling an effective gradient scale resembles doubling this toy step size, but the instrument has no replicas, all-reduce, optimizer state, data pipeline, or distributed completion semantics.

Two gradients produce one agreed SGD update

Two replicas start from scalar parameter ten with identical stateless SGD settings and learning rate 0.1. Their local gradients are two and six. Assume the stated default averaging reducer and completed synchronization.

  1. The summed local gradient is eight. Dividing by the two participating replicas gives an aggregate gradient of four; it is neither the first worker’s gradient nor the global sum of eight.

  2. Each replica applies the same update: ten minus 0.1 times four equals 9.6. Identical starting parameters and update settings make the next parameters agree under exact arithmetic.

  3. If one worker instead consumes a sum of eight, its update reaches 9.2. Broadcasting a diagnostic loss or observing that both workers completed backward does not establish that the intended mean-gradient contract was used. Inspect the actual gradient and update state.

The result

Both correct replicas reach 9.6. Their agreement depends on the reducer scale, completed communication, and matching update inputs.

Explore the model

Interactive lab

Interactive lab · optimization

A scale error changes a simple update immediately

Use independent Reset → explicitly set BOTH step size and initial position → predict → Step runs for (.1,2) and (.2,2). The fixed quadratic gives first iterates 1.8 and 1.6. The instrument does not perform distributed reduction or simulate a real optimizer state.

A scale error changes a simple update immediatelyGradient descent on f(x) = x²/2: xₙ = (1 − η)ⁿx₀. Playback advances two discrete iterations per second. Values outside |x| ≤ 4 are explicitly reported. Current readings: Position x0: 2; Objective x²/2: 2; Iteration behavior: Stable step. All parameters are adjustable with the labeled controls below.−4−202402.174.356.528.7Parameter xf(x) = x²/2n = 0
ObjectiveDiscrete iterate
Position x0
2
Objective x²/2
2
Iteration behavior
Stable step
n = 0 · t = 0 s

Gradient descent on f(x) = x²/2: xₙ = (1 − η)ⁿx₀. Playback advances two discrete iterations per second. Values outside |x| ≤ 4 are explicitly reported. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forCheck aggregation scale before explaining a distributed update through learning-rate tuning.

Check your understanding

DDP returns the same averaged gradient on every rank, but one rank restored a different momentum buffer. What follows?

Try it yourself

Three identical scalar replicas start at five with stateless SGD learning rate 0.2. Their local gradients are one, two, and six. Compute the default averaged gradient and next parameter. What changes if a custom hook returns an undivided sum?

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Separate the collective’s aggregate from the optimizer update, and retain the hook assumption explicitly.

Compare with the solution

The default gradient is (1+2+6)/3=3, so every matching replica reaches 5−0.2×3=4.4. An undivided sum gives nine and reaches 3.2 instead. A custom hook can define another algorithm, but its output must be accounted for rather than assumed to inherit default averaging. Matching initial parameters, optimizer state, hyperparameters, participation, and completion remain necessary to interpret replica agreement and reference equivalence.

Take it with you

  • State local loss reduction and the reducer divisor explicitly.
  • Matching gradients preserve agreement only with matching update state.
  • Input partitioning and non-parameter behavior require separate contracts.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.