The Testing Academy · AI for QA

How a Transformer Predicts
the Next Token

Type "The cat will sit on the ___" and a model will most likely answer mat. This page walks that one sentence through the whole machine, tokens, embeddings, attention, probabilities, in numbers small enough to read, and ends with what next-token prediction means for anyone who tests AI.

One sentence, start to finish Fourteen steps Toy numbers, honest labels The QA angle

Our running sentence is "The cat will sit on the ___." and the model has exactly one job: predict the next token after that final "the". A transformer does this by converting words to numbers, processing the relationships between those numbers, and producing probabilities for possible next words. It does not understand the sentence the way you do; it computes.

TOKEN_

The Next-Token Machine

what actually happens inside a transformer

Type "The cat will sit on the" and the model completes it. Between your text and that one word sit tokens, embeddings, attention, and a probability table over the whole vocabulary. This page walks the full path with one sentence, in numbers small enough to read.

Tokenize

text becomes integer IDs

Embed

IDs look up feature vectors

Attend

tokens read each other

Decode

a decoding rule picks the word

How one token gets predicted

1. Split
Tokenize
[The][cat][will][sit][on][the]

Six tokens, six integer IDs

2. Embed
Look up vectors
cat -> [0.018, -0.246, ...]

Numbers that carry learned features

3. Place
Add position
embedding + position

Cat-chases-dog is not dog-chases-cat

4. Attend
Read the context
softmax(QKᵀ/√d) x V

sit and on pull the most weight

5. Score
Logits to softmax
mat 8.2 -> 36%

Every vocabulary token gets a probability

6. Pick
Decode
greedy or sample + temp

One token out, then loop again

All numbers on this page are simplified teaching examples; real models run thousands of dimensions through many layers.

Next-Token ProbeIllustration

what the stack is holding

tokens: The cat will sit on the6
ids: 791 8415 690 2503 389 2796
dims per token (real models)1000s
attention heads readingmany
layers stackeddozens
vocabulary scoredall

decoding

greedy

temperature

0.0near-deterministic

tokenize › embed › attend › score › pick

The cat will sit on the ___
Probetoy numbers
  • Attention pulled hardest on on (34%) and sit (31%)
  • Final position now expects: a noun, a surface, cat-sized
  • Top scores: mat 36%, floor 20%, chair 10%
  • Greedy pick: mat, then the whole stack runs again

prediction traced to

[1]attend"on" (a surface follows)34%
[2]attend"sit" (the action)31%
[3]attend"cat" (who sits)19%
The cat will sit on the mat

The pipeline, one word each

tokens

text in pieces

ids

pieces as integers

vectors

integers as features

attention

context read in

logits

every token scored

softmax

scores to percents

What this page settles

  • Why 8415 is a label, not a meaning
  • What Query, Key, and Value actually ask
  • Where "mat 36%" comes from, step by step
  • Greedy vs sampling vs temperature, in one table
  • Why generation happens one token at a time
  • Why probable is not the same as true (the QA part)

Quickstart (local)

# 1. get a small model running
ollama pull llama3.2:3b

# 2. at the prompt, watch it complete
ollama run llama3.2:3b "The cat will sit on the"

# 3. then learn to score outputs
pip install deepeval

Why testers should care

Every LLM answer is a draw from a probability table, so identical prompts can differ and fluent can still be false. Once you see the machine, flaky AI features and hallucinations stop being mysteries and start being testable behavior.

14steps walked
7tabs
14diagrams
2decoding modes
1token at a time

The task in one line

The whole pipeline compresses into three moves:

  1. Numbers in. Convert the words into numbers.
  2. Relate. Process the relationships between those numbers.
  3. Probabilities out. Produce a probability for every possible next token.
Textthe sentenceyou typeTokenssplit intopiecesVectorsnumbers withfeaturesAttentioncontext read inProbabilitiesevery tokenscoredNext tokenone word out
The whole pipeline in one line: text in, one probable token out

The fourteen steps at a glance

Here is the full journey from raw text to a chosen token. The IDs and results in this table are simplified teaching examples, not values from any real system; the rest of this guide walks through each step in slow motion.

StepOperationSimplified result
1TokenizationThe, cat, will, sit, on, the
2Token IDs[791, 8415, 690, 2503, 389, 279]
3EmbeddingsEach token becomes a vector of numbers
4Positional informationThe model learns each token's location
5Query, Key, ValueThree vectors per token, from learned matrices
6Self-attentionTokens examine other relevant tokens
7Multi-head attentionSeveral attention calculations run in parallel
8Feed-forward networkProcesses the combined meaning
9Residual connections + layer normalizationKeep information and numbers stable
10Repeat transformer layersRepresentation becomes more contextual
11Output projectionLogits: one raw score per vocabulary token
12SoftmaxScores become probabilities (they sum to 100%)
13DecodingSelect a token (example: mat)
14Continue generationAppend the token, run everything again, one token at a time
Predict one tokenthe full stack runs onceAppend it to the textthe sentence grows by oneRun the whole stackagainfresh pass, freshprobabilitiesStop or keep goinguntil an end tokenone token at a time
Generation is a loop, not a single answer

What this page is not

Why testers should care. "Most probable continuation" is not the same thing as "true statement". Keep that framing and hallucinations stop being mysterious: the mechanism is doing exactly what it was designed to do, which is why evals exist.

Next: the first two steps in slow motion, watching "The cat will sit on the" become six tokens and then six integers, in the Tokens tab.

Before any math can happen, the sentence has to stop being text. Step 1 splits "The cat will sit on the ___." into tokens; step 2 swaps each token for an integer ID. From this point on, the model works only with numbers.

Step 1: split the text into tokens

The tokenizer splits our sentence into six tokens and leaves position 7 empty, because that is the slot the model must fill. The position numbers simply show reading order (like every number on this page, this is the simplified teaching view).

PositionTextToken
1The[The]
2cat[cat]
3will[will]
4sit[sit]
5on[on]
6the[the]
7___Missing: model must predict this

As a plain sequence, the model's working input is:

[The] [cat] [will] [sit] [on] [the]
The cat will sit on the ___one string of textSix tokensThe, cat, will, sit, on, theSix integer IDs791, 8415, 690, 2503, 389, 279
From sentence to numbers in two moves (example IDs)

Step 2: tokens become token IDs

Every token in the model's vocabulary has its own integer ID, so this step is a mechanical lookup. The IDs below are simplified teaching examples, not values taken from any particular tokenizer or model.

  1. Look up. Find each token in the vocabulary.
  2. Replace. Swap the token for its integer ID.
  3. Hand off. Pass the ID list forward so the next step can turn each ID into a vector.
TokenToken ID
The791
cat8415
will690
sit2503
on389
the279

So the sentence the model actually receives is:

[791, 8415, 690, 2503, 389, 279]
What you seeWhole words and spacesPunctuation and capitalsOne readable sentenceMeaning is obvious to youWhat the model seesSubword tokensInteger IDs from a vocabularyNo meaning in the numbers yetMeaning comes later, from embeddingsVS
Same sentence, two views
Watch out. Tokens are not always whole words. Rare or unusual words get split into several pieces, so a sentence can contain more tokens than words.

Next: how each of those six IDs becomes a vector of numbers that can actually carry meaning, in the Embeddings tab.

Step 2 turned the sentence into IDs: [791, 8415, 690, 2503, 389, 279]. But an ID is just a label, the way a defect ID points at a bug without describing it. The number 8415 does not contain the meaning of "cat". The embedding is where the features actually live.

Step 3: token IDs become embeddings

Here is the running sentence, "The cat will sit on the ___.", in a simplified 4-dimensional embedding space. Every value in this table is a simplified teaching example: real models learn thousands of dimensions.

TokenAnimal-relatedAction-relatedLocation-relatedGrammar-related
The0.050.020.040.92
cat0.940.150.100.32
will0.030.400.010.88
sit0.150.960.350.25
on0.020.080.950.61
the0.050.020.040.92

A real embedding does not come with four tidy columns. It looks like this:

cat -> [0.018, -0.246, 0.774, ..., -0.091]   (thousands of numbers)
Grammar-relatedthe, The and will score high in the toy exampleAction-relatedsit scores 0.96 in the toy exampleAnimal-relatedcat scores 0.94 in the toy exampleLocation-relatedon scores 0.95 in the toy example
A toy 4-dimension embedding space; real models learn thousands of unlabeled dimensions

Step 4: add positional information

Embeddings say what a token is, not where it sits. And order changes everything:

"The cat chased the dog."   ->  the cat does the chasing
"The dog chased the cat."   ->  same words, opposite meaning

Position by position, here is what location adds in our sentence. The readings are simplified teaching interpretations, not literal labels inside the model.

PositionTokenWhat the position tells the model
1TheSentence beginning
2catSubject position
3willComes after the subject
4sitThe main action
5onIntroduces a location or surface
6theA noun probably comes next
Spot the twins: in the toy embedding table, "The" and "the" carry identical feature values, yet the model treats them differently: position 1 reads as "sentence beginning" while position 6 reads as "a noun probably comes next". That difference is exactly what this step adds.
Token embeddingwhat the token isPlus positionwhere it sits in the sentenceOrder-aware vectorwhat and where, together
After this step, cat-chases-dog can never equal dog-chases-cat

Every token now knows what it is and where it stands: open the Attention tab to watch those vectors start asking each other for help.

Attention is how the final position asks the rest of the sentence for help. On its own, the last "the" only knows that a noun phrase has started: to set up the prediction it has to pull in who is acting (cat), what the action is (sit), and what kind of word fits the blank.

Step 5: every token gets a Query, a Key, and a Value

VectorPlain-English meaning
Query (Q)"What information am I looking for?"
Key (K)"What type of information do I contain?"
Value (V)"What information should I pass forward?"
Q = Embedding x WQ
K = Embedding x WK
V = Embedding x WV

Conceptually, the Query of the final the behaves like: "I need information that helps identify the noun that should come next."

And here is what each token's Key advertises. Real Keys are vectors of numbers: these paraphrases are simplified teaching examples.

TokenWhat its Key advertises (simplified)
TheSentence beginning and grammar
catThe subject, an animal
willA future construction
sitA sitting action
onA surface or location relationship
theA noun phrase has started
Compare Q with every Khow relevant is eachtoken?Relevance scoresraw numbers, one pertokenSoftmax to percentagesthey now sum to 100%Blend the V vectorsweighted context flows in
One attention pass, seen from the final position

Step 6: self-attention scores the sentence

One formula runs the whole conversation:

Attention(Q, K, V) = softmax(QK^T / sqrt(d)) x V
  1. Compare. Match the current token's Query against every Key in the sentence.
  2. Score. Each comparison produces a relevance score.
  3. Normalize. Softmax converts the scores into percentages that add up to 100%.
  4. Collect. Pull information from the Value vectors, weighted by those percentages.

For the final position in "The cat will sit on the ___.", a simplified attention pattern could look like this. The percentages are teaching examples, not real model weights.

TokenAttention weightWhy it matters
The3%General sentence structure
cat19%Who will be doing the sitting
will5%Future tense
sit31%Defines the action
on34%Signals a surface or location follows
the8%A noun comes next
Total100%Softmax guarantees the weights sum to 100%

Blend the Values with those weights and the final position now holds an idea close to: "An animal is going to sit on a particular surface or object."

Reality check: this step can look like reading comprehension, but the transformer does not understand the sentence the way a human does. It converts words to numbers and processes relationships between those numbers: worth remembering when an LLM's confident output still needs testing.
Grammar headwill + the: a noun should followAction headsit: the noun must suit sittingRelationship headon: the noun is likely a surfaceSubject headcat: the surface should suit a catPhrase headsit on the: common continuations
Multi-head attention: several relationships read in parallel, then combined

Step 7: many heads, one richer picture

The sentence has now been read from several angles at once: the Layers tab shows how repeated transformer blocks refine that blended reading into a prediction-ready vector.

Attention decided where each token should look. The machinery that follows does the refining: a feed-forward network sharpens what each position now knows, residual connections and normalization keep everything intact and stable, and then the whole block repeats, layer after layer.

Step 8: the feed-forward network refines the picture

After attention has gathered context from across the sentence, each token's representation passes through a small network:

linear transformation -> activation -> linear transformation -> improved contextual representation
Condition encoded at the final positionStrength
The next token is probably a nounVery high
It describes a surface or a placeHigh
It is compatible with sittingHigh
It is plausible for a catHigh
The sentence is in future tenseMedium

These strengths are simplified teaching examples: inside the model this is a pattern of numbers, not a labeled checklist.

Multi-head attentionwhere to lookAdd and normalizekeep what you hadFeed-forward networkrefine the meaningAdd and normalizestable numbers outnext layer, dozens of times
One transformer block; the model stacks many of these

Step 9: residual connections and normalization

Two safety rails wrap around attention and the feed-forward network so useful information survives and the numbers stay well behaved:

new representation = old representation + processed information

Put together, one transformer block has this shape:

  1. Input. The token representations enter the block.
  2. Multi-head self-attention. Every token gathers context from the tokens that matter to it.
  3. Add and normalize. The attention output is added to the input, then normalized.
  4. Feed-forward network. Each position gets refined.
  5. Add and normalize. Added back on top and stabilized once more.
  6. Output. A more contextual representation, ready for the next block.

Step 10: repeat through many layers

That block does not run once. It repeats, and a model may stack dozens or even hundreds of these layers, with the representation becoming more contextual at every pass.

Nobody assigns jobs to the layers: the division of labor below emerges from training, and in a real model the boundaries are blurry. Read the table as tendencies, simplified for teaching, not as a spec.
Depth in the stackWhat it tends to learn
Early layersTokens and basic grammar
Middle layersSubject, action, and the relationships between them
Later layersSentence-level meaning and likely continuations
Final layerPreparing next-token scores
Final layerprepare next-token scoresLater layerssentence meaning and continuationsMiddle layerssubject, action, relationshipsEarly layerstokens and basic grammar
What each depth of the stack tends to learn

The stack has done its thinking; the Decoding tab shows how those final numbers become one score per vocabulary token, then a probability table, then the word on your screen.

The stack of layers ends with one score for every token in the model's vocabulary. Decoding is the final stretch: raw scores become probabilities, a selection rule picks one token from the table, and that pick is the word you actually see.

Step 11: the final vector becomes logits

The refined vector at the final position is multiplied by an output matrix, and out comes one raw score, called a logit, for every token the model knows:

final vector x output matrix -> one raw score per vocabulary token (a logit)
Candidate tokenLogit (raw score)
mat8.2
floor7.6
chair6.9
sofa6.5
bed6.1
table4.8
moon0.7
banana-0.5
running-1.2

These logits are simplified teaching numbers; a real model scores every token in its vocabulary in one go.

Final vectorthe last position'ssummaryLogitsone raw score pervocabulary tokenSoftmaxexponentiate andnormalizeProbabilitiesthey sum to 100%
From scores to a probability table over the whole vocabulary

Step 12: softmax turns scores into probabilities

Softmax converts the whole set of logits into a clean probability table:

Probability(token i) = e^(logit i) / sum of e^(all logits)
TokenProbability
mat36%
floor20%
chair10%
sofa7%
bed5%
table1%
Thousands of other tokens (combined)21%
Total100%

Again, simplified teaching numbers: the exact values do not matter, the shape of the table does.

Step 13: pick one token

One probability table, several ways to pick from it. The whole finish in miniature:

  1. Score. Every vocabulary token gets a logit.
  2. Normalize. Softmax turns the logits into a table that sums to 100%.
  3. Select. A decoding rule chooses exactly one token from that table.
TemperatureEffect on the pick
0 or very lowUsually the top token: highly predictable
0.7Balanced mix of predictability and variety
1.0More variation
Above 1More randomness, less predictability

Treat the effect descriptions as simplified rules of thumb for teaching.

Greedy (always the top token):  The cat will sit on the mat
Sampling (one possible run):    The cat will sit on the sofa
Greedy decodingAlways takes the top tokenSame input, same pick, nearly alwaysmat wins at 36%Good for tests and CISampling + temperatureDraws by probabilitySame input can varysofa at 7% is still possibleGood for creative rangeVS
Two ways to pick from the same probability table
Remember this dial when you test LLM features: at temperature 0 the same prompt almost always gives you the same output, which is what you want for repeatable checks and CI (and assert on properties for the rest). Above 0, the same prompt can legitimately return different words, so assert on properties of the answer rather than exact strings.

That is the full journey from prompt to token; the QA angle tab turns it into what this mechanism means for the people who test it.

You now know the machine. Text became tokens, tokens became vectors, attention mixed them, and a probability table picked mat. This last tab is about what that machine means for anyone who has to test it: why generation is a loop, why LLM features feel flaky, and the whole pipeline recapped on one screen.

Step 14: generation is a loop

Picking mat did not finish the job, it produced exactly one token. The selected token is appended, the input becomes "The cat will sit on the mat", and the entire stack you just walked through, tokenization all the way to softmax, runs again from the top on that longer text.

Candidate next tokenProbability (simplified example)
"."65%
and9%
near5%
because2%
all other tokens combined19%

As with every number on this page, these values are simplified teaching examples, not real model output. In pseudocode, the whole generator is a short loop:

while not stopped:
    tokens     = tokenize(text)
    probs      = full_forward_pass(tokens)   # steps 1 to 12
    next_token = pick(probs, temperature)    # step 13
    text       = text + next_token           # append, repeat
Current text inthe prompt so farFull forward passevery layer runsProbability table outthe whole vocabularyscoredPick and append onetokenthe text growsrepeat until stop
The generation loop: one token per cycle, no plan for the whole sentence

Why testers should care

Everything above was mechanics. Read the same story as a tester and each mechanical fact turns into a testing consequence.

Practical rule. Treat an LLM feature as a stochastic dependency, not a pure function. Pin temperature to 0 when you need repeatable pipelines, write property assertions instead of string equality, and back both with an eval suite that scores outputs across a broad set of cases.
Database lookupFetches a stored answerSame query, same rowWrong means missing or staleVerify by checking the sourceNext-token engineComputes a probable continuationSame prompt can varyWrong can still sound fluentVerify with evals, not spot checksVS
Why LLM output needs evals, not just spot checks

The whole pipeline on one screen

The full journey from raw text to the next token, one row per stage. Every numeric value here is a simplified teaching example; real models use thousands of dimensions, billions of parameters, and many transformer layers.

StageInputOperationOutput
Tokenization"The cat will sit on the"split the text into tokensThe, cat, will, sit, on, the
Token IDstokenslook up each token's vocabulary ID[791, 8415, 690, 2503, 389, 279] (example IDs)
Embeddingstoken IDsfetch a learned vector per tokenlists of numbers carrying learned features
Positional informationembeddingscombine each vector with its positionvectors that know what and where
Q, K, Vposition-aware vectorsmultiply by learned matrices WQ, WK, WVthree vectors per token
Self-attentionQ, K, Vsoftmax(QK^T / sqrt(d)) x Vcontext-mixed vector (last token leans on "on" 34%, "sit" 31%, "cat" 19%)
Multi-head attentionthe same vectors, several headsparallel attention runs, results combinedone richer representation
Feed-forward networkattention outputlinear transformation, activation, linear transformationimproved contextual representation
Residual + layer normblock input and outputadd the original back, normalize the numbersstable output with nothing useful lost
Repeat layersone block's outputrun the block again, layer after layerincreasingly contextual representation
Logitsfinal vector at the last positionmultiply by the output matrixone raw score per vocabulary token (mat 8.2, floor 7.6)
Softmaxlogitse^(logit) divided by the sum over all tokensprobabilities summing to 100% (mat 36%, floor 20%)
Decodingprobability tablegreedy pick or temperature-shaped samplingone selected token: mat
Next cycle"The cat will sit on the mat"the whole stack runs againthe next table: "." 65%, and 9%, near 5%

If you keep one line from this page, keep the chain: text -> tokens -> token IDs -> vectors -> attention -> transformer layers -> vocabulary scores -> probabilities -> selected next token. The transformer does not retrieve a fixed answer from a database. Training taught it statistical and structural patterns, roughly "cat" plus "sit on the" points toward mat, floor, chair, sofa, bed, and it calculates which continuation is most probable for the current context.

Where to go from here

A short ladder for a QA reader who wants to turn this theory into day-job skills, in the order that builds best.

  1. Separate the LLM from the agent. A next-token engine on its own only predicts text; an agent wraps it with tools, memory, and goals. See where the line sits in LLM vs AI agent.
  2. Score outputs with evals. Turn "most probable is not always true" into numbers you can gate a release on with the DeepEval masterclass.
  3. Ground answers with RAG. Cut hallucination by letting the model draw from your own documents in the RAG tutorial for QA.
  4. Set up the machine end to end. Build a working local AI testing environment with the AI Tester Blueprint setup guide.
  5. Pick your lane. Work out where a QA background lands among the roles in ML vs AI vs DL engineer.

You have now watched a transformer predict a single token end to end, and you know why testing one is a different sport from testing regular code. The next practical step is to get the machine running on your own laptop: start with the AI Tester Blueprint setup guide.