Guided tour: generation (generate.py)
The autoregressive loop, from prompt to generated text
This file turns logits into a sequence: at each step, reprocess the context, read the logits at the final position, pick one token, append it, repeat. This page is the fifth and last stop (5 of 5) of the tour; the model is assumed read. Source: src/llm_lab/foundations/generate.py.
At each iteration, the generator validates the prompt, keeps the allowed context window, runs the model, reads the final-position logits, selects a token (greedy or sampled after temperature), appends it to the context, and repeats. This version does not cache keys/values or define an early-stopping rule; these limitations are part of its contract, not implicit features.
By the end of this tour, you will be able to: - unroll a generation by hand, sliding window included; - explain why greedy mode is reproducible without a seed and why temperature does not change the model; - distinguish the deliberate limitations (no KV cache, no early stopping) from omissions.
One step of the loop, in order
context = ids.astype(np.int64, copy=True)
for _ in range(max_new_tokens):
window = context[-model.config.context_length :]
logits = model.forward(window[None, :])[0, -1, :]
if greedy:
next_token = int(np.argmax(logits))
else:
probs = softmax_with_temperature(logits, temperature=temperature)
if top_k is not None:
probs = top_k_filter(probs, k=top_k)
if top_p is not None:
probs = top_p_filter(probs, p=top_p)
next_token = int(rng.choice(model.config.vocab_size, p=probs))
context = np.append(context, np.int64(next_token))
return np.asarray(context, dtype=np.int64)Hover over or select a loop line: its stage lights up. Keyboard: Tab, Enter to pin, Esc to release.
One full step: slice the window, run the model, read the last position, pick a token, append it to the context — then repeat, up to max_new_tokens.
Line by line:
astype(..., copy=True): the working sequence is a fresh int64 copy — the caller’s array is never mutated, and the return type is stable.window = context[-context_length:]: the sliding window. Once the sequence outgrows the context, only the lastcontext_lengthtokens enter the pass — tokens that fell out of the window no longer influence what follows.window[None, :]: a batch of one sequence; the forward pass expects(B, T).[0, -1, :]: batch 0, last position, all logits. PositionT-1predicts the token afterT-1— the only logit row useful for one more token.greedy:argmaxis deterministic — no seed needed; ties resolve to the lowest index (NumPy’s convention).- sampling: temperature scales the logits before the softmax (
T < 1sharpens,T > 1flattens), thenrng.choicedraws one id. Reproducibility comes from the caller’s seededrng. - optional truncation:
top_kthentop_pcut the distribution after temperature and renormalize the retained probabilities before the draw; in greedy mode they are validated but ignored. np.append: the token becomes context; the loop repeats.
temperature, top_k, and top_p are validated even in greedy mode. Temperature must be a finite positive real (not a boolean), top_k a positive integer (not a boolean or string), and top_p a real in (0, 1]. A call such as greedy=True, temperature=0.0 or top_k="3" fails before the loop: a hidden invalid value must not wait for a switch to sampling to reveal itself.
Two deliberate limitations, not two omissions
- No KV cache. Each step recomputes attention over the whole window:
O(T^2)work per token where a cache would make the incremental step much cheaper. The reference chooses inspectability; caching is an optimization topic, not a conceptual one. - No early stopping. The loop stops at
max_new_tokens, never at an end-of-text token: that rule belongs to the vocabulary/tokenizer layer, outside this milestone’s scope.
Common misconceptions. (1) Temperature does not change the model: same parameters, same logits; it only changes the distribution you sample from. (2) The model does not “plan” several tokens ahead: it produces a score for one next token; everything else is the loop.
What the tests verify
tests/unit/test_generate.py: greedy mode is deterministic and matches an independently recomputed argmax chain; sampling is reproducible at equal seed; the optional truncations follow an independently recomputed temperature → top-k → top-p chain; runtime checks reject boolean/text temperatures and text top_k values; a prompt filling the whole window still generates (sliding); max_new_tokens=0 returns the prompt unchanged.
Exercises
The questions for this tour and their worked answers are collected on its dedicated practice page. Try them before opening the answers: they check the stated outcomes without duplicating the prompts in the walkthrough.
Connections
- Previous stop: assembling the GPT (
gpt.py). - Back to the Build path: Build a small GPT.
Supplementary resources Experiment, explore further, and practise the ideas from this lesson.
Further reading
- Concept pages: generating text step by step, logits, probabilities.
- Back to the path: Build a small GPT.
- Source:
generate.py· Tests:test_generate.py.