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))Review the design
Define the effective batch objective before adding accumulation, clipping or distributed reduction. Zero valid targets can require skipping an optimizer step even when backward is defined.
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.
The explanation opens here once every check passes.