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 None
Inspect 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

About this algorithm

How Accumulate unequal token microbatches by valid targets works

The idea

Gradient accumulation splits a batch that is too big for memory into microbatches and adds up their gradients. With text, microbatches hold different numbers of real tokens, because sequences differ in length and are padded.

If each microbatch reports its own mean loss and those means are averaged, a microbatch with 2 real tokens counts as much as one with 200. The fix is to make the result equal to the loss of one concatenated batch: sum the cross entropy over valid targets everywhere, count the valid targets, and divide once by the total. An all-padding microbatch adds logits.sum() * 0, a zero that stays attached to its graph so backward() still works.

How it works

  1. Reject an empty collection and any microbatch whose logits [N, C] and long targets [N] do not line up.
  2. Build the mask valid = targets != pad and count its true entries as n.
  3. If n is positive, add F.cross_entropy(logits[valid], targets[valid], reduction='sum') to total.
  4. Otherwise add logits.sum() * 0, a zero that is still connected to that microbatch's graph.
  5. Add n to the running count.
  6. Return total / count, or the differentiable zero when every target was padding.

What it costs

Time
O(T·C)
Memory
every graph kept
Scales with
tokens T, classes C

Cross entropy reads C logits for each of the T valid targets, and because one scalar covers all microbatches, every graph stays in memory until backward() runs.

Where it is used

  • fairseq sums token losses and divides the gradients by the total token count over the batches accumulated with --update-freq.
  • PyTorch's F.cross_entropy with ignore_index averages over the non-ignored targets only, the single-batch form of this rule.
  • Perplexity for language models is the exponential of total token loss divided by total token count, not an average of per-batch means.

Watch out for

  • Averaging the microbatch means, or dividing each by the number of microbatches: short microbatches then weigh as much as long ones.
  • Counting padded positions in the denominator: the loss shrinks as padding grows, although the model did not improve.
  • Calling mean-reduced cross entropy on an all-padding microbatch: zero divided by zero gives nan, which poisons the whole sum.