← All posts
EducationNovember 2, 2026 · 12 min read

How a Transformer Works: A Step-by-Step Walkthrough

How a GPT-style transformer turns 'What is the capital of France?' into 'The capital of France is Paris.' — two boxes, step cards with diagrams, a clickable attention map, a layer slider and a token-by-token generator.

How a Transformer Works: A Step-by-Step Walkthrough
One sentence through GPT‑2, step by step.

Seven words walk in. One word walks out. Then another. This page follows exactly what happens to each of them, with the math drawn, the tables readable, and three panels you can play with.

What is the capital of France ? → The capital of France is Paris .

ColourMeaning
ambermodel file: frozen weights, Box 1
tealworking memory: this sentence, Box 2
greypure arithmetic, no weights involved
redthe one moment stored knowledge is used

The room

Picture seven people in a row, each holding one word of the question. The last person, holding ?, has to guess the next word. At the start each person knows only their own word and their seat number.

A round goes like this. Everyone asks a question aloud ("who here is the thing I'm about?"). Everyone else says how relevant they are (France: "very"; the: "not really"). Each person adds what they heard to their notes, keeping the original word. Then each person thinks alone for a moment and writes a conclusion.

Twelve rounds. Each round, people ask better questions because their notes are richer. At the end a clerk takes the last person's notes, holds them against a list of 50,000 words, and picks the one that fits best: The. An eighth person sits down holding it, and the room runs again.

Everything below is this story written in matrices. This is the dictionary:

In the storyIn the math
a person's notesone row of X: 768 numbers
asking aloudquery vector, Q
"how relevant am I"key vector, K, dot‑producted with the query
what they hand overvalue vector, V
adding to notesweighted sum of V, plus residual
thinking alonethe MLP, W1 and W2
twelve roundstwelve layers
the clerkLM head: row · every word vector, softmax

1. The two boxes

Before anything runs, memory holds exactly two things. Keep them apart and nothing else on this page is confusing.

Box 1 · Model file

  • Embedding table50,257 words × 768
  • Position table1,024 seats × 768
  • Layer 1: Wq Wk Wv Wo W1 W26 matrices
  • Layer 2: Wq Wk Wv Wo W1 W26 matrices
  • … ×12 layers72 matrices
  • LM headreuses embedding table

Everything the model knows: 124 million numbers learned in training. Identical for every question anyone ever asks. Downloaded once, never changes while answering.

Box 2 · Working memory

  • X, row 1What · 768 numbers
  • X, row 2is · 768 numbers
  • X, row 3the · 768 numbers
  • X, row 4capital · 768 numbers
  • X, row 5of · 768 numbers
  • X, row 6France · 768 numbers
  • X, row 7? · 768 numbers
  • K, V cachesaved per layer

Everything about this sentence. One row per word, rewritten after every layer. Built fresh for this request.

The whole model is one move repeated: X × W → new X. Box 1 is the lens; Box 2 is what passes through it. Nothing is searched. A function is applied.

2. Where Q, K and V come from

They are not stored anywhere. At every layer they are made fresh from the current rows of X, using that layer's three matrices from the model file.

X times Wq gives Q, X times Wk gives K, X times Wv gives V

Row 7 of Q is the question asked by ?. Row 6 of K is the label worn by France. Wq and Wk are learned so that these two line up, even though "?" and "France" are nothing alike as words. That is the whole reason the projections exist: they let "asking" mean something other than "being similar."

3. Who listens to whom

The 7 × 7 table that attention produces in layer 1. Click a row to see that word's shares and the weighted sum it computes. Illustrative numbers; the real model spreads this over 12 heads.

What
is
the
capital
of
France
?
1.00
0.55
0.45
0.20
0.50
0.30
0.30
0.10
0.15
0.45
0.05
0.05
0.10
0.60
0.20
0.08
0.05
0.04
0.33
0.20
0.30
0.18
0.03
0.02
0.30
0.03
0.40
0.04

Rows: who is asking. Columns: who answers. Striped cells are the future, masked out. Each row sums to 1.

? listens hardest to France and capital, then What. After this line it carries the whole question.

gathered(?) =
  0.18·V(What) +
  0.03·V(is) +
  0.02·V(the) +
  0.30·V(capital) +
  0.03·V(of) +
  0.40·V(France) +
  0.04·V(?)
then: row 7 = row 7 + gathered·Wo

The shares come from Q·Kᵀ then softmax (step 4). The sum is shares × V (step 5). Neither line uses a weight matrix; the weights were already used to make Q, K and V.

4. The pipeline, step by step

Each card: what goes in, where it came from, what comes out, and what we have accomplished for our sentence once it is done. The italic line is the same step in the story.

Prepare · done once

0

Tokenize text → numbers

Input"What is the capital of France?"

Usestokenizer vocabulary Box 1

Output[2061, 318, 262, 3139, 286, 4881, 30]

Accomplished: each word is now an ID that can index a table. Nothing is understood yet.

Seven people are handed seven word cards.
1

Embed ID → 768 properties

Input7 IDs

Usesembedding table Box 1

OutputX, 7 rows × 768 Box 2

Embedding lookup: ID 4881 picks row France from the table

Accomplished: every row describes its own word alone: France = country, capital = city/government noun, ? = end of a question.

Each person recalls everything they know about their one word.

2

Add position so order exists

InputX

Usesposition table Box 1

OutputX, each row + its seat vector

Accomplished: row 6 now reads "France, in seat 6." Without this, attention would see an unordered bag and "France is the capital of what" would look identical.

Each person notes which seat they are in.

Attention · gather from others · repeated in every layer

3

Make Q, K, V three roles per word

InputX (current rows)

UsesWq, Wk, Wv of this layer Box 1

OutputQ, K, V, each 7 rows Box 2

Accomplished: every word has published a question, a label and a payload. See the diagram in section 2.

Each person decides what to ask, how to describe themselves, and what they would share.

4

Score who listens to whom

InputQ, K

Usesnothing from Box 1 pure math

Output7 × 7 table of shares

Q times K transposed, mask the future, softmax rows

Accomplished: each word has decided how much to listen to each earlier word. That is the table in section 3.

Everyone asks; everyone else says how relevant they are.

5

Gather the weighted sum

Inputshares table, V

Usesnothing from Box 1 pure math

Output7 rows of mixed payloads

gathered row for ? equals weighted sum of value rows

Accomplished: row ? now holds a blend that is 40% France, 30% capital, 18% What. Context has physically moved into the row.

Each person writes down what the relevant people told them.

6

Add back keep the original

InputX, gathered rows

UsesWo of this layer Box 1

OutputX = X + gathered·Wo

Accomplished: row ? = "end of question" plus "about France's capital." It did not lose its identity; it accumulated. This is what lets 12 layers stack without the early meaning washing out.

Notes are added to, never thrown away.

Think · each word alone · repeated in every layer

7

MLP draw conclusions

InputX (one row at a time, no cross-talk)

UsesW1, W2 of this layer Box 1

OutputX = X + gelu(X·W1)·W2

row expands to 3072 detectors, some fire, contracts back to 768

Accomplished: gathered facts became a conclusion. Row ? no longer just "contains France and capital"; it now says "this is a request for France's capital city." Most of the model's factual knowledge lives in W1 and W2.

Each person thinks alone and writes a conclusion under their notes.

Repeat

8

Layers 2 to 12 steps 3–7 again, new matrices each time

InputX from the previous layer

Usesthat layer's own 6 matrices Box 1

OutputX, richer each time

Accomplished: each round can ask sharper questions because the rows it reads are already annotated. Early layers settle grammar (what is the subject), middle layers settle meaning (what is being asked), late layers settle the prediction (what comes next). Drag the slider in section 5 to watch it happen.

Eleven more rounds; the questions get smarter each time.

Read out · once per generated token

9

LM head description → word

Inputrow 7 of final X

Usesembedding table again Box 1

Output50,257 probabilities

row 7 dotted with every word vector, softmax, The wins

Accomplished: the 768-number description at ? is translated back into a word. "Which word's own vector points the same way as this description?" is the whole question, answered with one dot product per word.

The clerk reads the last person's notes and picks the best-fitting word.

10

Append and repeat only the new word does work

Input"The" as row 8

Usessaved K, V of rows 1–7 from every layer Box 2 cache

Outputnext word, then row 9, …

Accomplished: rows 1–7 are frozen (they could never see row 8 anyway), so only row 8 runs steps 3–9, scoring its Q against the seven stored K's. That is why the first token of a reply is slow and the rest stream quickly. Section 6 lets you step through it.

An eighth person sits down. The first seven keep their notes exactly as they were.

5. Watch the ? row learn, layer by layer

Drag through the 12 layers. The left card is what row 7 encodes after that layer. The right bars are what the clerk would pick if asked right now (the "logit lens": applying the LM head to an intermediate row). Illustrative, but this is the real shape: generic early, specific late.

0 / 12
embedgrammarmeaningprediction
row 7 · after embedding + position
“?” — end-of-question punctuation, seat 7.
Nothing gathered yet. The row knows only its own word and seat.
If the clerk read this row now
the
6%
I
5%
\n
5%
Paris
0%

6. Generate the answer, one row at a time

Press Next token. Each press appends one row, runs it through the layers against the saved rows, and reads it out. Watch which rows it listens to and what mechanism produced the word.

WhatisthecapitalofFrance?
Row “?” has been through 12 layers. Reading it out…
New row listens mostly to
FrancecapitalWhat
Row’s conclusion after layer 12
An answer sentence starts now.
read out
Clerk’s probabilities
The
31%
Paris
22%
It
12%
A
5%

Only one step used stored knowledge

"The capital of France" is attention copying words that already appear in the question; "is" is grammar. The one word that was not in the input, Paris, appears at row is: a few hundred of the 3,072 detectors in the later layers fire for "capital-of-France answer slot," and their W2 rows push the vector toward the direction that, at the LM head, lines up with "Paris." That direction lives in Box 1, learned from text during training. Nothing was looked up; a function was applied.

7. Every row, every stage

The 768 numbers are not readable directly, so this table says what they encode. The + marks what attention pulled in.

RowAfter step 2 (embed + position)After step 6, layer 1 (gathered)After step 7, layer 1 (concluded)After layer 12
Whatquestion word · seat 1nothing to its left; unchanged"I open a question""a what‑question wanting a noun answer"
isverb · seat 2+ What"verb of a what‑question""the question is about identity"
thearticle · seat 3+ is, What"a noun phrase is starting"a signpost; little more
capitalnoun: city, government · seat 4+ the, What"the thing asked about is a capital""capital‑of‑something is the target"
ofpreposition · seat 5+ capital"capital of ___, owner coming"links capital to France
Francecountry, European · seat 6+ of, capital"France owns the capital""country = France, subject of the question"
?end of question · seat 7+ What, capital, France"a question about France's capital just ended""an answer sentence starts now; it will involve Paris"

Early rows barely change because they have nothing to gather. The last row changes the most and ends up holding the description of the whole question, which is why it is the row the clerk reads.

8. What to keep

  1. Two boxes. Weights are the lens and never change. X is one row per word and is rewritten every layer.
  2. Q, K, V are made fresh at every layer: current X × that layer's Wq / Wk / Wv. They are not stored anywhere.
  3. Two operations only. Gather (attention: dot products choose shares, a weighted sum mixes payloads) and conclude (MLP: detectors fire, write a conclusion). Everything else is add‑back and repeat.
  4. A row never loses itself. Each layer adds annotations on top; that is why the last row ends up describing the whole question while still knowing it is "?".
  5. Reading out is one dot product per vocabulary word. The row's direction is compared with each word's own vector; the closest wins.
  6. Generation is the same machine run once more per word, with earlier rows frozen in the cache. Most answer words are copied from the question; the rare "Paris" moment is the MLP weights speaking.

From understanding to building

You now know exactly what happens inside a transformer when it reads a sentence — two boxes, a gather-and-conclude loop, and a single dot product to read out each word. The next step is putting that power to work on your data.

GuidedMind is the no-code context engine for AI agents, workflows, and automations. It gives your models reliable document context with GraphRAG, eval benchmarking, and live monitoring — so you can ship AI that actually works, without writing code.

Start building with GuidedMind →
All posts →
Under the hood: a more secure, observable platform
System Update

Under the hood: a more secure, observable platform

guidedmindai
View Article
RAG Builder is now available to everyone, with a brand-new Data Source board
System Update

RAG Builder is now available to everyone, with a brand-new Data Source board

guidedmindai
View Article
Meet Claude: search your Knowledge Graph right from Claude chat
System Update

Meet Claude: search your Knowledge Graph right from Claude chat

guidedmindai
View Article