Skip to main content

Language Models 101: Predicting the Next Token

Editorial

Introduction

Large language models write code, answer questions and hold long conversations, so it is natural to picture something elaborate inside. The job they are trained to do is short to state:

A language model predicts the next token.

Chat, code and translation all come out of a model that keeps guessing what comes next, one token at a time. Here that picture is built with a model small enough to count by hand, and then with what the large models were measured to do.

You'll learn:

  • the model's one job, and the keyboard suggestion that already does it on your phone;
  • why its answer is a probability for every next word, not one word;
  • how whole paragraphs come from predict, append, repeat;
  • where the apparent understanding comes from, and the measurement that tested it;
  • how to build a next-word model in a few lines of Python and watch it run.

The One Job: Predict What Comes Next

Give a model some text, the prompt, and it answers one question: which token comes next?

Your phone's keyboard does a small version of this when it suggests the next word: one team trained a language model "for the purpose of next-word prediction in a virtual keyboard for smartphones" (Hard and colleagues, 2018). A large language model does the same job with a far larger model, trained on far more text.

A word on token: for now, think of it as roughly a word, or a piece of one. Models work in tokens rather than whole words, and Tokenization: How Text Becomes Numbers (BPE) makes the difference exact. Until then, a token is close enough to a word.

It Outputs a Probability Distribution (Not One Word)

The model does not answer with one word. It gives a probability to every token in its vocabulary, and those probabilities add up to 1. A vocabulary is large: GPT-2's paper says "The vocabulary is expanded to 50,257."

To see a real distribution, a counting model was built from these courses' own text. A trigram model reads the last two words and predicts the third by counting: how often each word followed those two, divided by how often the two appeared. Counted over the prose of the 280 lesson files of the seven AI Engineering courses (613,665 words and punctuation marks, as committed on 14 November 2026, code left out), it had seen the next 329 times, followed by 104 different words.

Three parts. One step: after the words "the next", the lab's trigram model, counted over the 280 AI Engineering lesson files, had seen 329 continuations of 104 different words, and gives each a share by its count: lesson 11.6%, token 10.6%, section 10.0%, step 6.1%, lessons 5.2%, action 2.7%, a full stop 2.4%, thought 2.4%, and the other 96 words 48.9% between them; "lesson" is the most likely. A second step then picks one word: the most likely, or a draw by share. Predict, append, repeat: taking the most likely word each time, "the next" gets "lesson" (11.6%), then a full stop (32.5%), then the end of a text (24.2%), and the loop stops; each picked word is appended and the model reads the last two words again. Under them, what getting the next word right takes when the text is about something: after "2 + 2 =" the next word is "4" (arithmetic), after "the opposite of hot is" it is "cold" (word meaning), after "def add(a, b): return" it is "a + b" (code), and after "and the killer was" only the plot and its logic can say. Every reply is this loop: predict a word, append it, read again.

lesson came 38 times (11.6%), token 35 (10.6%) and section 33 (10.0%). No word holds most of the probability: 48.9% of it is spread over the 96 words outside the top eight.

Then a separate step picks one word: always the most likely one, or a draw that lands on each word as often as its share. Greedy Decoding vs Sampling and Temperature, Top-k & Top-p Explained take that step apart.

A large model gets its probabilities by computing, not counting, but they come out in the same form. Its last layer gives one score to every token in the vocabulary, and a softmax turns the scores into probabilities that add up to 1. The Transformer paper puts it in one sentence: "We also use the usual learned linear transformation and softmax function to convert the decoder output to predicted next-token probabilities." From Logits to Probabilities (Softmax) works through the arithmetic.

This is where the probabilistic behaviour of The AI Engineering Mindset (Build-vs-Buy, Eval-First, Iterate) comes from: the model gives a distribution, and a draw from it can differ from one run to the next, sometimes landing on a word that sounds right and is wrong.

Generation = Predict, Append, Repeat

If the model predicts one token, how does it write a paragraph? It loops. This is autoregressive generation; GPT-3's paper calls its model "an autoregressive language model".

  1. Predict the next token from the text so far.
  2. Append it to the text.
  3. Predict again, from the longer text.
  4. Stop when the model picks an end token, or when the output reaches the length the request allows (Controlling Output: Stop Sequences, Max Tokens, Penalties).

The lab marks where every passage it counted ends, so the end of a text is a word the counting model can predict, as a large model predicts its end token. Taking the most likely word each time, from the next it goes:

  • it reads the next and picks lesson (38 of 329 times, 11.6%);
  • it reads next lesson and picks a full stop (27 of 83, 32.5%);
  • it reads lesson . and picks the end of a text (30 of 124, 24.2%), so the loop stops.

It writes the next lesson ., a phrase these lessons used often.

Two things follow:

  • Generation is sequential. Every token needs a prediction of its own, so a longer answer takes more steps, and more time. Understanding API Pricing (Token Math) shows what the tokens cost.
  • Each step reads the text so far. The counting model reads only the last two words. A large model reads all the text it is given, up to its context window (Tokens, Context Windows & Why They Matter).

See It: Run the Loop

Here is the counting model running. Pick a prompt and press Predict next: the model reads the last two words, its bars show how often each word followed them in the counted lessons, one word is picked and flies into the text, and the loop goes round again. Most likely always takes the top word. Sample draws one by its share, and Draw again runs the same prompt with another draw. Every number in it comes from the lab's counts.

A trigram model counted over the AI Engineering lessons: every next word gets its share, one is picked, and the loop runs again.

Where Does the "Understanding" Come From?

Predicting the next word of real text well takes more than grammar. To continue:

  • 2 + 2 = a model needs arithmetic;
  • the opposite of hot is it needs word meaning;
  • def add(a, b): return it needs code;
  • the last page of a mystery, and the killer was, it needs the plot and its logic.

A trigram has none of that: it can only repeat what followed two words. Large models trained on the same one job showed far more. GPT-2's authors took tasks such as "question answering, machine translation, reading comprehension, and summarization", usually trained one by one on labelled examples, and found that language models "begin to learn these tasks without any explicit supervision when trained on a new dataset of millions of webpages called WebText." GPT-3, given a few examples in its prompt, was measured on sums it had to answer exactly. Its paper reports "100% accuracy on 2 digit addition, 98.9% at 2 digit subtraction, 80.2% at 3 digit addition, and 94.2% at 3-digit subtraction." "Performance decreases as the number of digits increases", the paper adds.

Were those answers looked up from the training text? The authors searched it for the test's 3-digit sums: "Out of 2,000 addition problems we found only 17 matches (0.8%)", which they read as "only a trivial fraction of the correct answers could have been memorized."

No one programmed arithmetic into GPT-3: it was trained only to predict the next token, at scale. That is the phenomenon the rest of the AI Engineering courses build on.

How It Learns This (Self-Supervised Training)

Where do a large model's probabilities come from? From training that needs no human labels: the text labels itself.

  1. Take a passage of training text.
  2. Hide the next token and have the model predict it.
  3. Compare the prediction with the real token, and nudge the model's weights so it would have been a little more right.
  4. Repeat over a very large amount of text.

The answer to every question is the token that came next, so any text can be training data, with no one labelling it. Chip Huyen's book credits the step from language models to large language models to this, "a training approach called self-supervision." The counting model learns the same way in miniature: its whole training is counting what came next. Pretraining: Learning from the Internet covers how much text the large models see, and where it comes from.

See It Yourself: Count the Next Word

You can build the counting model yourself, with no key and nothing to install. Python ships a short text of its own, the Zen of Python, which import this prints. Save this as next_word.py and run python3 next_word.py. It counts what follows every two words of the Zen, prints two distributions, and runs the loop from now is, taking the most likely word each time.

import contextlib
import io
from collections import Counter, defaultdict

with contextlib.redirect_stdout(io.StringIO()):
    import this  # importing it prints the Zen of Python; the print is caught here
zen = "".join(this.d.get(c, c) for c in this.s)  # the Zen's own text

follows = defaultdict(Counter)  # two words -> how often each word came next
for line in zen.splitlines()[2:]:  # the 19 lines under the title
    words = line.lower().replace(".", " .").replace("!", " !").split() + ["<end>"]
    for a, b, nxt in zip(words, words[1:], words[2:]):
        follows[a, b][nxt] += 1


def next_words(a, b):
    seen = follows[a, b]
    total = sum(seen.values())
    print(f'after "{a} {b}", seen {total} times:')
    for word, n in seen.most_common():
        print(f"  {word:<12} {n}/{total} = {n / total:.1%}")


next_words("is", "better")
next_words("better", "than")

text = ["now", "is"]
while text[-1] != "<end>":
    nxt = follows[text[-2], text[-1]].most_common(1)[0][0]  # the most likely word
    text.append(nxt)
print(" ".join(text))

Run on the Mac's own Python 3.9.6 and on Python 3.14, it prints the same:

after "is better", seen 7 times:
  than         7/7 = 100.0%
after "better than", seen 8 times:
  ugly         1/8 = 12.5%
  implicit     1/8 = 12.5%
  complex      1/8 = 12.5%
  complicated  1/8 = 12.5%
  nested       1/8 = 12.5%
  dense        1/8 = 12.5%
  never        1/8 = 12.5%
  *right*      1/8 = 12.5%
now is better than ugly . <end>

Three things to see in it:

  • After is better one word came every time, so the model is certain.
  • After better than eight words are tied at one in eight. Python's documentation for most_common says "Elements with equal counts are ordered in the order first encountered", so the most likely word is the first one counted, ugly.
  • The loop writes now is better than ugly ., a line the Zen never says. Reading only two words, the model forgot now is as soon as it had written better than. A large model reads all the text it is given, so a word written ten words back still counts for the next one.

Hosted models can show you their own probabilities. OpenAI's Responses API returns them when the request asks for message.output_text.logprobs in include, and top_logprobs sets "the maximum number of most likely tokens to return at each token position, each with an associated log probability", from 0 to 20. Check the API reference for the model you call before you rely on it.

Mental-Model Corrections

  • "It's just autocomplete." It is next-word prediction, the keyboard's job. The difference is the size of the model and of the text it learned from: GPT-3's sums above came from that same job, at that size.
  • It doesn't look up facts. It predicts likely tokens. When the likely continuation is not the true one, you get a confident wrong answer; Where Hallucinations Come From follows that, and the RAG & Retrieval Systems course is one answer to it.
  • It keeps no memory between requests. Each prediction is made from the text it is given. A conversation goes on because its earlier turns are given to the model again with each request; Anatomy of an LLM API Call (Messages, Roles, Params) shows how.
  • A token isn't a word. These pages have used the two as one; Tokenization: How Text Becomes Numbers (BPE) makes the difference exact.

Try It Yourself

Six questions on the loop and on where its numbers come from.

Check the loop

1 / 6

Multiple choice

After the next, the counting model had seen 329 continuations, 38 of them lesson. What probability does it give lesson?

Key Takeaways

  • A language model has one job: give every possible next token a probability. A separate step then picks one, the most likely or a draw.
  • Text comes from autoregressive generation: predict, append, repeat, until an end token or a length limit.
  • The counting model here reads two words; a large model reads all the text it is given, and at scale it showed skills nobody wrote in, such as GPT-3's sums.
  • Large models learn by self-supervision: the next token of real text is the label.
  • The same mechanism explains why answers vary, why a confident answer can be wrong, and why the model keeps nothing between requests.

Next: Tokenization: How Text Becomes Numbers (BPE), where a token stops being a stand-in for a word.