Log inStart free
LESSON 11.01 · 6 STAGES · 3 CONTROLS · 3 CHECKS

Next-token prediction and causal language modeling

Watch a tiny model learn to guess each next token of two sentences.


EXPLAINER · 11.01 · TOKEN BAY
01
Stage 1 of 6 · Shift by one
Each target is the next input token. One sentence gives 7 examples of next-token prediction.
Explain it simply

You see one sentence: the dog sat on the rug. The bottom row is what the model reads, and the top row is what it must guess. Each target is the token that comes next. So one sentence of 8 tokens gives the model 7 small tests.

The sentence <s> the dog sat on the rug . splits into 7 inputs and 7 targets. Each target is the next token.

tokenstokens a position readsloss floorprobabilities, guessesloss, leaks, wrong inputshidden
Toy: 2 sentences, 9 tokens, trained from zero weights
HOVER OR TAP A SHAPE TO SEE ITS NUMBERS
causal
Which input tokens each position may read.
300
How many gradient steps the model trains.
true tokens
What the model reads during training.
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
yt=xt+1\sy{y}{data}{y_t} = \sy{x}{data}{x_{t+1}}
y5=x6=rugy_5 = x_6 = \text{rug}

The target at position t is the input at position t plus 1.

Show the code ▾Hide the code ▴ · Try it yourself · Python 3
import math

VOCAB = ["<s>", "the", "cat", "dog", "sat", "on", "mat", "rug", "."]
SENTENCES = ["<s> the cat sat on the mat .", "<s> the dog sat on the rug ."]
MASK = "causal"   # "causal" or "none"
STEPS = 300
FEED = "true"   # "true" (teacher forcing) or "own" (own guesses)
V, T, LR = len(VOCAB), 7, 1.0
ids = [[VOCAB.index(w) for w in s.split()] for s in SENTENCES]
b = [0.0] * V
W = {d: [[0.0] * V for _ in range(V)] for d in range(-(T - 1), T)}  # W[d][token][next]

def probs(xs, t, mask):
    z = b[:]
    for s in range(len(xs)):
        if mask == "none" or s <= t:
            z = [a + w for a, w in zip(z, W[s - t][xs[s]])]
    m = max(z)
    e = [math.exp(v - m) for v in z]
    total = sum(e)
    return [v / total for v in e]

def top(p):
    return next(k for k, v in enumerate(p) if v >= max(p) - 1e-9)

def inputs(sent, feed):
    if feed == "true":
        return sent[:T]                  # teacher forcing: the true tokens
    xs = [sent[0]]
    for t in range(T - 1):               # each guess becomes the next input
        xs.append(top(probs(xs, t, "causal")))
    return xs

def mean_loss(mask, feed):
    total = 0.0
    for sent in ids:
        xs = inputs(sent, feed)
        for t in range(T):
            total -= math.log(probs(xs, t, mask)[sent[t + 1]])
    return total / (2 * T)

for step in range(STEPS):
    gb = [0.0] * V
    gW = {d: [[0.0] * V for _ in range(V)] for d in W}
    for sent in ids:
        xs = inputs(sent, FEED)
        for t in range(T):
            p = probs(xs, t, MASK)
            g = [(p[k] - (k == sent[t + 1])) / (2 * T) for k in range(V)]
            gb = [a + c for a, c in zip(gb, g)]
            for s in range(T):
                if MASK == "none" or s <= t:
                    gW[s - t][xs[s]] = [a + c for a, c in zip(gW[s - t][xs[s]], g)]
    b = [a - LR * c for a, c in zip(b, gb)]
    for d in W:
        for k in range(V):
            W[d][k] = [a - LR * c for a, c in zip(W[d][k], gW[d][k])]

print(f"training loss {mean_loss(MASK, FEED):.3f}")  # 0.111
print(f"later tokens hidden {mean_loss('causal', 'true'):.3f}")  # 0.111
dog = ids[1]
xs = inputs(dog, FEED)
print("inputs:", " ".join(VOCAB[x] for x in xs))
# inputs: <s> the dog sat on the rug
for t in range(T):
    p = probs(xs, t, MASK)
    print(VOCAB[dog[t + 1]], f"{p[dog[t + 1]]:.2f}", "guess", VOCAB[top(p)])
# the 0.98 guess the
# dog 0.49 guess cat
# sat 0.99 guess sat
# on 0.99 guess on
# the 1.00 guess the
# rug 0.97 guess rug
# . 1.00 guess .

Copy it into a file and run it. Change MASK, STEPS and FEED.

Common mix-ups

MYTHA lower training loss always means a better model.

FIXWith no mask, each position reads its own target. The loss falls to 0.006, but with later tokens hidden it is 0.39.

MYTHIn training, the model reads its own guesses.

FIXTeacher forcing feeds the true tokens. With its own guesses, the dog sentence reads as cat, and the model never learns rug.

Predict, then reveal
0 / 3 REVEALED
Q01At step 0, all 9 tokens are equally likely. What is the loss?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q02If the mask is removed, does the training loss after 300 steps go up or down?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q03If the model trains on its own guesses, what probability does rug get after 300 steps?
1 · GUESS2 · TRY IT IN THE DIAGRAM

Takeaways

  1. A causal language model predicts each next token from the tokens before it.
  2. The causal mask hides later tokens, so training matches writing.
  3. Teacher forcing feeds the true tokens, so one pass trains every position.