Combine local mean gradients by their sample counts
Averaging worker mean gradients gives equal weight to workers, not examples. If workers processed different numbers of examples, the global mean gradient is a count-weighted reduction. This matters for short final batches and uneven work assignment.
The exercise performs the reduction on real local tensors and compares it with known weighted results. It is an algebraic prerequisite for distributed training, not an execution of DDP, an all-reduce backend or a multi-GPU benchmark. Real clusters additionally need consistent collective ordering, failure handling, synchronization and checkpoint recovery.
import torch
gradients=[torch.tensor([2.]),torch.tensor([8.])]
counts=[3,1]
print(sum(g*n for g,n in zip(gradients,counts))/sum(counts))Review the design
A reduction formula does not establish a distributed execution guarantee. The declared local objective, token/sample denominators and collective scaling must agree before this weighting matches the intended global gradient.
Your task
Implement weighted_gradient(gradients,counts) returning sum(g*n)/sum(n), same-shaped tensors with positive integer counts. Reject empty/mismatched inputs, invalid counts and unequal tensor shapes. Do not modify the inputs.
The explanation opens here once every check passes.