Shift inputs and targets for next-token prediction

Watch the spaces around tokens and probability values. · 185 words

Next-token prediction teaches a language model to guess the next token from earlier tokens. During training, the text is shifted by one position: the input begins at the first token, and each target is the token immediately after the corresponding input. For the four-token sequence "The cat sat down," the input sequence is "The cat sat" and the target sequence is "cat sat down." The model checks three predictions at once: "cat" from "The," "sat" from "The cat," and "down" from "The cat sat."

In a causal transformer, the attention mask prevents a position from looking ahead at its answer. For a second example, use the three tokens [I, like, tea]. The input array [I, like] aligns with the target array [like, tea]. The first position predicts like from I alone. The second predicts tea from the two-word prefix I like. At generation time, the model starts with a prompt, predicts one token, appends it to the context, and repeats. Teacher forcing usually supplies the known earlier tokens during training, so the model learns each conditional step without having to generate a whole text first.

Check your recall

What are the input and target sequences for "The cat sat down"?

Check your answer

The input tokens are [The, cat, sat] and the target tokens are [cat, sat, down].

Sources and credits

Original KeyTouch lesson. Background reading · Hugging Face · LLM Course.