TL;DR:
An LLM writes one token (roughly, a piece of a word) at a time, then feeds its own output back in and repeats/loops.
Each step produces probabilities for every possible next token. It is not looking up an answer.
Settings like temperature decide how adventurous/creative the pick is.
A hallucination is just a likely-looking token that happens to be wrong. There is no fact-check step anywhere.
You know the trick your phone keyboard does. You type “Happy” and it suggests “birthday”. Your phone has seen you type that a hundred times, so it guesses.
A large language model does exactly the same job: look at the text so far and guess the next piece. The difference is in the scale. Your keyboard looks at the last one or two words. ChatGPT or Claude looks at your entire conversation, and the thing doing the guessing has billions of numbers inside it, tuned on a good chunk of the internet.
When I first understood this, my honest reaction was “That’s it? Then how is it writing working Python code and explaining RAG to me?”
That is what this post is about. I’ll go step by step, and wherever possible I’ll show you real numbers. I ran a small open model, Qwen2.5-0.5B (half a billion parameters, it runs on a normal laptop), and recorded what it actually predicts. The code is at the end if you want to try it yourself.
First, the full picture
Read it top to bottom, seven steps. But the most important thing in this picture is the orange arrow on the left.
After the model picks one token, it sticks that token at the end of your text and runs the whole thing again. Then again. Then again. A 500-word answer is roughly 650 rounds of this loop. There is no moment where the model “plans the whole paragraph” and then writes it out. Every word you see on screen came out of its own separate round.
Keep this picture in mind. The rest of the post is just me zooming into each box.
Step 1: The model doesn’t see words. It sees tokens.
Before anything else, a tokenizer cuts your text into pieces from a fixed list called the vocabulary. Each piece has an ID number, and from here onwards the model only works with those numbers. It never sees letters.
Here is what the real GPT-4o tokenizer does with a few inputs:
A few things worth noticing:
Common English words are one token, and the space before the word is usually part of the token. “ intelligence” with the space is a single piece.
Rare words get chopped up. Thiruvananthapuram, a city in South India, becomes 7 pieces. The vocabulary is built from what appears most often in the training text, so a word the tokenizer has rarely seen gets cut into smaller, common pieces. Even “unbelievable” becomes three, and “tikka masala” becomes four.
Code gets cut into small pieces too. Brackets, commas and names each take their own token.
This is not just trivia. API pricing is per token, and the context window is measured in tokens. Text full of names, rare words or code uses more tokens than plain everyday English of the same length, so it costs more and fills up the model’s memory faster. A rough rule for normal English is 100 tokens for about 75 words.
Why not just use whole words? Because the list would never end: names, typos, new slang, variable names in code. Why not single letters? Because then every sentence becomes very long, and long sequences are expensive to process. Sub-word pieces are the middle path. The most common method for building this vocabulary is called BPE (byte pair encoding): start with raw bytes and keep merging the pairs that occur most often, until you have about 100,000 to 200,000 pieces.
Step 2: Every token ID becomes a list of numbers
For our running example, "The capital of France is", the model gets the IDs [785, 6722, 315, 9625, 374]. (If these don't match the numbers in the figure above, that's expected. Every model family has its own tokenizer and its own numbering. From here on, all IDs come from Qwen's tokenizer, since Qwen is the model we're running.) A number like 9625 means nothing by itself, so the first thing the model does is a lookup.
There is one big table inside the model called the embedding table. In Qwen2.5-0.5B it has 151,936 rows (one per token) and 896 columns. Token 9625 (” France”) means “go to row 9625 and take those 896 numbers”. That’s it. That list of numbers is called the token’s embedding (or vector). The values in the table on the left are the real first few numbers from this model.
Nobody sits and fills these numbers by hand. They are learned during training, and over time, tokens that appear in similar places get pushed towards similar vectors. “Tea”, “chai” and “coffee” all keep showing up after “a cup of”, so they end up as neighbours. It’s like school, where kids who share the same timetable slowly become friends.
The right side of the figure is a 2-D sketch of that idea. The real thing has 896 dimensions, which nobody can draw, but the “similar things stay close” idea holds.
One more detail: the vector for “dog” is the same wherever “dog” appears, so the model also needs to know where each token sits. Position information is mixed in (Qwen and most modern models use a method called RoPE for this). Without it, “dog bites man” and “man bites dog” would look identical to the model.
Step 3: Attention, the part everyone talks about
Here is the problem with Step 2. The vector for “bank” comes from one row of the table, so it is the same vector in every sentence. But “bank” can mean two completely different things:
Attention is how a token updates its own vector by looking at the tokens before it and pulling in information from the ones that matter. After attention, “bank” in the first sentence carries a money flavour and “bank” in the second carries a river flavour.
How does a token decide which earlier tokens matter? For every token, the model makes three new vectors out of its embedding:
Query: what am I looking for?
Key: how do I describe myself to others?
Value: what information will I hand over if someone picks me?
Think of a matrimony site, or a dating app if that’s more your world. Your query is your list of what you’re looking for. Every profile has a short summary, which is the key. The app scores how well your list matches each summary. (Mathematically, this is a dot product of the query and the key. Don’t let the term scare you: multiply the two lists of numbers position by position and add everything up. Lists that point in the same direction get a big score.) It gives every profile a score, softmax turns the scores into weights that add up to 1, and then you take a weighted mix of everyone’s actual details (the values).
So for our sentence, “bank” sends out a query that is roughly “what kind of bank am I?”. The keys of “deposited” and “salary” match it strongly, so their values flow into the vector for “bank”.
Two important details:
A token can only look backwards, never at the tokens after it. In the figure, every line goes from “bank” to an earlier word. This is called causal masking. It makes sense: when the model is generating, the future words don’t exist yet.
There isn’t just one attention. Each layer runs several in parallel, called attention heads (Qwen2.5-0.5B has 14 per layer), each with its own query, key and value weights. Different heads end up tracking different things: one might follow grammar, another might track what “it” refers to.
Step 4: Now do that 24 times
One transformer layer = attention + a small neural network called the feed-forward network. Attention collects information from other tokens; the feed-forward part then processes each token’s vector on its own. A lot of what the model “knows”, like facts and associations, is believed to be stored in these feed-forward weights.
Stack 24 such layers and each layer refines every token’s vector a little more.
The key point is in the orange column. After the last layer, only the vector at the last position is used to predict the next token. By then, that one vector for “is” has soaked up everything relevant from “The capital of France”. All the other columns did their job by feeding information into it.
Step 5: A score for every token, then softmax
That final vector (896 numbers) is multiplied by one more big matrix, and out comes one score for every token in the vocabulary. For this model, that’s 151,936 scores. These raw scores are called logits. Higher means the model likes that token more.
Logits can be any number, positive or negative, so they are converted into probabilities using softmax:
probability of token i = e^(logit_i) / sum of e^(logit_j) over all tokens
The exponent does two jobs. It makes everything positive, and it makes small gaps matter. A difference of just 1 in logit makes one token e^1 ≈ 2.7 times as likely as the other.
Now here is the actual output of the model for “The capital of France is”:
Look closely, because this is my favourite part.
Even for the easiest question in the world, the top answer gets only 32%. Paris wins, but the model is far from sure.
And then look at ranks 2, 3 and 4: blank lines. ______, ____, __. Together they are about 23%. Why would a model want to write a blank line?
Because it has read hundreds of thousands of quiz sheets and exam papers from the internet: “The capital of France is ______. (a) Paris (b) Lyon…”. hahaha. This model was trained only to continue internet text, and for that job, writing a blank is a perfectly reasonable next token. It is not answering your question. It is continuing a document.
Try “The capital of Australia is” and it’s even funnier. The blank line comes first (23%) and Canberra gets only 6.5%. If you let it keep writing, it produces a full multiple-choice question: “______. A. Canberra B. Sydney C. …”
So why does ChatGPT answer directly instead of printing a blank? Chat models start from exactly this kind of “base” model and then get extra training on question-and-answer conversations and human feedback. That teaches them to respond like an assistant. The engine underneath, predicting one token from probabilities, is the same.
Step 6: Picking one token
We have probabilities for 151,936 tokens. Now the model has to choose one.
Greedy decoding always takes the top token. It’s predictable, but it tends to get repetitive and boring.
Sampling rolls a weighted dice: “Paris” gets picked about 32% of the time, the blank line about 11% of the time, and so on. This is why you get a different answer when you hit regenerate.
Three settings control the dice.
Temperature
Before softmax, every logit is divided by the temperature. A low temperature makes the gaps bigger, so the top tokens get even stronger. A high temperature squashes the gaps, so the long tail of strange tokens gets more chances.
Here are real numbers for the prompt “Every morning I drink a cup of hot”:
At 0.2, it’s basically a fight between water and tea, and everything else disappears. At 1.5, “all others” (the long tail of 150,000-odd tokens) jumps to 53%. That means more than half the time, the model picks something weird.
And this is what actually came out when I let the model write 12 tokens at each setting:
At 1.5, it falls apart completely. The words are real, but the sentence makes no sense.
Top-k and top-p
These two cut off the tail before the dice is rolled.
Top-k = 3 keeps only the 3 best tokens: water, tea and chocolate.
Top-p = 0.9 keeps the smallest group of tokens that together cross 90%. Here that’s 6 tokens. When the model is confident, this group is small; when it’s unsure, the group grows. That is why top-p is usually preferred.
The kept tokens are re-scaled to add up to 100%, and one is sampled.
Poor “chai” sits at 0.33%, so with top-p 0.9 it never gets picked. As someone who drinks chai every single day, I take this personally.
Practical rule of thumb: for code, JSON or data extraction, where you want the same correct answer every time, use temperature 0 to 0.3. For brainstorming or writing, use 0.7 to 1.0. Above that is rarely useful.
Step 7: Round and round, one token at a time
Here is a real greedy run, round by round. Watch the text grow on the left:
Every round, the full text goes back in and exactly one new token comes out.
The loop stops when the model produces a special end-of-text token, hits the maximum token limit, or produces a stop sequence you configured.
Now look at the highlighted round 6.
After “It is the”, the model’s top choices were “largest” (19.4%), “seat” (19.1%) and “capital” (14.9%). “Seat” would have led somewhere true, like “the seat of the French government”. But greedy decoding took “largest”, winning by just 0.3 points. Once “largest” is in the text, the model has to stay consistent with it: “largest” → “city” (74.5%) → “in” (78.5%) → “Europe” (53.5%). Each step looks very confident.
The result is “Paris. It is the largest city in Europe”, which is wrong. Moscow, Istanbul and London are all bigger.
This is what a hallucination is, mechanically. The model was not lying, and it did not “forget” anything. There is simply no fact-checking step anywhere in the loop. There’s only “which token looks likely here?”. A confident-sounding sentence got built on top of a near coin toss.
Bigger models make this kind of mistake less often because their probabilities are sharper and better calibrated, not because they started checking facts. This is also why RAG helps: when you paste the right paragraph into the prompt, attention can copy from it, and the correct token gets a much higher probability.
Step 8: Where do these probabilities come from?
All the numbers we saw come from the model’s weights. So how did the weights get these values?
Training is fill in the blanks, like the exercise every one of us did in school, except the model does it trillions of times.
Take a sentence from the training data. Hide the next token. Let the model guess. In the figure, the model’s favourite guess was “Asia”, which is wrong. That’s normal early in training, and it’s exactly what the next part fixes. Compare its guess with the real answer and compute the loss (the negative log of the probability it gave to the correct token). If it gave “Japan” 30%, the loss is 1.20. If it gave 90%, the loss is only 0.11. Then backpropagation works out, for every one of the ~500 million weights, which small change would reduce that loss, and nudges each weight a tiny bit in that direction.
Repeat this for every position of every sentence. Qwen2.5 was trained on about 18 trillion tokens.
Nobody writes a rule like “capitals of countries”. The model ends up knowing facts because knowing facts reduces the loss. Grammar too. Even some reasoning patterns, because predicting the next line of a worked-out maths solution needs some of that reasoning.
So what does this change in how you use LLMs?
Once you see the loop, a lot of everyday behaviour makes sense:
Same prompt, different answer? That’s sampling. If you need repeatable output, set the temperature to 0.
Confidently wrong facts? The model picks likely tokens; it doesn’t look facts up. Put the facts in the prompt (RAG), or ask it to quote its source.
Bill higher than you expected? You pay per token, not per word. Long names, rare words and code take more tokens. Run your prompts through the tokenizer before you budget.
“Think step by step” helps? Every token gets the same fixed amount of computation. When the model writes out intermediate steps, it gets more rounds to work with, and each later token can attend to the earlier reasoning. That’s the basic idea behind today’s “reasoning” models too.
Every word in your prompt matters. Every token you add changes the attention, which changes every probability downstream.
Try it yourself
This is roughly the code I used to get the numbers above. It runs on a laptop CPU in a few seconds after the first download (about 1 GB).
# pip install torch transformers
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
name = "Qwen/Qwen2.5-0.5B"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, dtype=torch.float32)
prompt = "The capital of France is"
ids = tok(prompt, return_tensors="pt").input_ids
with torch.no_grad():
logits = model(ids).logits[0, -1] # scores for the LAST position only
probs = torch.softmax(logits, dim=-1)
top = torch.topk(probs, 10)
for p, i in zip(top.values, top.indices):
print(f"{tok.decode([int(i)])!r:15} {float(logits[i]):6.2f} {float(p)*100:5.2f}%")
Change the prompt, and try dividing logits by a temperature before the softmax. Spend ten minutes with this and the whole idea clicks much better than any blog, including this one.
It still amazes me that this simple loop, guessing one token, adding it and guessing again, produces everything we get from these models. But at least now, when it tells me Paris is the largest city in Europe, I know exactly which round it went wrong in.













the phone keyboard analogy finally made this click for me. does temperature basically just flatten those suggestions?