Compare token-mean and sequence-mean SFT loss reductions

MediumFine-tuningPro

Why it matters Choosing token-level versus sequence-level averaging is a real SFT and RL design choice that changes what the model learns from long versus short answers.

How you average per-token losses changes how much each example counts. Long answers dominate a token-level mean; a sequence-level mean gives every example equal weight.

Write loss_reductions(token_losses, mask). Both are (B, T); mask is 1 on tokens that count. Return a dict:
- "token_mean": sum(loss * mask) / sum(mask)
- "seq_mean": average over rows with at least one counted token of (row sum of loss * mask) / (row count)
- "per_batch_sum": sum(loss * mask) / B
Use 0.0 for a value whose denominator is 0.

Signaturedef loss_reductions(token_losses, mask)

Example

loss_reductions([[1, 1, 0], [4, 0, 0]], [[1, 1, 0], [1, 0, 0]]) is {"token_mean": 2.0, "seq_mean": 2.5, "per_batch_sum": 3.0}.

Understand the idea

A batch has several answers of different lengths. Averaging over all tokens is like counting votes per word: a 100-token answer has 100 votes and a 5-token answer has 5. Averaging per sequence gives every answer one vote.

Example: answer A has two tokens with loss 1 each, answer B has one token with loss 4. Token mean = (1 + 1 + 4) / 3 = 2.0. Sequence mean = (A's mean 1 + B's mean 4) / 2 = 2.5. Dividing the total by the batch size gives 6 / 2 = 3.0, which also changes with how many tokens are in the batch.

Rule: token_mean = sum(l m) / sum(m); seq_mean = mean over non-empty rows of sum_t(l m) / sum_t(m); per_batch_sum = sum(l m) / B.

Pretraining usually uses the token mean. SFT and RL recipes argue about it: sequence means favour short answers per token, and some RL methods switched to token-level averaging so long reasoning traces are not under-weighted.

Shapes and data flow

token_losses, mask (B, T) -> row sums, row counts (B,) -> three scalars
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleloss_reductions([[1, 1, 0], [4, 0, 0]], [[1, 1, 0], [1, 0, 0]])
  • Sample 2: empty rowloss_reductions([[2, 2], [9, 9]], [[1, 1], [0, 0]])