Inside the Brain of an LLM: How Transformers Predict the Next Token
1. The pizza is ready. But how did the machine know?
The oven beeps.
You pull the door open, inhale the scent of melted mozzarella and toasted crust, and call across the room:
“The pizza is ready to…”
You probably finished that sentence in your mind before your eyes even reached this line.
Eat.
Nobody handed you a multiple-choice quiz.
Nobody stopped to give you a dictionary definition of dough or cheese. The unfinished sentence was all your mind needed.
Now picture a computer doing the exact same thing.
A computer has no mouth.
It has never tasted crispy crust. It has no stomach, no appetite, and no memory of a warm kitchen. It is just a box of metal, silicon chips, and electricity.
Yet when you feed it the words “The pizza is ready to…”, it calmly writes back: “eat.”
How can a machine that only understands numbers produce something that feels so human, so natural, and so immediate?
In the previous chapter, we crossed the first bridge: words are broken into tiny puzzle pieces called tokens, and each token is looked up in a digital dictionary to get a list of numbers called an embedding.
A token ID identifies the token.
An embedding is the learned numerical representation looked up using that ID. To recall the simpler vector idea, imagine a hand-written description:
For example, if you wanted to describe a slice of pizza to a computer using three scores, you might write:
Sweetness: 1
Cheesiness: 9
Crunchiness: 8
That row of numbers—[1, 9, 8]—is what computer scientists call a vector. Here it is a list of hand-chosen measurements. A real token embedding is also a vector, but its entries are learned—not scores we label sweetness, cheesiness, and crunchiness.
Giving numbers to a computer is only the starting line.
Today, we follow those numbers through the machinery that produces the next-token prediction. For readability, we will often draw whole words as single token cards; an actual tokenizer may split them differently.

2. Opening the mysterious box: What is an AI factory?
Before we look under the hood, let’s unpack the three letters in GPT:
G — Generative: It generates a continuation one token at a time. Tokens can be whole words, word pieces, punctuation, or other tokenizer-defined units.
P — Pre-trained: It learned patterns during an earlier training stage, before you type your question. The training data and duration depend on the model.
T — Transformer: The blueprint of the digital factory that processes the words.
To understand how this factory works, we need to understand three everyday words that AI engineers use all the time: neural networks, parameters, and layers.
What is a neural network?
Despite the science-fiction name, a neural network is not a human brain in a glass jar. It is an organized assembly line of math problems—including matrix multiplications, additions, and nonlinear transformations. Numbers enter one side, get calculated along the way, and new numbers come out the other side.
What are parameters?
Imagine a giant sound mixing board with millions of volume sliders and knobs. In an AI model, those adjustable numbers are called parameters. Weights are one kind; biases and normalization settings can also be parameters. Many weights begin randomly, while some other settings start at zero or one.
Training adjusts the numbers to reduce prediction errors.
What is a layer?
Think of baking in a bakery:
Station 1: Measures and mixes the flour and yeast.
Station 2: Kneads the dough.
Station 3: Bakes the loaves in the oven.
Station 4: Packages the bread in paper bags.
Each station has one clear job. In a neural network, each station is called a layer.
A single layer takes in numbers, performs one specific step of calculation, and hands the updated numbers to the next layer down the line. When you put several layers together, one after another, you get a deep network.
The Transformer was introduced in the 2017 paper Attention Is All You Need. Earlier sequence models commonly used RNNs and LSTMs, whose recurrent calculations depended on previous steps. Imagine a worker passing a running notebook from one word to the next.
The Transformer removed that recurrent dependency within its attention-based layers, allowing much more work across token positions to happen in parallel during training. Attention itself already existed; this new architecture made it central.
Parallel processing does not mean a text-generating model may peek at future answers. We will meet the rule that prevents that shortly.
Our factory tour follows GPT-2 Small, a published, inspectable example. Other models can use different position methods, normalization, and feed-forward designs. Gemini, Claude, and Grok are separate model families, not names for OpenAI’s GPT models.
Now, let's step inside this factory and follow our sentence—“The pizza is ready to…”—from the moment it arrives at the front door.


3. A word arrives with numbers—but it still needs a seat number
Look at these two sentences:
The dog chased the boy.
The boy chased the dog.
Both sentences contain the exact same words. Yet for the boy, sentence number one is a terrifying afternoon, while sentence number two is a fun game of tag in the backyard.
In our AI factory, each word enters as a vector—a list of numbers describing what the word means. But if you only look at word meanings, both sentences look identical, like throwing letter tiles into a soup bowl. The computer would have no idea who ran after whom!
A computer needs to know where each word is sitting.
In our GPT-2 example, order is represented using learned Position Embeddings. Think of it like giving each word a ticket with a seat number stamped on it.
When the word arrives, the computer adds the seat ticket directly to the word card:
Token embedding (boy): [ 0.4, -0.2, 0.7 ]
Seat ticket (Seat number 1):+ [ 0.1, 0.3, 0.2 ]
----------------------------------------------------
Combined card: = [ 0.5, 0.1, 0.9 ]
The numbers are added together one by one. In real models, these cards can contain hundreds or thousands of numbers, but the logic is simple: Word identity + Seat position = Position-aware word card.
Now every word has an identity and knows its place in line. But words still face a big problem: on their own, words can be confusing chameleons.


4. A bank is not always a bank: Why words need context
Imagine your phone buzzes with this text message:
“Meet me near the bank.”
You freeze with your coat in your hand. Which bank?
A moment later, another message arrives:
“Bring your checkbook and deposit slip.”
Instantly, the word “bank” snaps into clear focus: a brick building with tellers, vaults, and money.
Now imagine if the follow-up text had been:
“Bring fishing rods and a picnic blanket. We’ll sit by the water.”
The exact same four letters, “bank,” now mean the grassy, muddy edge of a flowing river.
Words change their meaning based on who is standing next to them. If a computer only looks at a word in isolation, it will constantly guess wrong.
Consider another sentence:
“The cat sat on the mat because it was tired.”
As a human, you know immediately that “it” refers to the cat, because mats don't get tired. But if the sentence ended with “because it was soft,” you would probably interpret “it” as referring to the mat.
Some sentences remain ambiguous, and a model can still interpret them incorrectly.
The words need a way to talk to each other, compare notes, and update their cards based on context.
That conversation between words is the beating heart of the Transformer. It is called Self-Attention.

5. Three versions of the same word: Query, Key, and Value
How can words talk to each other without creating a chaotic shouting match?
Imagine you are standing in a crowded school cafeteria at lunchtime:
You have a craving in mind: “I want something hot and cheesy.”
Each food stall has a sign hanging above the counter: “Fresh Salads,” “Spicy Noodles,” “Wood-Fired Pizza.”
When your craving matches a stall's sign, you walk up and receive your lunch: A warm slice of pizza.
In the Transformer, each token representation is transformed into vectors with three distinct roles:
Role | Cafeteria Analogy | What It Does in the Model |
|---|---|---|
Query (Q) | What you are looking for | A search vector asking: "Which other words are relevant to me?" |
Key (K) | The sign above the stall | A label vector saying: "Here is the kind of information I have." |
Value (V) | The food you take home | The actual content packaged up to be shared with other words. |
When a word arrives, the computer multiplies its numbers by three separate sets of learned knobs to create its Query, its Key, and its Value.
The same incoming representation produces three learned numerical views: Query, Key, and Value.


Now let’s watch the five-step attention process unfold in real time, using a deliberately invented numerical example for our sentence:
“The pizza is ready”
Imagine you are the fourth word: “ready”.
On your own, you are just a generic adjective. Ready for what? Ready for a sprint? Ready for a flight? Ready to explode? You have no idea what you are preparing for! You desperately need context from the earlier words in the sentence: “The”, “pizza”, and “is”.
Here is how one illustrative attention head at “ready” gathers an update. The scores below are invented to explain the calculation, not measured from GPT-2. Q, K, and V are numerical vectors; the sticky-note descriptions are analogies.
Step 1: Compare (The Search)
The word “ready” pulls out its Query card. Think of this Query like a question written on a sticky note:
“I am the state of being prepared... but WHO or WHAT is prepared?”
It holds this sticky note up against the Key cards of every word in the sentence to see who has an answer:
“The” shows its Key: “I am just a tiny grammatical pointer word.”
──► Match score: 2 (very low connection).“pizza” shows its Key: “I am a hot, baked food noun fresh out of the oven!”
──► Match score: 24 (MASSIVE connection! This is exactly what “ready” is searching for).“is” shows its Key: “I am a present-tense linking verb connecting subjects.”
──► Match score: 6 (mild connection).“ready” shows its own Key: “I am the state of readiness itself.”
──► Match score: 8 (keeps a healthy link to its own meaning).
In math, this comparison is done by multiplying the numbers together (called a dot product). A higher score means a stronger match.
Step 2: Scale down (The Volume Limiter)
Look at those raw match scores: [2, 24, 6, 8].
The score for “pizza” is 24! In real AI models where vectors have 64 or 128 numbers, multiplying them can produce scores in the hundreds.
If one score is much larger than the others, softmax can assign almost all the weight to that position, leaving very little room for other contributions. It’s like turning a microphone so loud that everyone’s voice turns into distorted screeching.
To keep the math calm, the computer divides all scores by a scaling factor: the square root of the key size, written as sqrt(d_k).
If the key vector size is 16 numbers wide, its square root is 4. So we divide every score by 4:
2 / 4 = 0.524 / 4 = 6.06 / 4 = 1.58 / 4 = 2.0
Scaling helps prevent very large dot products from making softmax excessively concentrated and its gradients very small. It does not guarantee balanced weights: 6.0 is still much larger than 0.5.
Step 3: Mask (The Privacy Blinders)
Are there any future words in front of “ready” that it shouldn't see?
Not right now—words 1 through 4 are all in the past or present, so all four are allowed. (In the very next section, we’ll see how future words get blocked so the model can't cheat).
Step 4: Turn into weights (Softmax)
Next, the computer passes those scaled scores through Softmax.
Softmax turns raw numbers into positive percentages that add up to exactly 100%:
For our scaled scores [0.5, 6.0, 1.5, 2.0], the approximate weights are:
Position | Attention weight |
|---|---|
The | 0.40% |
pizza | 96.76% |
is | 1.07% |
ready | 1.77% |
Total | 100.00% |
Step 5: Blend the values (Packing the New Lunch Tray)
Now “ready” collects a weighted mixture of the Value vectors:
Attention update ≈
0.0040 × V(The) + 0.9676 × V(pizza)
+ 0.0107 × V(is) + 0.0177 × V(ready)
Use the unrounded weights for an exact calculation. The output is another vector—not the word “eat” yet.
In this invented head, the pizza position contributes most strongly to the mixture. That does not mean the whole representation is “96.76% pizza meaning.” The Values are learned vectors, other heads contribute their own mixtures, and the original representation is added back later.
Our cafeteria analogy has done its job: it shows weighted information gathering. We should not mistake the lunch tray for a conscious thought or a guarantee that ambiguity has been solved.


And look at the famous formula from the 2017 research paper again:
Attention(Q, K, V) = softmax( (Q × K_transpose) / sqrt(d_k) + mask ) × V
It doesn’t look like intimidating alien math anymore, does it? You can read it as five simple human actions:
Q × K_transpose: Compare questions against signs (Step 1)./ sqrt(d_k): Turn down the volume so big scores don't crackle (Step 2).+ mask: Put on blinders so you can't peek at future words (Step 3).softmax(...): Turn the scores into percentages that sum to 100% (Step 4).× V: Fill your lunch tray with those percentages of each word's food (Step 5).
6. The model must not peek at the answer: The Causal Mask
Imagine you are in classroom taking a reading test:
“The pizza is ready to ___”
If the teacher accidentally printed the answer key right on the bottom of the page, you wouldn't need to think; you could just peek ahead. The test would be completely pointless.
When an AI model is being trained to predict the next word, it faces the exact same temptation. For example, the representation at “to” is used to predict “eat”. If it could already read “eat”, the training task would leak its own answer.
To prevent cheating, GPT models use Causal Self-Attention.
"Causal" simply means that time only moves in one direction: a word can only look at itself and words that came before it. Future words are locked behind an opaque privacy curtain.
Let’s pretend our sentence is four words long and look at the permission rules:
Looking Word (Query) | The | pizza | is | ready |
|---|---|---|---|---|
The | Allowed | Blocked | Blocked | Blocked |
pizza | Allowed | Allowed | Blocked | Blocked |
is | Allowed | Allowed | Allowed | Blocked |
ready | Allowed | Allowed | Allowed | Allowed |
Look at the pattern: the permitted cells form a lower triangle.
Every blocked cell is given a score of negative infinity before the percentages are calculated. In math, an exponential score of negative infinity turns into 0%. That future word receives zero attention, making it completely invisible.
During training, this triangular curtain allows the computer to compute many token positions in parallel on graphics cards without letting any word cheat by looking ahead.
A Subtle Detail: In the sentence “I sat on the bank of the river,” the early word “bank” cannot look forward to see “river”. But when the model reaches the later word “river”, “river” can look back and see both “bank” and itself. The rich understanding builds up steadily as the sentence moves forward.


7. Several pairs of eyes: Multi-Head Attention
When you read a story, you pay attention to several different things at the same time:
Grammar: Is this sentence in the past tense or future tense?
Relationships: Who does the word “she” or “it” refer to?
Emotion: Is the speaker angry, excited, or joking?
If you tried to track grammar, character clues, and emotional tone with only one pair of eyes, your brain would quickly get overwhelmed.
In a Transformer, this is solved with Multi-Head Attention.
Instead of calculating attention just once, the model uses different learned projections to create several attention views called heads (for example, 12 separate heads in GPT-2 Small).
Different attention heads → concatenate their outputs → learned output projection.
Each head uses its own learned projections. Heads can develop different patterns, but nobody assigns permanent job titles such as “grammar” or “emotion”. Possible patterns include:
One head might track words right next to each other (like “hot” and “pizza”).
Another head might connect pronouns to names across long distances.
A third head might track sentence structure and question marks.
After each head finishes its work:
All heads turn in their notes.
Their output vectors are glued together side by side (concatenated).
A final layer of learned knobs blends all those notes back into a single, polished representation.
Now the full technical name makes complete sense:
Multi-head: Several teams looking at the sentence in parallel.
Causal: A strict rule that prevents peeking at future words.
Self-attention: Words in the same sentence comparing notes with each other.

8. Don't lose your original thoughts: Residual Connections
After you finish listening to everyone’s notes in a group project, do you throw away your original thoughts?
Of course not! If you erased your memory every time you heard someone else speak, you would lose track of who you are and what you were doing.
In deep neural networks, this problem is solved with a Residual Connection (also called a skip connection).
Instead of replacing the old card with the new attention notes, the computer adds the new notes directly onto the original card:
Output = Original Card + New Attention Notes
Here is a simple three-number example:
Original card: [ 1.0, 2.0, 3.0 ]
New attention notes: + [ 0.2, 0.7, 0.1 ]
--------------------------------------------------
Result after addition: = [ 1.2, 2.7, 3.1 ]
Notice that both rows must have the exact same length. You cannot add a three-number card to a two-number card.
Residual connections give the network two superpowers:
Adding an Update: The incoming representation has a direct route to the result instead of being completely replaced. This does not guarantee that its original meaning stays unchanged.
Learning Superhighways: During training, feedback signals (called gradients) can travel backward directly along the addition highway which helps deep networks train. It does not guarantee that gradients can never become too small or too large.


9. The volume control: Layer Normalization
If you keep adding numbers together over and over through 12, 24, or 96 layers, what happens to the math?
Repeated transformations can make numerical scales harder to manage. We want the next station to receive representations at a useful scale.
To keep the numbers well-behaved, the Transformer uses Layer Normalization (or LayerNorm).
Think of LayerNorm like an automatic volume control on a television:
If a movie scene is a whisper, it gently raises the sound so you can hear it.
If an explosion happens, it brings the volume down so it doesn't hurt your ears.
The dialogue doesn't change, but the volume stays in a safe, comfortable zone.
For each token, LayerNorm uses the mean and variance across its features, normalizes with a small numerical stabilizer, then applies learned scale and shift settings. The final output need not have exactly zero mean or unit variance. It keeps the same vector length and does not produce probabilities.
The vector enters LayerNorm and leaves with the same number of features, transformed using normalized statistics and learned scale/shift.
In GPT-2, LayerNorm is applied before attention and before the feed-forward network. This keeps the numbers calm and steady throughout the entire journey.

10. Thinking quietly at your desk: The Feed-Forward Network (FFN)
Now we arrive at an essential question:
We already let the words talk to each other through Attention. Why do we need another network right after it?
Think back to school:
Attention is a group discussion. All the students gather around a table, talk to each other, and exchange ideas.
But after the meeting ends, each student has to sit down alone at their own desk to work through the notes they collected.
The model is not storing new facts in its trained weights during this step. That private desk work is performed by the Feed-Forward Network (FFN), sometimes called an MLP (Multilayer Perceptron).
While attention passes information between words, the FFN transforms each token’s representation separately. “Thinking at a desk” is only our analogy. Every word passes through the exact same network at its own desk, without looking at its neighbors.
Each token position goes through the same FFN separately. The weights are shared across positions within that layer.
Inside the FFN, the word's card goes through three steps:
Expand: The list of numbers is stretched to four times wider (in GPT-2, from 768 numbers to 3,072 numbers). Expanding the width gives the network extra scratchpad space to combine facts and patterns.
The Nonlinear Curve (GELU): The numbers pass through a mathematical curve called GELU. Straight linear math can only stretch and rotate lines. Nonlinearity lets the network represent patterns that stacked linear transformations alone could not express. GELU is a mathematical operation, not permission to bend rules.
Compress: The card is squeezed back down to its standard size (768 numbers).
Once the desk work is finished, the result is added back onto the card using another residual connection!
The Big Takeaway:
Attention gathers information from the rest of the sentence. - The FFN transforms each position using learned parameters and the context already gathered.

11. Stacking the floors: The Transformer Block
We now have all the ingredients to build one complete Transformer Block:
Keep the input on a skip path while attention computes its update; add them. Then repeat the pattern with the FFN.
In code, this entire block is written in two clear lines:
a = x + Attention(LayerNorm(x))
output = a + FFN(LayerNorm(a))
Why do we stack multiple blocks?
A single block is only one step of thinking. To understand complex human ideas, the model stacks these blocks into a multi-story tower:
Each block receives the previous block’s updated representations and applies its own learned transformations. Later blocks can build on earlier computations, but we cannot label exact floor ranges “spelling”, “grammar”, and “knowledge” as universal facts.
GPT-2 Small has 12 blocks. Layer counts in other models vary; this chapter does not assume unpublished details of current chatbots.
As our word card travels up through floor after floor, it becomes richer, deeper, and more insightful.

12. From numbers to real words: Logits and Softmax
Our sentence has reached the top floor of the tower:
“The pizza is ready to…”
In our GPT-2 Small example, all input token positions have traveled through 12 blocks, followed by final LayerNorm. Because we want to know what comes next, we look at the word sitting at the very end of the line: the word “to”.
Its card is now packed with deep understanding about pizza, ovens, readiness, and English grammar. But it is still just a list of 768 numbers. How does that list become a word you can read?
The model passes this final card through one last station called the Vocabulary Projection.
This station holds a giant digital dictionary of all 50,257 possible tokens in the model’s vocabulary. It calculates a raw score for every token in that vocabulary, measuring how well it fits as the next word.
These raw scores are called logits.
Final hidden representation → vocabulary projection → one logit per vocabulary token.
Logits are raw scores. They can be positive, negative, or zero, and they don't add up to anything specific.
To turn raw scores into percentages, the computer applies Softmax:
It takes the exponential of each score (turning negative numbers into positive numbers).
It divides each exponentiated score by the sum of all exponentiated scores.
Now, all scores become neat probabilities that add up to exactly 100%.
Let’s temporarily shrink the vocabulary to four candidates. These are invented scores—not GPT-2 measurements. In the real model, softmax uses the entire vocabulary:
Candidate Word | Raw Logit Score | Exponential Score | Probability Percentage |
|---|---|---|---|
eat | 2.0 | 7.389 | 64.39% |
serve | 1.0 | 2.718 | 23.69% |
cool | 0.0 | 1.000 | 8.71% |
dance | -1.0 | 0.368 | 3.21% |
Total | — | 11.475 | 100.00% |
(Math check: 7.389 / 11.475 = 0.6439, which is 64.39%. The displayed values are rounded; the underlying softmax calculation uses full precision.)
An Essential Truth: A 64.39% probability does not mean the pizza is legally guaranteed to be eaten. It is the model’s assigned probability for that token under the current context, not a direct count of matching sentences in its training data. A likely continuation can still be factually wrong.

13. Picking the winner: How the model chooses
Now that the computer has a probability table, how does it pick the word?
There are two main strategies:
1. Greedy Choice (Argmax)
Always pick the word with the highest percentage.
In our example, it would pick “eat” every single time. While fast and logical, picking the top word every time can make long stories sound stiff, repetitive, and robotic.
2. Rolling the Dice (Sampling with Temperature and Top-K)
Instead of always picking number one, the model rolls a weighted dice.
Temperature: A positive setting that scales logits before sampling. Lower values concentrate the distribution; higher values spread it out.
Low Temperature (e.g., 0.2): Sharpens the differences. The highest-scoring candidates receive more of the probability. Sampling becomes more concentrated. This does not guarantee factual accuracy.
Higher Temperature (e.g., 1.2 compared with 1.0): Flattens the differences. Lower-scoring candidates get a larger share, making the writing varied and creative.
Top-K Filtering: Keeps the k highest-scoring token candidates, then renormalizes their probabilities. The value of k is configurable. It ranks scores, not objective sensibility; with four candidates and k = 2, only “eat” and “serve” remain in our example.
Once the word is chosen (let's say “eat”), what happens next?
The computer appends the new word to the end of the sentence:
“The pizza is ready to eat”
Then it predicts another token conditioned on the updated context: perhaps punctuation or a continuation. A simple implementation can rerun the context. Efficient serving often reuses earlier keys and values in a KV cache, avoiding full recomputation of every earlier token at each step.
This loop repeats over and over until the model outputs a special End-of-Text token or reaches a length limit. That is why this process is called autoregressive generation.

14. Where did the smarts come from? Training vs. Chatting
If you built this entire machine today and turned it on without training, it would output complete gibberish:
“The pizza is ready to purple rocket bubble.”
How did it learn that pizza is something you eat?
Through Self-Supervised Pre-Training.
The model trains on token sequences from a dataset whose size and contents depend on the training run:
It receives text with each prediction position restricted to its preceding context.
It produces next-token distributions at many positions.
The training objective uses the actual next tokens as targets.
It calculates its mistake (called the loss).
Backpropagation computes gradients through the layers; an optimizer uses them to update parameters. The aim is to reduce loss across training examples, not guarantee that every individual prediction improves after every update.
Repeat that process across many training batches, and the knobs gradually align to reflect the patterns, grammar, and knowledge of human language.
A Critical Difference: Knobs vs. Scratchpad
Parameters (Weights): The learned knob settings saved in the model file on your hard drive. During ordinary inference, these settings are held fixed. A later training or fine-tuning run can update them.
Activations: The temporary scratchpad numbers calculated while processing your specific sentence. Their lifetime depends on the implementation; some are discarded while others, such as cached keys and values, may be retained for later generation steps.
When you chat with an AI model today, ordinary inference does not update the model’s parameters. It is simply running your words through its frozen dials.

15. 300 lines of code vs. 124 million numbers
When people hear about artificial intelligence, they often imagine millions of lines of mysterious programming code.
The reality is surprising: the actual code defining a Transformer model is remarkably short.
In Andrej Karpathy’s open-source nanoGPT repository, the core model definition in model.py is only about 300 lines of Python code.
In those 300 lines, you will find the exact pieces we walked through:
CausalSelfAttention: The Query, Key, Value calculations and the triangular privacy mask.MLP: The desk work with 4x feature expansion and GELU curve.Block: The floor combining LayerNorm, Attention, Residual additions, and MLP.GPT: The tower stacking the blocks and running the final vocabulary projection.
The 300 lines of code are just the building plan. The true capability comes from the 124 million parameters (in GPT-2 Small) with a chosen configuration and training run. Larger published models can have many more parameters, but code length alone does not measure their capability.
nanoGPT is an implementation, not a single fixed tiny model. It can run small experiments or GPT-2-sized configurations. A small program can create a vast digital architecture.

16. Back to the oven
The oven beeps. You call out:
“The pizza is ready to…”
At the beginning of this chapter, the computer’s ability to finish that thought felt like magic.
Now you can trace the entire journey with your own eyes:
Prepare: text → tokens → token embeddings plus position embeddings.
Transform: repeated GPT-2-style blocks → final LayerNorm.
Predict: vocabulary projection → logits → softmax → token selection.
Continue: append the chosen token and predict again.
The selected token for “eat” is added to the context, and the cycle begins again.
There is no conscious chef living inside the silicon chip, no mouth, and no hunger. But through the harmonious dance of embeddings, attention, residual highways, normalization, and probability, mathematics produces something that reads like natural human thought.
The next time an answer appears on your screen, you will know the quiet clockwork running behind each generated token.

Snapshot: The Whole Chapter in One Place
Term | What It Actually Is | The Simple Mental Picture |
|---|---|---|
GPT | Generative Pre-trained Transformer | An AI trained on text to predict the next token in line. |
Token | A word, word piece, or punctuation mark | A standardized puzzle piece of language. |
Embedding | Learned vector looked up using token identity | The starting numerical card; not the token ID itself. |
Vector | An ordered list of numbers; traits are one illustration | A digital ID card of measurements. |
Position Embedding | A learned position vector added to token embeddings in GPT-2 | A seat number pinned to each word's jersey. |
Self-Attention | Q/K comparisons produce weights that mix V vectors | A group meeting where words look around to update notes. |
Query (Q) | A learned vector used to compare with keys | What you are craving at the cafeteria. |
Key (K) | A learned vector compared with queries | The sign hanging above a food stall. |
Value (V) | The actual information packaged to share | The plate of food you carry to your table. |
Causal Mask | A triangular mask blocking future words | Taking a test without being allowed to peek at answers. |
Multi-Head Attention | Multiple parallel attention teams | Several pairs of eyes looking at grammar, tone, and clues. |
Residual Connection | Adding the layer input directly to its output | Keeping your original notes and writing new clues on top. |
LayerNorm | Rescaling numbers across features per word | An analogy for adjusting feature scale before processing. |
Feed-Forward (FFN) | Position-wise learned transformation; GPT-2 uses 4x expansion and GELU | Each student sitting at their desk to digest what they heard. |
Transformer Block | Two pre-LN sublayers: attention and FFN, each with residual addition | One complete floor in the multi-story thinking tower. |
Logits | Raw scores for every vocabulary token | A preliminary tally of votes before turning into percentages. |
Softmax | Turns logits into positive percentages summing to 100% | Converting votes into clear, official percentages. |
Temperature | A positive logit-scaling setting before sampling | A knob between strict predictability and creative flair. |
Autoregressive Loop | Appending the chosen token and predicting again | Weaving a sweater, one stitch at a time. |
Parameters | Learned knobs frozen during inference | The tuning held fixed during ordinary inference. |
Activations | Input-dependent intermediate numbers; some may be cached | Working notes; some may be cached for later steps. |
Keep these distinctions together: Attention weights describe how Value vectors are mixed; output probabilities describe candidate next tokens. The causal triangle is imposed by a mask, while the weights within it depend on the input and learned projections.
GPT-2 Small’s 12 blocks, 768 features, 4× FFN expansion, and learned position embeddings are example-specific. A probable token can be wrong, and sampling settings do not guarantee truth.
Sources and Recommended Reading
The analogies, toy vectors, and cafeteria examples in this chapter are designed for intuitive education. The walkthrough follows GPT-2-style implementations and the sources below. All toy attention scores and four-candidate output probabilities are illustrative, not model measurements:
Vaswani, A., et al. (2017). Attention Is All You Need. NeurIPS 2017. (The original paper introducing the Transformer, scaled dot-product attention, and multi-head attention).
Radford, A., et al. (2019). Language Models are Unsupervised Multitask Learners. OpenAI Technical Report. (The GPT-2 paper establishing autoregressive decoder-only Transformers, learned position embeddings, and 50,257 BPE vocabulary).
Karpathy, A. (2022). nanoGPT. Open-source repository. (A clean, inspectable ~300-line PyTorch implementation of the GPT architecture, including Pre-LN blocks and causal masking).
Ba, J. L., Kiros, J. R., & Hinton, G. E. (2016). Layer Normalization. arXiv:1607.06450. (The foundational paper introducing per-token feature normalization to stabilize neural network training).
He, K., Zhang, X., Ren, S., & Sun, J. (2016). Deep Residual Learning for Image Recognition. CVPR 2016. (Residual learning with identity shortcuts in deep networks).
Hendrycks, D., & Gimpel, K. (2016). Gaussian Error Linear Units (GELUs). arXiv:1606.08415. (The smooth nonlinear activation function used in GPT and modern Transformer FFNs).
Brown, T. B., et al. (2020). Language Models are Few-Shot Learners. (The GPT-3 paper detailing the behavior and scaling properties of large autoregressive models).
Primary-source links: Transformer paper, GPT-2 report, OpenAI GPT-2 code, nanoGPT code, LayerNorm, Residual learning, GELU.