PythiloLesson 6 of 9 · progress kept in this browser

Practice in Lab: Accumulate unequal token microbatches by valid targets →

Accumulate unequal token microbatches by valid targets

Equal weighting of microbatch means overweights a short or heavily padded microbatch. Token-level training needs one denominator for the complete effective batch. The numerator is a sum over admitted targets, while padding contributes neither loss nor count. An all-padding batch still needs a graph-connected zero so backward remains defined. This exercise combines real independent computation graphs and checks that repartitioning the same tokens preserves both loss and gradients. It does not assume that stochastic layers or batch-dependent model behavior are equivalent across partitions.

counts = [3, 1]
means = [2., 4.]
print(sum(n*m for n,m in zip(counts, means))
      / sum(counts))
Your task

Each microbatch is (logits[N,C], targets[N]) with long targets and a pad sentinel. Sum cross-entropy over valid targets across all microbatches and divide once by the total valid target count. Return one scalar attached to every logits graph. All-padding microbatches contribute differentiable zero; an entirely padded collection returns differentiable zero. Reject an empty collection or invalid aligned shapes/dtypes.

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.