Next-token prediction and causal language modeling
Watch a tiny model learn to guess each next token of two sentences.
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.
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.
Takeaways
- A causal language model predicts each next token from the tokens before it.
- The causal mask hides later tokens, so training matches writing.
- Teacher forcing feeds the true tokens, so one pass trains every position.