AlgoViz

From an example to a next-token prediction

easy 7 min

Generation is a sequence of conditional choices.

Video lesson · Chapter 1 of 4

The parcel dispatch desk

0:00 / 3:03

Theory

Read or listen first. About 2 min.

What it is

Generation is a sequence of conditional choices. During training a model learns which continuations reduce prediction error across many prefixes. At inference it runs the learned network on the current prefix, samples or selects a token, appends that token and repeats.

Why it exists

Prediction and verification answer different questions. A model can produce the day of the week that fits a sentence while having no access to the delivery schedule. Decide which answers may be generated from context alone and which must be checked against a record.

Which word follows the delivery notice?

Prefix → Vocabulary scores (encode prefix). Vocabulary scores → Next prefix (pass logits). Next prefix → Prefix (append selected token)
Prefix → Vocabulary scores (encode prefix). Vocabulary scores → Next prefix (pass logits). Next prefix → Prefix (append selected token)

Inside this chapter

Chapter sources
What is an LLM?
A language model estimates a distribution over the next token from the prefix it has seen. Generating an answer means repeating that operation with an ever longer prefix. A fluent explanation of yesterday’s refund rules can therefore sound convincing even when the policy changed this morning. Supply current evidence when the answer depends on external facts.

At every step the model produces a score for each vocabulary entry, a decoder picks one, and the chosen token is glued onto the prefix before the next step. Nothing in that loop looks anything up: the only facts available are those absorbed during training and those placed in the prompt. That is why a model can describe last year's refund policy with total confidence. You notice the problem when answers are fluent but disagree with the current record, so log which evidence was in the prompt for each answer.

Example. Offer the prefix “The museum opens at” without its timetable. Compare two completions with the actual opening hours and mark the missing evidence.

Another example. A support bot asked about a parcel's delivery date can write a convincing weekday. Unless the carrier's tracking record for that order is in the prompt, that weekday is a plausible continuation, not a lookup.

A fluent guess is not a checked fact

Both completions read naturally. Only the supplied timetable can say which one is right.
Neural Networks Recap
A layer multiplies its input by learned weights, adds a bias and applies a transformation. During training, a loss measures error and backpropagation assigns gradients to those weights. During ordinary inference the weights stay fixed. Correcting a chatbot in one conversation changes its input context, not its training parameters.

Training and inference run the same arithmetic but differ in what is allowed to change. In training, a loss compares the output with a target, backpropagation works out how much each weight contributed to the error, and an optimiser nudges every weight. In inference the weights are frozen and only the input varies. So when a user corrects a chatbot mid-conversation, the correction lives in the prompt for that session and vanishes when the session ends.

Example. A one-input unit with w=2w=2, b=−1b=-1 and ReLU produces 5 at x=3x=3 and 0 at x=0x=0. New inputs change outputs while the weights stay fixed.

One unit, fixed weights, different inputs

Input xw·x + b (w = 2, b = -1)ReLU output
355
111
0-10
The weights never change between rows. Only the input does, so only the output does.
The "Next Token" Concept
Given “the delivery arrived on”, the model scores every possible continuation. Selecting “Tuesday” appends that token and changes the distribution used by the next step. Training can score many positions together with a causal mask. Autoregressive generation still needs the previously selected token before it can extend that particular answer.

During training the model sees whole sentences at once and a causal mask stops each position from peeking at later ones, so it can learn from every position in parallel. Generation cannot do that, because the token at step five does not exist until step four has been chosen. This is why output length drives latency: every new token costs one more pass through the network.

Example. Start with two candidates, “red” and “blue.” After choosing “red,” ask for the next distribution using the entire new prefix, including that choice.

Another example. A coding agent writing a 300-token function performs 300 sequential decoding steps, even though the prompt of several thousand tokens was processed in one parallel pass.

Each choice becomes part of the next question
  1. 1PrefixThe car is
  2. 2Score candidatesred 0.55 · blue 0.45
  3. 3Choose onered
  4. 4AppendThe car is red
  5. 5Score againnew distribution from the longer prefix
Repeat: back to Prefix

Illustrative probabilities. The loop repeats until a stop token or length limit.

Probability Distributions Visualized
Logits express relative preference on an unrestricted scale. Softmax converts them into nonnegative probabilities whose sum is one. Adding the same constant to every logit changes none of the probabilities. A token with twice another token’s probability can still lose a random draw.

Logits are raw preferences that can be any real number. Softmax exponentiates each one, which makes them all positive, then divides by the total so they sum to one. Because a common factor cancels top and bottom, only differences between logits matter. The probabilities describe how often each token would be drawn, not how likely the resulting statement is to be true.

Example. For logits [0, 0], each token receives 0.5. Adding 10 to both logits still gives [0.5, 0.5].

Shifting every logit changes nothing

pi=ezi+c∑jezj+c=ec eziec∑jezj=ezi∑jezjp_i=\frac{e^{z_i+c}}{\sum_j e^{z_j+c}}=\frac{e^{c}\,e^{z_i}}{e^{c}\sum_j e^{z_j}}=\frac{e^{z_i}}{\sum_j e^{z_j}}
Logits [0, 0] and [10, 10] both give [0.5, 0.5]. Only the gaps between logits matter.
The Chef Analogy
Imagine a chef choosing an ingredient after tasting the dish so far. Salt changes which ingredient makes sense next. In generation, the prefix is the dish and the selected token changes the next distribution. The analogy stops at factual verification: a model can continue a recipe coherently without having tested the result.

The analogy is useful for one idea: each choice is conditioned on everything before it, and once made it changes what follows. It is misleading if it suggests the model has a goal for the finished dish or tests it. A model can write a coherent recipe it has never cooked, so treat checks against records as part of the application, not part of generation.

Example. Salt the soup before choosing the next ingredient. Compare with appending “Tuesday” before scoring the next word. Neither operation checks the carrier’s timetable.

Where the analogy holds and where it stops

  • Dish so far

    The prefix. Everything already added shapes what comes next.

  • Next ingredient

    The next token, chosen in light of the dish so far.

  • Salt changes the plan

    Appending Tuesday changes the next distribution, just as salt changes the next ingredient.

  • Nobody tastes the result

    The model never checks the carrier timetable. Verification is a separate step.

How it works

Step through the idea, or press Play.

Step 1 of 3

Prefix. “Delivery arrives on”

Understand it

Worked example

Which word follows the delivery notice?

  1. 1

    “Delivery arrives on”

    The text ends before a weekday. Training examples have shaped likely continuations; no live shipping record has been consulted.

  2. 2

    Mon 2 · Tue 1 · Fri 0

    In this three-token example the decoder produces logits. Softmax turns their differences into probabilities of about 0.67, 0.24 and 0.09.

  3. 3

    “Delivery arrives on Monday”

    Choosing Monday appends one token. The next prediction uses the extended text. Nothing in that operation verifies a delivery date.

Convert scores to probabilities

pi=exp⁡(zi)∑jexp⁡(zj)p_i=\frac{\exp(z_i)}{\sum_j \exp(z_j)}
For logits 2, 1 and 0, exponentiate each score and divide by their sum. The three probabilities are approximately 0.665, 0.245 and 0.090.

Follow the handoffs

Prediction and verification answer different questions. A model can produce the day of the week that fits a sentence while having no access to the delivery schedule. Decide which answers may be generated from context alone and which must be checked against a record.

From logits to probabilities, by hand

TokenLogit ze^zProbability
Monday27.390.665
Tuesday12.720.245
Friday01.000.090
Sum11.111.000
Divide each exponential by 11.11. Monday is most likely, yet one draw in three would still pick another day.

Generate or check a record?

The model's 0.665 for Monday is a language statistic. Only the carrier record settles the date.

Summary

The whole topic in one minute.

The model scored possible strings. Delivery is an external fact that requires matching the shipment identity to a current record.

Prediction and verification answer different questions. A model can produce the day of the week that fits a sentence while having no access to the delivery schedule. Decide which answers may be generated from context alone and which must be checked against a record.

Sources