All courses

Autoregressive generation loop

Generate text by repeatedly computing logits for the last position, picking or sampling a token, appending it and running the model again. Explain why output tokens are produced strictly one at a time.

Builds on: The decoder-only transformer, end to end

▶ Watch this lesson Start the whole course

What the animation says

Only the last row is new

One forward pass reads every token at once, and gives one row of predictions per position. Here the prompt is four tokens: the, cat, sat, on. So we get four rows. Each row predicts the token right after its position. Row one predicts the second token. But we already have it: cat. Tap the one row that predicts something we don't have yet.

Why not the whole reply at once?

So one pass gives us one genuinely new token. Why not read the token after that from the same pass? To predict position six, the model needs token five as input. But token five doesn't exist yet. It appears only once we choose it from row four. So a reply can't come out in one pass. Each token waits for the one before it. To get the token after next, what has to happen first?

Pass one, with real numbers

Pick, append, run again. Let's do it with a vocabulary of four: the, cat, sat, and end of text. The prompt is: the, cat. Two tokens in, so the logits are two rows of four. Keep only the last row. Exponentiate it: one, one, six, two. They sum to ten. Divide by ten: point one, point one, point six, point two. That's the softmax. Argmax picks sat. Sampling would pick it sixty percent of the time. Append it. Now pass two runs. What shape are its logits?

Stop, and count the cost

Pass two runs on all three tokens, so the logits are three by four. Again, only the last row matters. Its argmax is end of text, so we stop. Two passes, two new tokens. Every generated token costs exactly one pass. Each pass reads one more token than the last. The final token is never an input. It's what the last pass produces. When sampling, the chance of this reply is a product: point six, times the chance of end of text after 'the cat sat'.

The loop in numpy

Here's the loop in numpy. The model is a toy where row t only sees ids up to t. The loop is the real thing. Inside the loop: run the model on every id so far, and keep the last row. Softmax it, sample one id, and append it. The prompt has two ids and the loop runs four times. That's four passes, and the last pass reads five ids. This naive loop redoes the whole sequence every step. Tap the line that does it.

Why do replies arrive one token at a time?

One forward pass over $T$ tokens yields $T$ next-token distributions. Yet a model's reply appears token by token, and each new token costs another pass. Why can't the model produce a whole reply in one pass? And what exact loop turns a next-token predictor into something that writes text?

Only the last row predicts something new

Of the $T$ rows of logits, rows $1\ldots T-1$ predict tokens you already have: tokens $2\ldots T$ of the prompt. Only row $T$ is about an unseen position, $T+1$. Predicting position $T+2$ needs token $T+1$ as **input**, and that token does not exist until you choose it. So the loop is: run the model, pick one token from the last row, append it, run again.

The generation loop, precisely

The prompt has $T_0$ tokens. $T$ is the current length, starting at $T = T_0$. 1. Run the model on $x_1\ldots x_T$, which gives logits of shape $[T, V]$. Keep only the last row, $z_T$. 2. Compute $p = \mathrm{softmax}(z_T) = p_\theta(x_{T+1}\mid x_{\le T})$. 3. Set $x_{T+1} = \arg\max p$, or sample $x_{T+1} \sim p$. 4. Append it, set $T \leftarrow T+1$ and repeat. Stop at an end-of-text token or a length limit. If you sample, the probability of producing the continuation $x_{T_0+1}\ldots x_{T_1}$ is $\prod_{t=T_0}^{T_1-1} p_\theta(x_{t+1}\mid x_{\le t})$. That is one factor per generated token, each conditioned on everything before it.

Two steps with a 4-token vocabulary

Vocabulary: 0 = "the", 1 = "cat", 2 = "sat", 3 = end-of-text. Prompt: [0, 1]. **Pass 1:** the logits have shape $[2,4]$. The last row is $z_2=[0,0,\ln 6,\ln 2]$. Exponentiating gives $[1,1,6,2]$, which sums to 10, so $p=[0.1,0.1,0.6,0.2]$. Argmax picks token 2 ("sat"). Sampling would pick it 60% of the time. **Pass 2:** run on [0, 1, 2]. The logits have shape $[3,4]$, and the argmax of the last row is 3, so stop.

The loop in numpy

A toy causal "model" stands in for the transformer: row $t$ of its output depends only on ids up to $t$. The loop itself is the real thing. It runs the model on everything so far, takes the last row's logits, applies softmax, samples, and appends. Note that this naive version reruns the whole sequence every step.
import numpy as np
rng = np.random.default_rng(0)
V, d = 5, 8
W_E, W_U = rng.normal(size=(V, d)), rng.normal(size=(d, V))
def model(ids):                      # [T] ids -> [T, V] logits
    return np.cumsum(W_E[ids], axis=0) @ W_U   # row t sees ids[:t+1]
ids = [1, 3]                         # prompt
for _ in range(4):
    z = model(np.array(ids))[-1]     # logits of the last position only
    p = np.exp(z - z.max()); p /= p.sum()
    ids.append(int(rng.choice(V, p=p)))  # or int(z.argmax())
print(ids)

Remember

Generation is a loop: run the model, take the softmax of the **last** position's logits, pick or sample one token, append it, repeat. Outputs come strictly one at a time because each next distribution takes the previous chosen token as input. That token does not exist until it is picked.

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.