REAL PYTORCH · CPU TRAINING AND AUTOGRAD
Accumulate unequal token microbatches by valid targets
Equal weighting of microbatch means overweights a short or heavily padded microbatch.
Run this Lab in Pythilo
Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.
No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.
PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.
Pythilo on the App Store →Read lesson: Accumulate unequal token microbatches by valid targets →
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.
Starter
import torch
def accumulated_token_loss(batches, pad=-1):
return NoneInspect the worked answer
import torch
from torch.nn import functional as F
def accumulated_token_loss(batches, pad=-1):
if not batches:
raise ValueError('at least one logits/target microbatch required')
total, count = None, 0
for logits, targets in batches:
if logits.ndim != 2 or logits.shape[0] == 0 or logits.shape[1] < 2 or targets.shape != logits.shape[:1] or targets.dtype != torch.long:
raise ValueError('nonempty logits and aligned integer targets required')
valid = targets != pad
n = int(valid.sum())
if n:
part = F.cross_entropy(logits[valid], targets[valid], reduction='sum')
else:
part = logits.sum() * 0
total = part if total is None else total + part
count += n
return total / count if count else total