All courses

Shifted targets and parallel training

Build targets by shifting the input one token left. Explain how causal masking lets one forward pass train all T predictions in parallel, with the true prefix always fed in (teacher forcing).

Builds on: Causal masking, The next-token cross-entropy objective

▶ Watch this lesson Start the whole course

What the animation says

Four problems in one chunk

Here is a training chunk: five token ids. Five, nine, two, seven, three. Hidden inside are four next-token problems. From five, predict nine. From five and nine, predict two. And so on, up to predicting three. Running the model once per prefix means four passes, redoing the same prefix work every time. So try a single pass over the text, with nothing hiding the future. What would position two learn to do?

Mask it, shift it

It would copy. Seeing the answer makes the guess free, and useless when generating new text. The causal mask fixes this. Each position sees only itself and the tokens before it. Now the output at every position is an honest next-token predictor. Feed in the first four tokens. Each position's correct answer is simply the next token in the text. Position one's target is nine. Position two's target is two. Position three reads the token two. Tap its target.

One pass, one loss

Seven. So the targets are nine, two, seven and three: the text shifted one step left. One forward pass gives a row of scores at every position, turned into probabilities. From each row, read the probability of its target: point two, point five, point one, point four. Take minus the log of each, then average. The loss is about one point three eight nats. Position three gave seven only point one. Suppose it bet on token four instead. When position four makes its prediction, which prefix does it see?

Teacher forcing vs generation

Position four sees five, nine, two, seven: the true text, never the model's guess. Every position is conditioned on the real prefix. This is called teacher forcing. Because no prediction waits on another, all four are scored together in one parallel pass. Generation is different. There, the next input is the model's own output. So generation must run one token at a time, each step waiting for the last.

Shift and score in numpy

Now in numpy. The chunk holds the five ids. This line does the shift: inputs drop the last token, targets drop the first. Z stands in for one forward pass: four rows of ten logits. Next, these three lines turn each row into log probabilities, safely. Finally each row needs just one entry: the log probability of its own target. Tap the line that picks those entries.

T predictions from one pass of the text?

A training chunk of $T{+}1$ tokens holds $T$ next-token problems: predict $x_2$ from $x_1$, $x_3$ from $x_{\le 2}$, and so on. Running the model separately on each prefix would take $T$ passes instead of one, redoing the shared prefix work every time. Can a single forward pass (one run of the model over the text) score all $T$ predictions at once and still be honest, with no position peeking at its own answer? If so, where do the targets come from?

Shift the text, let the mask hide the future

Feed the true tokens $x_1\dots x_T$ in once. Because of the causal mask, the output at position $t$ depends only on $x_{\le t}$, so each position is its own next-token predictor. Its correct answer is simply the next token in the text, so the targets are the input shifted one step left. Every position always sees the **true** prefix, never the model's own guesses. This is called **teacher forcing**.

Inputs, targets and the loss

From a chunk $(x_1,\dots,x_{T+1})$: - inputs: $(x_1,\dots,x_T)$ - targets: $y_t = x_{t+1}$ for $t=1\dots T$ One forward pass gives logits $Z\in\mathbb{R}^{T\times V}$, with row $z_t$ for position $t$. Then $$\mathcal{L} = -\frac{1}{T}\sum_{t=1}^{T} \log \mathrm{softmax}(z_t)[y_t].$$ Without the mask, position $t$ could attend to $x_{t+1}$, which is its own target. It would learn to copy it, and that is useless when generating.

Five tokens, four predictions

Chunk ids: $[5,9,2,7,3]$. Inputs $[5,9,2,7]$, targets $[9,2,7,3]$. Say one pass gives the targets probabilities $0.2, 0.5, 0.1, 0.4$. $$\mathcal{L}=\tfrac{1}{4}(1.609+0.693+2.303+0.916)=1.380 \text{ nats}$$ Position 3 gave its target 7 only $0.1$. Suppose it rated token 4 most likely. Position 4 still receives the true $[5,9,2,7]$ as its prefix, not $[5,9,2,4]$.

Shift and score in numpy

`Z` stands in for the model's output from one forward pass. The loss takes one term per position, using fancy indexing to pick each row's target.
import numpy as np
rng = np.random.default_rng(0)
V = 10
chunk = np.array([5, 9, 2, 7, 3])     # T+1 token ids
inp, tgt = chunk[:-1], chunk[1:]      # shift left by one
T = len(inp)
Z = rng.normal(size=(T, V))           # stand-in logits [T, V] from one pass
Z = Z - Z.max(axis=1, keepdims=True)  # log-sum-exp stability
logp = Z - np.log(np.exp(Z).sum(axis=1, keepdims=True))
loss = -logp[np.arange(T), tgt].mean()
print(inp, tgt, round(loss, 3))

Remember

The targets are the inputs shifted one token left. The causal mask makes every position an honest predictor, so one forward pass scores all $T$ predictions in parallel. Each prediction is conditioned on the true prefix (teacher forcing). Generation differs: there the next input is the model's own output, so it must go one token at a time.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.