PythiloLesson 1 of 8 · progress kept in this browser

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())
This example uses torch. Run it in the Pythilo app, where these features are available.
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.

This lesson uses torch, which Python in this browser does not include. Read it here, and run and check it in the Pythilo app on iPhone or iPad.