Compute a multi-token prediction loss over several heads

Why it matters Multi-token prediction heads are used in some recent LLMs as an extra training signal and for faster speculative decoding.

Multi-token prediction trains extra output heads to predict tokens further ahead: head 0 predicts the next token, head 1 the one after, and so on.

Write mtp_loss(head_logits, tokens, weights=None). head_logits is a list of K arrays of shape (T, V), where T = len(tokens). Head i at position t predicts tokens[t + i + 1], so only positions t with t + i + 1 < T count. loss_i is the mean cross-entropy over those positions (use a stable log-softmax). The total is the weighted mean of the loss_i with weights (default all ones), divided by the sum of weights. Return (losses, total) with losses a list of floats.

Signaturedef mtp_loss(head_logits, tokens, weights=None)

Example

tokens [0, 1, 2] with two heads of all-zero logits over V = 3 gives losses [1.0986, 1.0986] and total 1.0986.

Understand the idea

Normal language model training asks: given everything so far, what comes next? Multi-token prediction asks a few more questions at once: what comes after that, and after that? It is like a chess player planning several moves ahead.

Alignment is the whole trick. With tokens [a, b, c, d], head 0 at position 0 predicts b, head 1 at position 0 predicts c. Head 1 has no target at positions 2 and 3, so only rows 0 and 1 count.

Example: three tokens, two heads, all logits zero over 3 classes. Every prediction has probability 1/3, so each head's loss is ln 3 = 1.0986 and the average is 1.0986.

Rule: loss_i = mean over t < T - i - 1 of -log softmax(logits_i[t])[tokens[t + i + 1]]; total = sum(w_i * loss_i) / sum(w_i).

The extra heads share the trunk of the network, so they add a richer training signal cheaply, and at inference they can propose draft tokens for speculative decoding.

Shapes and data flow

head i logits (T, V) -> valid rows (T - i - 1, V) vs targets tokens[i+1:] (T - i - 1,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: examplemtp_loss([np.zeros((3, 3)), np.zeros((3, 3))], [0, 1, 2])
  • Sample 2: randommtp_loss([L1, L2, L3], [1, 3, 0, 2, 2])