Average gradients across data-parallel workers
In data-parallel training each GPU holds a full copy of the model, computes gradients on its own shard of the batch, and the gradients are averaged so every copy takes the same step.
Shards can be uneven. Each worker reports (grad, n_examples) where grad is the gradient of the MEAN loss on its shard.
Write dp_gradient(worker_results) returning the gradient of the mean loss over all examples on all workers.
def dp_gradient(worker_results)Understand the idea
In data-parallel training every GPU holds a full copy of the model and computes gradients on its own slice of the batch. The gradients are then combined so every copy takes the same step. If each worker reports the gradient of its own mean loss and the slices have different sizes, a plain average gives the small slice too much say. Like averaging class marks from two sections: you weight each section by its number of students. Worked example: worker A reports grad 2.0 over 3 examples, worker B reports grad 6.0 over 1 example. Plain average = 4.0, wrong. Weighted: (3 x 2.0 + 1 x 6.0) / 4 = 12 / 4 = 3.0, which is the true gradient of the mean loss over all 4 examples. Gradients can be arrays; the same weighting applies element by element. Rule: global grad = sum over workers of (n_i x grad_i) / sum of n_i. With equal shard sizes this equals the plain average. PyTorch DDP and similar systems all-reduce gradients this way.