Compute cross-entropy when the vocabulary is split across GPUs

Why it matters Vocabulary-parallel cross-entropy avoids gathering huge logit matrices, which would otherwise dominate memory for models with large vocabularies.

With a large vocabulary, the output layer's logits are split by vocabulary across ranks. Cross-entropy can still be computed exactly with three small all-reduces: the max, the sum of exponentials, and the target logit.

Write vocab_parallel_ce(shards, targets). shards is a list of arrays, shard r has shape (T, V_r) and holds vocabulary ids offset_r to offset_r + V_r - 1 (offsets follow shard order; shards may differ in size). targets has length T with global ids. Simulate: each rank computes its row max, take the global max m (all-reduce max); each rank computes sum exp(logits - m), add them (all-reduce sum) to get Z; the rank owning each target contributes its logit, others contribute 0 (all-reduce sum) to get z_t. Loss per token = log Z + m - z_t. Return (mean loss, grads) where grads is a list of arrays shaped like the shards: softmax probabilities minus 1 at the target, divided by T (gradient of the mean loss).

Signaturedef vocab_parallel_ce(shards, targets)

Example

shards [[[2, 0]], [[1]]], targets [2] gives loss 1.4076 (rounded) and grads [[[0.6652, 0.09]], [[-0.7553]]] rounded to 4 places.

Understand the idea

Cross-entropy needs the softmax denominator, the sum of exp(logit) over the whole vocabulary. If the vocabulary is spread over 8 GPUs, each GPU can add up its own part, but only if they all subtract the same number first for numerical safety. So first agree on the global max, then add the parts. Worked example: one token, rank 0 holds logits [2, 0] for ids 0 and 1, rank 1 holds [1] for id 2, target 2. Global max 2. Rank 0 sum: e^0 + e^-2 = 1.135; rank 1: e^-1 = 0.368. Z = 1.503. Loss = log 1.503 + 2 - 1 = 1.408. Rule: loss = log(sum_r sum_v exp(z - m)) + m - z_target, with m and the sums shared by all-reduce. The full logit matrix never has to be gathered on one GPU.

Shapes and data flow

shard r (T, V_r)  max, Z, z_t (T,)  grads[r] (T, V_r)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: example(lambda r: (round(r[0], 4), [np.round(g, 4) for g in r[1]]))(vocab_parallel_ce([[[2, 0]], [[1]]], [2]))
  • Sample 2: matches full_check()