Weight uneven microbatches by sample count
Accumulating the mean loss of every microbatch and then averaging microbatches gives a short final batch too much influence. To reproduce one full-batch mean gradient, sum each batch loss and divide by the total number of samples before backpropagation.
This exercise uses actual PyTorch autograd with a scalar parameter and deliberately unequal microbatches. It compares the gradient with the analytical full-dataset result. Distributed training has the same weighting question when local batch sizes differ. The local calculation does not execute an all-reduce or measure a real cluster.
import torch
w=torch.tensor(0.,requires_grad=True)
x=torch.tensor([1.,2.])
y=torch.tensor([2.,4.])
loss=((w*x-y)**2).mean()
loss.backward()
print(w.grad.item())Review the design
This reproduces full-batch gradients for a decomposable squared loss. Batch-dependent layers, stochastic operations and optimizer steps between microbatches can break equivalence even when the arithmetic weighting is correct.
Your task
Implement accumulated_gradient(batches,w0), where each batch is (xs,ys) nonempty equal lists. Use one scalar torch parameter, squared loss summed per batch divided by total sample count, backward each batch and return the gradient as float. Reject no batches or invalid lengths.
The explanation opens here once every check passes.