TL;DR: Transformers consist of stacked blocks of multi-head self-attention and feed-forward networks. At their heart are query, key and value vectors, which compute which tokens are relevant to each other. In this deep dive we take every component apart step by step β first with intuition, then with the technical details.
For everyone
A quick recap

Transformers replaced RNNs because they can process the entire text in parallel. Self-attention lets every token look at and weight every other token. The result is a model that can capture context across very long distances β instead of running through the text sequentially, every word looks at all the others at the same time.
At its core, a transformer does one single thing: next-token prediction. Given a piece of text β what is the most likely next token? Out of this simple task come ChatGPT, Claude, Gemini and the like.
For nerds
The architecture
Every text-generating transformer consists of three main components:
- Embedding: tokenization and conversion into vectors with positional information.
- Transformer block: multi-head self-attention + MLP β stacked several times.
- Output layer: linear projection onto the vocabulary and sampling of the next token.
Below we walk step by step through every station a token passes through, from the input text to the output probability. As a reference we use GPT-2 (small) β a model that, at 124 million parameters, is still manageable but architecturally practically identical to modern LLMs.
1. Tokenization & embeddings
Intuition: Models compute with numbers, not letters. So we have to bring text into a numerical form that reflects semantic similarity β similar words should get similar numbers.

Technical: The process runs in four steps:
- Tokenization: Byte-pair encoding (BPE) splits the text into tokens. Frequent words ("data") stay whole, rare words are split into subwords ("empower" β "empow" + "ers"). GPT-2 has a vocabulary of 50,257 tokens.
- Token embedding: Each token ID is assigned a 768-dimensional vector (the exact dimension depends on the model). The embedding matrix therefore has the shape (50,257 Γ 768) β about 39 million parameters that the model learns during training. Tokens with similar meanings end up close to each other in this matrix.
- Positional encoding: Since self-attention is order-agnostic, we need additional information about where in the sentence a token sits. GPT-2 learns its own position matrix for this; other models use sinusoidal functions or rotary encodings (RoPE).
- Final embedding: Token embedding and positional encoding are simply added together. The result is one vector per input token that carries both meaning and position.
Demo to try out: tiktokenizer.vercel.app β play around and see for yourself how a sentence is split into tokens.
2. Multi-head self-attention: Q, K, V
Intuition: Self-attention is the heart of it all. Picture it like this: every word gets to "ask" the other words what is relevant. The Polo Club explainer uses a search-engine analogy:
- Query (Q) = the search query a token issues. "Which of you are relevant to me?"
- Key (K) = the description of each token. "This is how I can be found."
- Value (V) = the actual content a token passes on once it is recognized as relevant.
Technical: The computation runs in four stages.
Step 1 β Compute Q/K/V: Three vectors are derived from the embedding (dimension 768) by multiplying it with three learned weight matrices W_Q, W_K, W_V:
Q = X Β· W_Q
K = X Β· W_K
V = X Β· W_VStep 2 β Multi-head splitting: Q, K and V are split into several heads β GPT-2 small uses 12 heads with 64 dimensions each (12 Γ 64 = 768). Each head focuses on different linguistic aspects: one might learn subjectβverb relationships, another pronoun resolution, a third semantic similarity. This keeps the model from committing to a single view.
Step 3 β Masked self-attention: For each head, the famous attention formula is computed:
Attention(Q, K, V) = softmax( Q Β· Kα΅ / βd_k ) Β· V- Q Β· Kα΅: dot product of all query vectors with all key vectors β yields an nΓn matrix of "relevance scores" between every pair of tokens.
- / βd_k: scaling prevents the values from exploding at high dimensions and the softmax from tipping into flat gradients.
- Masking: In generative models (decoder-only, like GPT), the upper triangle of the matrix is filled with ββ so that a token can never look into the future. This way the model learns genuine prediction instead of memorization.
- Softmax: turns the scores into a probability distribution per row (sum = 1).
- Β· V: multiplying by the value vectors yields a context-enriched representation for each token.
Step 4 β Output & concatenation: The outputs of all 12 heads are glued back together into a 768-dimensional vector and projected through a final linear layer (W_O). This is how the model consolidates the information from all heads.
3. MLP / feed-forward layer
Intuition: While attention lets the tokens talk to each other, the MLP "thinks" about each token on its own. It is the layer in which the model stores knowledge and refines non-linear patterns.
Technical: The MLP consists of two linear layers with a GELU activation in between:
- Expansion: 768 β 3072 dimensions. The model projects into a space four times larger, with room for more β and more finely resolved β patterns.
- GELU activation: a smooth variant of ReLU β it introduces the necessary non-linearity.
- Compression: 3072 β 768 again. The result flows into the next block.
Important: the MLP works on each token independently β it no longer mixes token contents; attention has already taken care of that. Exactly this division of labor ("attention routes, the MLP refines") is the trick that makes transformers so scalable.
4. Stacking transformer blocks
A transformer block combines these stations, each wrapped in LayerNorm and residual connections:
x β LayerNorm β Multi-Head Attention β + Residual
β LayerNorm β MLP β + ResidualGPT-2 small stacks 12 of these blocks, GPT-3 has 96, modern frontier models considerably more. With every layer the representations become more abstract: lower layers often learn syntax and parts of speech, higher layers thematic and logical relationships.
5. Output: logits, softmax and sampling
Intuition: After all the blocks, the model has to decide: which token comes next?
Technical: The final 768-dimensional representation is projected onto the vocabulary size by a linear layer (50,257 values = logits). Softmax turns them into a probability distribution. Then the model samples β controlled by three hyperparameters:
- Temperature: the logits are divided by T before the softmax. T < 1 makes the model more deterministic ("better behaved"), T > 1 increases the spread ("more creative"). T = 0 corresponds to greedy decoding: always the most likely token.
- Top-k: only the k tokens with the highest probability are considered; the rest are cut off.
- Top-p (nucleus sampling): we take the smallest set of tokens whose cumulative probability is β₯ p β i.e. adaptively more or fewer candidates depending on the distribution.
The chosen token is appended to the input sequence and the entire forward pass starts over. This is how a response is built token by token (autoregressively).
6. Helper components: LayerNorm, dropout, residuals
Three small but crucial components keep training stable:
- Layer normalization: normalizes the activations of each layer to mean 0 and variance 1. This stabilizes training and speeds up convergence. In transformer blocks it is applied before attention and the MLP (pre-LN).
- Dropout: randomly sets a fraction of the activations to 0 during training. It prevents overfitting and forces the model to learn more robust features. Disabled at inference time.
- Residual connections: the input of a sublayer is added to its output (x + f(x)). These "shortcuts" let gradients flow straight through and are what make it possible to stack dozens or even hundreds of layers in the first place.
Recommended visualization
If you want to watch token vectors, attention maps and softmax distributions move live: the Transformer Explainer from Georgia Tech (Polo Club) runs a GPT-2 model directly in your browser and shows each of the steps described above interactively. Change the input, turn up the temperature, compare attention heads β all in real time.
π poloclub.github.io/transformer-explainer
This site's own AI Lab also runs a model right in your browser.
Why it matters in 2026
Transformers remain the foundation of every large model. If you understand the mechanisms, you also understand their strengths and limits:
- Context limits exist because the attention matrix grows quadratically with sequence length.
- Hallucinations are a consequence of the model simply choosing the most likely next token β not the truest one.
- Optimizations such as Flash Attention, grouped-query attention or mixture of experts target exactly the bottlenecks described above.
Once you've understood how 12 Q/K/V matrices, an MLP sandwich and a softmax soup add up to a language model, you'll read model releases with completely different eyes.
Further resources
If you want to dig deeper, here is some curated material:
- sannykim/transformer (GitHub) β a curated link list with core reading such as The Illustrated Transformer and further deep dives. Ideal for working through the topic systematically.
- Attention Is All You Need (Vaswani et al., 2017) β the original paper that started it all.
- The Illustrated Transformer by Jay Alammar β a visually compelling explanation of the encoder-decoder architecture.
- Polo Club Transformer Explainer β interactive GPT-2 in the browser (see above).
- karpathy/nanoGPT (GitHub) β Andrej Karpathy's minimalist reference implementation of GPT-2 training in ~600 lines of Python. If you'd rather read code than theory, it's all here.
- 3Blue1Brown β Transformers, the tech behind LLMs β a beautifully animated explainer video (chapter 5 of the deep learning series). Ideal for internalizing embeddings, attention and softmax visually.
- Andrej Karpathy β Deep Dive into LLMs like ChatGPT β a good 3.5 hours of concentrated overview of the complete LLM stack: pretraining, tokenization, post-training, RLHF, hallucinations. Essential viewing for anyone who is serious about this.
Where next? Which path is worth taking depends on your background: if you're familiar with backpropagation and RNNs, you can jump straight into the original paper. If you're more at home with the basics of neural networks, you're better off starting with Jay Alammar's visualizations before moving on to Q/K/V formulas and multi-head splitting.