Watch a generation loop stop on its own
Step a toy decoder until it emits its end token, and distinguish a requested token limit from a model-chosen stop.
An autoregressive loop has two ways to stop: the caller’s token limit, or a
token the model itself chooses, usually an end-of-sequence id. They are not
interchangeable. A request that stops at max_tokens may be cut off mid-answer;
a request that stops on EOS ended where the model intended. A service has to
report which happened.
This example runs the toy decoder from Chapter 04 with an explicit EOS id. The
interesting part is not the seven generated integers. It is that the loop
requests eight tokens, emits seven, and returns stop_reason: "eos" because the
seventh was token 15. The result object records the per-step token, the time and
the cumulative length, so the stopping rule is auditable after the fact.
Run it
From the canonical repository at commit
f958967d70992d7b09d9c75000bd8c543f1644d4:
python examples/ch05/generation_loop.py --max-new-tokens 8 --jsonPython 3.11 or later with PyTorch. The default path is the toy model: CPU-only,
seeded, no download, network, GPU or credentials. It finishes in about a second.
The optional --real path loads GPT-2 and is not required here.
Implementation
The loop appends one argmax token per iteration, records the step, calls the
optional streaming callback, then checks EOS. The default stop_reason is
max_tokens; only an observed EOS changes it to eos.
with torch.no_grad():
for _ in range(max_new_tokens):
step_start = time.perf_counter()
logits = model(torch.tensor([generated]))[0]
next_id = int(torch.argmax(logits[0, -1]).item())
generated.append(next_id)
step = GenerationStep(
token_id=next_id,
token_text=str(next_id),
seconds=time.perf_counter() - step_start,
cumulative_tokens=len(generated),
)
steps.append(step)
if callback is not None:
callback(step)
if eos_token_id is not None and next_id == eos_token_id:
stop_reason = "eos"
break
total_seconds = time.perf_counter() - start_total
new_ids = generated[len(prompt_ids):]
return GenerationResult(
prompt_ids=prompt_ids,
generated_ids=new_ids,
text_tokens=[str(i) for i in new_ids],
steps=steps,
stop_reason=stop_reason,
total_seconds=total_seconds,
metadata={"generator": "toy", "max_new_tokens": max_new_tokens},
)Expected outcome
Observed with the command above (exit 0). Selected stable fields:
"generated_ids": [
0,
13,
0,
0,
0,
4,
15
],
"stop_reason": "eos",Seven tokens were appended although eight were requested. The prompt ids were
1, 2, 3; the first step operated on those three positions, and the final token
was EOS. The per-step timing fields are omitted because they vary by machine and
by run; the token ids and stop reason are stable for this seed.
Mechanism and limitations
Documented: toy_generate rejects a non-positive token limit, calls
model.eval(), runs under torch.no_grad(), records a GenerationStep per
token, invokes a callback if supplied, and stops on eos_token_id when one is
given. run_toy_demo seeds PyTorch, builds a one-layer TinyTransformer with
vocabulary 16, and uses prompt [1, 2, 3] with EOS id 15. The tests check greedy
determinism, EOS stopping, the max_tokens path, callback count, invalid limits,
non-negative step times and JSON serialisation.
Observed: the command exited 0 with the seven ids above and
stop_reason: "eos". The targeted tests.test_ch05_generation ran in a 36-test
batch with Chapters 02-04 and reported OK.
Not shown: real text quality, tokeniser behaviour, sampling instead of greedy decoding, stop-string handling, streaming deltas, or the cost of recomputing the whole prefix each step. The toy model was never trained. The per-step times in this trace are Python and CPU overhead, not a transformer throughput result.
Challenge this result
Run the same command with --max-new-tokens 3. The EOS token is not reached, so
the stop reason should become max_tokens while the generated ids stay a prefix
of the longer run. Then set the EOS id to a token that cannot appear and explain
why a client that treats max_tokens as success may accept a truncated answer.
Which field should a serving API expose so the client can tell the difference?
Source and verification
Canonical source:
examples/ch05/generation_loop.py
at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests:
tests/test_ch05_generation.py
.
Chapter: Autoregressive Generation
.
The run above is a fresh local execution on Windows 11 with Python 3.13.15 and
PyTorch 2.6.0+cu124; it uses the toy model, not GPT-2.
Understand this example
Copy this prompt into your AI tool. No code runs here.
Apply this example
Copy this prompt into your AI tool. No code runs here.