Transformers — Architecture & Recent Innovations

Generative-AI engineering module · From "Attention Is All You Need" to today's frontier LLMs
Intermediate Python + basic deep learning 14 hours · 7 sessions Pass: 75%
Vaswani et al. 2017 · R. Raghav (LinkedIn) · Hugging Face
Learning Objectives
  • Explain the Transformer architecture end to end — embedding, positional encoding, multi-head self-attention, feed-forward blocks, residuals, and the output head — as introduced in Attention Is All You Need (2017).
  • Contrast Transformers with classic deep learning (RNNs, LSTMs, CNNs, MLPs): why attention replaced recurrence, and what Transformers kept from deep learning.
  • Trace the forward pass of a decoder-only LLM like GPT, including masked self-attention and autoregressive next-token generation.
  • Understand recent innovations — RoPE, GQA/MQA, FlashAttention, Mixture-of-Experts, long-context tricks, and quantization — and which production models use them.
  • Run hands-on labs: a softmax/sampling sandbox, an attention-matrix explorer, and a model-size calculator.
  • Compare today's assistants — ChatGPT, Claude, Grok, and Meta AI — as different products built on the same Transformer foundation.
14h
Total duration
3
Interactive labs
6
Innovations ×5 examples
5
Graded assignments
20
Quiz questions
Course At A Glance — 7 Sessions × 2 Hours
#SessionFocusTime
1From Deep Learning to AttentionRNN/CNN limits, why self-attention, the 2017 leap2 h
2The Transformer BlockEmbedding, positional encoding, residual + LayerNorm2 h
3Self-Attention In DepthQ/K/V, scaled dot-product, masking, multi-head2 h
4Decoder-Only LLMs & GenerationCausal masking, softmax, sampling, autoregression2 h
5Recent InnovationsRoPE, GQA/MQA, FlashAttention, MoE, long context2 h
6Efficiency & DeploymentKV-cache, quantization, distillation, serving2 h
7Frontier Models & CapstoneChatGPT/Claude/Grok/Meta AI, project work2 h
What You Will Need
  • Python 3.9+ with pip install torch transformers numpy matplotlib.
  • A notebook environment — Jupyter, Google Colab, or Kaggle (free GPU helps but is not required for the labs here).
  • A Hugging Face account to pull pretrained models such as gpt2 / distilgpt2.
  • Optionalbertviz for attention visualization, and any LLM API key for the capstone.
Primary References
  • Attention Is All You Need — Vaswani et al., 2017 (the founding paper).
  • "Transformers Architecture and Recent Innovations" — R. Raghav, LinkedIn (course framing).
  • The Illustrated Transformer — Jay Alammar · Transformer Explainer — Georgia Tech (Polo Club).
  • Hugging Face Transformers documentation & course.

Foundation Keywords

Everything you need before reading the architecture — what a token and an embedding are, how attention lets words "look at" each other, and how a stack of these blocks becomes a language model. No prior NLP experience assumed.

Core Building Blocks
From Blocks To Language Models
How It Connects — One Forward Pass
Text becomes tokens, tokens become vectors, attention mixes them, a feed-forward net refines them, and the last vector is turned into a probability over the whole vocabulary — the next word.
Text
Tokens + embeddings
Self-attention
Feed-forward
Softmax → next token

Key idea: a Transformer is the same small block repeated many times. Each repeat lets every token gather a little more context, until the model "understands" the sentence well enough to predict what comes next.

Deep Learning vs Transformers

Transformers are deep learning — but a specific kind that abandoned recurrence and convolution in favour of attention. This page contrasts the classic architectures (RNN, LSTM, CNN, MLP) with the Transformer, and shows what stayed the same.

Side-By-Side
DimensionClassic Deep Learning (RNN / LSTM / CNN)Transformer
Sequence processingSequential — one timestep at a time (RNN/LSTM)Parallel — the whole sequence at once
Long-range dependenciesHard — signal fades over distance (vanishing gradients)Direct — any token can attend to any other in one step
Training speedSlow — recurrence blocks GPU parallelismFast — fully parallel across positions
Core operationRecurrence (RNN), convolution (CNN)Self-attention (scaled dot-product)
Inductive biasStrong — locality (CNN), order (RNN)Weak — must learn structure from data + positional encoding
Compute costLinear in sequence lengthQuadratic O(n²) in sequence length (the main cost)
Data appetiteWorks with less dataHungry — shines at large scale
Dominant use todayEdge/timeseries, vision (CNN still strong)Language, multimodal, increasingly vision & audio
RNN / LSTM
Reads left to right, carrying a hidden "memory". Great inductive bias for order, but slow and forgetful over long spans. Attention removed the bottleneck.
CNN
Slides filters to capture local patterns; superb for images. Limited receptive field per layer — attention sees the whole input immediately.
MLP
Fully-connected layers — no notion of sequence or position. Still lives inside the Transformer as the feed-forward sub-layer.
What Transformers KEPT From Deep Learning
  • They are still neural networks trained by backpropagation and gradient descent on a loss.
  • Stacked layers + nonlinearities — depth still builds abstraction, just with attention instead of recurrence.
  • Residual connections & normalization — borrowed straight from ResNets and earlier deep-learning work to train deep stacks.
  • Embeddings & softmax — the input and output machinery predates Transformers.
  • The MLP — every block contains a classic feed-forward network doing most of the "thinking".

One-line summary: RNNs and CNNs ask "what's nearby in time or space?" Transformers ask "what's relevant anywhere?" — and answer it for every token, in parallel.

The Road Here
1986 · MLP
Backprop popularised; fully-connected nets learn from data.
1998 · CNN
LeNet/AlexNet (2012) — convolution dominates vision.
1997 · LSTM
Gated recurrence tackles long sequences for translation & speech.
2014 · Seq2Seq + Attention
Bahdanau attention bolted onto RNNs — the seed of the idea.
2017 · Transformer
"Attention Is All You Need" drops recurrence entirely.
2018–now · LLMs
BERT, GPT, and the scaling era — Transformers everywhere.
The Forward Pass, In Order
A decoder-only LLM (GPT-style), traced top to bottom — the tensor shape is tracked at each step

Running example: the prompt "Data visualization empowers users to" → 6 tokens. The hidden size below is GPT-2 small's d_model = 768, with 12 blocks and 12 heads.

Tokens
Embedding
Block × 12
Output head
Next token
Scaled Dot-Product Attention
The single mechanism at the heart of every Transformer

Every token produces three vectors: a Query (what am I looking for?), a Key (what do I offer?), and a Value (what will I pass on?). Attention scores each token against every other, turns the scores into weights, and blends the Values accordingly.

scores = (Q @ K.T) / sqrt(d_k) # how much each token relates to each other scores = scores + causal_mask # upper triangle → -inf (can't see the future) weights = softmax(scores) # each row sums to 1 output = weights @ V # context-aware blend of Values

Why divide by √d_k? Dot products grow with dimension; without scaling, softmax saturates and gradients vanish. The √d_k keeps scores in a sane range.

Multi-Head Attention

Instead of one attention, run h of them in parallel on d_model/h-sized slices. Each head can specialise — one tracks syntax, another long-range reference — and their outputs are concatenated and projected back.

Q,K,V (d=768)
→ split →
12 heads × 64
→ attention →
concat → 768
linear

Try the Self-Attention Sandbox in the Labs tab to see per-head weight patterns and the causal mask in action.

Recent Innovations
What changed since 2017 — and which production models use each. Five worked examples per innovation.

Interactive Labs

Three live demonstrations that run entirely in this page — no install. Turn the dials and watch the math respond.

Lab 1 · Softmax & Sampling Sandbox

A frozen set of candidate next-tokens with fixed logits. Adjust temperature, top-k, and top-p and watch the probability distribution reshape — exactly what a model does at every generation step.

Lab 2 · Self-Attention Sandbox

An attention weight matrix for a short sentence. Each row is a query token; brighter cells = more attention paid to that key token. Toggle the causal mask and switch heads to see different patterns.

Weights here are illustrative (deterministic), generated to show typical head behaviour — not from a live model.

Lab 3 · Transformer Size Calculator

Punch in an architecture and estimate its parameter count — the same arithmetic that separates GPT-2 (124M) from frontier models.

Common Pitfalls — What Went Wrong?

Each snippet has a real, common Transformer/attention bug. Predict the problem, then reveal the diagnosis.

Lab Assignments — 5 Graded Projects

Each builds on the last, from attention-from-scratch to a frontier-model comparison. Submit a notebook plus a short write-up.

Responsible-Use Checklist
  • Hallucination: a Transformer predicts plausible tokens, not facts. Verify outputs; ground them with retrieval (RAG) where correctness matters.
  • Bias & representation: models inherit biases from training data. Evaluate across groups before deploying in hiring, lending, or moderation.
  • Context & privacy: anything in the prompt may be logged or echoed. Don't paste secrets or personal data into shared models.
  • Compute & cost: attention is O(n²); long contexts and large models carry real energy and dollar costs — measure before scaling.
  • Attribution & licensing: generated text/code can resemble training data. Respect licences and disclose AI assistance where required.
  • Evaluation, not vibes: benchmark on YOUR task. Public leaderboards rarely match your domain.
Knowledge Check — 20 Questions · Pass Mark 75%

Frontier Assistants Compared

ChatGPT, Claude, Grok, and Meta AI are four products built on the same decoder-only Transformer foundation. What differs is scale, training data, alignment method, tools, and openness. Snapshot as of June 2026 — this field moves fast, so always re-check current versions.

At A Glance
AspectChatGPTClaudeGrokMeta AI
MakerOpenAIAnthropicxAIMeta
Flagship (Jun 2026)GPT-5.5Claude Opus 4.8Grok 4.3Llama 4
ArchitectureDecoder-only Transformer (all four) — differences are in scale, data, alignment & tooling
Signature strengthBroad all-rounder; tools, images, agentsCoding, long-form, careful document work; tops intelligence/coding indexesReal-time X data; reasoning-first; permissiveOpen-weight & self-hostable; baked into Meta apps
Alignment approachRLHF + safety tuningConstitutional AI + RLHFRLHF; lightest guardrailsRLHF on open Llama base
OpennessClosed weightsClosed weightsMostly closed (some older weights opened)Open weights (Llama licence)
Context windowLarge (long-context tiers)Large (long-context, Projects)~1M tokensVery large (Llama 4 Scout up to ~10M)
Where you use itchatgpt.com, API, appsclaude.ai, API, Code/CoworkX (Twitter), grok.com, APIWhatsApp, Instagram, FB, Ray-Ban, API

Model names/versions change frequently; figures reflect mid-2026 reporting and should be re-verified for current work.

The teaching point: none of these "win" on architecture — they're all Transformers. The differences a user feels come from training data, model size, the alignment/RLHF recipe, the surrounding tools (web, code, agents), and how open the weights are. Pick by task and constraints, not brand.

The Transformer — In the Order It Runs

GPT-2 forward pass reassembled as one continuous pipeline. Your prompt enters at the top, a single tensor flows downward, and one token comes out the bottom.

Reading note · Transformer Explainer (poloclub)

The Transformer,
in the order it runs.

The same GPT-2 walkthrough as the interactive explainer — but reassembled as one continuous pipeline. Your prompt enters at the top, a single tensor flows downward, and one token comes out the bottom. Each stage shows what changes and the shape of what's moving.

model GPT-2 small params 124M vocab 50,257 d_model 768 blocks 12 heads 12 head_dim 64 mlp_hidden 3,072
activations (the tensor flowing through) learned weights (fixed after training) operation
Prompt “Data visualization empowers users to” text 1 · Embedding tokenize → look up vectors → add position (6, 768) 2 · Transformer block × 12 stacked Multi-head attention MLP 768→3072→768 + LayerNorm ×2 · Residual ×2 · shape stays (6, 768) throughout loop 3 · Output head linear → logits → softmax → sample (50257) Next token e.g. “ create ” → append, repeat

The map. Everything below is a zoom-in on one of these boxes. The rail on the left is the single tensor; only its shape changes — never its identity — until the very last step turns it into a word.

01

Tokenization

Text → discrete token IDs

The model can't read characters. The prompt is first chopped into tokens — whole words or word-pieces drawn from a fixed vocabulary of 50,257 entries. Common words map to one token; rarer ones split. Here "empowers" becomes two pieces, so six words yield six tokens.

Data 5178 visualization 32704 empower 39061 s 82 users 2985 to 284 one word → two tokens 6 tokens

Figure 1. Each box is one token; the number below is its ID — a row index into the embedding table built next.

02

Token embedding

Each ID → a 768-number vector of meaning

Each token ID is used to pull one row out of a giant learned lookup table of shape (50257, 768) — about 39M parameters. The row is a 768-dimensional vector. Tokens used in similar ways sit close together in this space, which is how raw IDs gain semantic meaning.

Embedding table (50257, 768) row 5178 → vector ID 5178 768-dim vector … 768 0.21 −0.04 0.88 0.10 −0.33 … do this for all 6 tokens → (6, 768)

Figure 2. The ID is just a row number. Six tokens become a (6, 768) matrix — six rows of 768 numbers.

03

Positional encoding

Stamp each token with where it sits

The token vectors alone carry no order — “users empowers” would look identical to “empowers users.” A second learned table maps each position 0,1,2,… to its own 768-vector, so the model can tell first from last.

Position table (1024, 768) → pick rows 0…5 pos 0 pos 1 pos 2 pos 3 pos 4 pos 5 each is a 768-vector, same shape as a token vector → ready to add

Figure 3. One position vector per slot. GPT-2 learns these during training rather than using a fixed formula.

04

Final embedding

token vector + position vector = the input to the stack

Add the two vectors element-wise. Each token now carries both what it means and where it is, in a single (6, 768) matrix. This is the tensor that enters the transformer blocks.

token embedding (6, 768) + position encoding (6, 768) = final embedding (6, 768) enters the stack of 12 transformer blocks ↓

Figure 4. The end of "Embedding." From here the shape (6, 768) stays fixed all the way through the 12 blocks.

05

Transformer block — the loop that repeats 12×

attention mixes tokens together · MLP refines each one alone

This is the engine. The (6, 768) tensor passes through the block below; its output feeds straight into an identical block, twelve times. Two ideas do all the work:

attention
Tokens talk to each other. Each token looks at the others and pulls in relevant context — “to” learns it follows “users,” etc.
MLP
Each token thinks alone. A feed-forward network refines every token's vector independently, with no cross-token mixing.
norm / res
A LayerNorm sits before each of the two parts, and a residual shortcut adds each part's input back to its output.
in (6, 768) LayerNorm Multi-head attention + residual LayerNorm MLP + repeat ×12 output → next block

Figure 5. One block. Stages 5a–5e below open up the two blue boxes — attention first, then MLP.

5a · Build Query, Key, Value

Inside attention, each token's vector is multiplied by three learned weight matrices to produce three new vectors. The classic search analogy: Query = what this token is looking for, Key = what each token offers, Value = the content it will hand over if matched.

embedding (6,768) Wq Wk Wv Q (6,768) K (6,768) V (6,768)

Figure 5a. One embedding → three projections via learned weights. Q · K · V, each (6, 768).

Deep dive · the projection, exactly

Why three matrices? A token is one vector, but attention needs it to play three roles at once: ask a question, answer others' questions, and carry content. Reusing the same vector for all three would force "what I'm looking for" and "what I offer" to share directions. Three separate learned projections give three independent views of the same token.

Q = XWQ  K = XWK  V = XWV
X (6×768)  ·  each W (768×768)  →  Q, K, V each (6×768)

What each output number is. Row i of Q is token i's query; its entry m is a dot product of the token's embedding with column m of WQ:

qi,m = d=1768 xi,d · (WQ)d,m

In GPT-2 the three matrices are stored fused as one 768 × 2304 weight (c_attn) and the result is sliced into Q | K | V; a bias is added to each.

5b · Split into 12 heads

Each of Q, K, V is sliced along its 768 columns into 12 heads of width 64. Every head runs attention independently and can specialise — one tracks grammar, another long-range meaning.

Q (6, 768) … 12 heads × (6, 64)

Figure 5b. 768 = 12 heads × 64. Same split applies to K and V.

5c · Masked self-attention (per head)

This is the heart of the model. Inside each head:

① score
Q · Kᵀ gives a 6×6 grid: how much every token relates to every other.
② mask
Scale down, then set the upper triangle to −∞ so a token can't see the future — essential for left-to-right generation.
③ softmax
Turn each row into weights that sum to 1 — a probability distribution over "who to listen to."
④ blend
Multiply those weights by V to get each token's context-aware output.
① Q·Kᵀ scores ② mask future −∞ ③ softmax rows ④ × V → output (6, 64) Each row only attends to itself and tokens to its left — the staircase of allowed (blue) vs blocked (red) cells. attend masked (future)

Figure 5c. The four moves of attention. The red triangle is the causal mask — the single rule that makes generation possible.

Deep dive · one head, four moves, expanded

Everything below happens inside one head, on its own (6×64) slices of Q, K, V, with dk = 64.

① Score — the raw dot product. Multiply every query by every key. Entry (i,j) measures how aligned token i's query is with token j's key — one number summarising 64 multiply-adds:

S = QKT,  Sij = qi·kj = d=164 qi,dkj,d
Q (6×64) · KT (64×6) → S (6×6)

② Scale — divide by √dk. Summing 64 products inflates the variance of S to about 64, so raw scores swing wildly and push softmax into a near one-hot spike where gradients vanish. Dividing by √64 = 8 pulls the variance back to ~1.

S' = QKT√dk = S8

③ Mask — block the future. Add a matrix that is 0 on/below the diagonal and −∞ above it, so token i may attend to j only when j ≤ i. This one rule is what makes left-to-right generation valid.

S''ij = S'ij + Mij,  Mij = { 0 if j ≤ i,  −∞ if j > i }

④ Softmax — scores become weights. Exponentiate each row and normalise so it sums to 1. The −∞ cells become exp(−∞) = 0, so masked positions get exactly zero weight. Row i now reads "how much token i listens to each earlier token."

Aij = exp(S''ij)k≤i exp(S''ik)
each row sums to 1 · A is lower-triangular (6×6) · in practice the row max is subtracted first for numerical stability
Deep dive · ⑤ blend with Value

The weights say who to listen to; the Values say what they carry. Each token's output is the weighted average of the Value vectors it attended to — context folded into one vector.

O = AV,  oi = j≤i Aij vj
A (6×6) · V (6×64) → O (6×64) — one context vector per token

Because row i's weights are zero past position i, oi can only ever be built from the current token and its left context.

5d · Recombine the heads

The 12 head outputs (each 6×64) are concatenated back into (6, 768) and passed through one more learned linear layer that lets the heads' findings mix. Attention is done.

…12 concat → (6, 768) linear (6, 768)

Figure 5d. Heads merge back to the familiar (6, 768) shape, then a residual add returns the result to the spine.

Deep dive · merging 12 heads

Why a final matrix? Each head produced a (6×64) view in its own subspace. Concatenation restores (6×768) but leaves those subspaces siloed; the output projection WO lets the heads' findings interact and re-mix into one coherent update.

headh = softmax(QhKhT√dk + M)Vh
Attention = Concat(head1, …, head12) WO
12 × (6×64) → concat (6×768) → ×WO (768×768) → (6×768), then a residual add returns it to the spine

5e · MLP — refine each token

The second half of the block. A two-layer network expands each token vector from 768 to 3,072, applies a GELU nonlinearity, then compresses back to 768. No token sees another here — it's pure per-token refinement.

768 ×W₁ 3072 expand ×4 GELU ×W₂ 768 → residual add
→ next block

Figure 5e. Expand-then-compress. The wide middle layer is where most of the model's "knowledge" parameters live. Block output goes back to 05 — eleven more times.

Deep dive · the MLP, exactly

Why it exists. Attention can only form weighted averages of existing vectors — it moves information between tokens but cannot compute new nonlinear features within a token. The MLP supplies exactly that: a per-token function with the capacity to detect and store patterns. Most of the model's factual "knowledge" lives here.

MLP(x) = GELU(xW1 + b1) W2 + b2
W1 (768×3072) expands ×4 · W2 (3072×768) compresses back · run on each token independently
What

Project up to 3,072 dimensions (room for many feature detectors), apply a nonlinearity, project back to 768.

How

GELU(x) = x·Φ(x) ≈ 0.5x(1 + tanh[√(2/π)(x + 0.044715x³)]) — a smooth gate that passes useful activations and softly suppresses the rest.

Why ×4

The wide middle holds the bulk of the block's parameters (~4.7M of ~7M). Width is capacity: more directions to recognise and recombine.

5f · The operators that wrap every sublayer

Attention and the MLP are never used bare. Each is wrapped in the same envelope — normalise → sublayer → dropout → add back. GPT-2 puts the LayerNorm before the sublayer (pre-norm):

xx + Dropout( Attn( LN1(x) ) )
xx + Dropout( MLP( LN2(x) ) )
Residual connection
What

Add the sublayer's input back to its output, so each sublayer learns a correction (a delta), never a full replacement.

Why

It builds a gradient highway: since ∂(x+f(x))/∂x = I + ∂f/∂x, gradients reach early layers through the identity term — the reason 12 (or 96) stacked blocks can train at all.

How

Plain element-wise addition of two (6×768) tensors. No parameters, negligible cost.

Layer normalization

Computed per token across its 768 features (μ and σ are scalars for that token), then rescaled by learned γ, β.

LN(x) = γx − μ√(σ² + ε) + β
Why

Keeps the scale of activations entering attention/MLP stable no matter how large the residual stream has grown — smoother, faster optimization.

How

μ, σ² are the mean and variance of the token's 768 numbers; ε (~1e−5) guards the divide; γ, β let the model rescale or even undo the normalization.

Dropout
train: ym = xm · maskm1 − pmask ∼ Bernoulli(1−p)  |  infer: y = x
What

During training only, randomly zero a fraction p of activations (GPT-2: p = 0.1) on attention weights, the MLP, and residual outputs.

Why

Stops the network over-relying on any single path; forces redundant, robust features — akin to averaging many thinned sub-networks.

How

Survivors are divided by (1−p) so the expected sum is unchanged; at inference dropout is off and nothing is scaled.

Why it deepens: after 12 rounds of (mix → refine), a token's vector is no longer "the word at position 5" — it's a rich summary of that word in this specific sentence. Only then is it ready to predict.
06

Output projection → logits

From 768 numbers to one score per vocabulary word

Only the last token's vector matters for predicting what comes next. A final linear layer projects its 768 numbers up to 50,257 — one raw score (a logit) for every possible token in the vocabulary.

last token (768) linear logits — one per token (50257)

Figure 6. Higher logit = the model thinks that token is a more likely continuation.

Deep dive · from one hidden vector to 50,257 scores

This final linear layer is the unembedding. In GPT-2 its weights are tied to the token-embedding matrix E — the same table that turned tokens into vectors at the start now turns the final vector back into per-token scores.

z = hlast WU,  WU = ET zv = hlast · Ev
hlast (768) · WU (768×50257) → z (50257). Each logit zv is how aligned the final vector is with vocab token v's embedding direction.
07

Softmax → probabilities → sampling

Turn scores into odds, then pick a winner

Softmax squashes the 50,257 logits into probabilities that sum to 1. Three dials shape the final pick:

create0.41 make0.22 explore0.13 build analyze

Figure 7. A probability for every word. The dials below decide how this distribution is read.

Deep dive · softmax, temperature & the final pick

Softmax exponentiates every logit and divides by the total, so each probability is positive and all 50,257 sum to 1. Because of the exponential, a modest gap in logits becomes a large gap in probability.

pv = exp(zv / T)w exp(zw / T)

Worked from the chart. If the leading logits exponentiate to relative weights 41 : 22 : 13 : …, dividing each by the running total over all 50,257 tokens gives the bars above:

p(create) = exp(zcreate)/Σ = 0.41 · p(make) = 0.22 · p(explore) = 0.13 ·  · Σ over vocab = 1.00
Temperature

T divides the logits first. T<1 widens the gaps (sharper, safer); T>1 shrinks them (flatter, riskier); T→0 becomes pure argmax.

Top-k / Top-p

Keep only the top k tokens, or the smallest set whose probabilities reach p; everything else is dropped to zero.

Renormalise

The surviving probabilities are rescaled to sum to 1 again, then one token is sampled from that trimmed distribution.

dialTemperature

Divides logits before softmax. <1 sharpens (safe, repetitive); >1 flattens (creative, risky); =1 leaves it unchanged.

dialTop-k

Keep only the k highest-probability tokens as candidates; discard the long tail entirely.

dialTop-p

Keep the smallest set of tokens whose probabilities add up to p — an adaptive cutoff that widens or narrows with confidence.

08

Emit token, then loop

Autoregression — one word at a time

One token is sampled — say "create". It's appended to the prompt, and the entire pipeline runs again on the now-longer sequence to produce the next word. This repeat-until-done loop is how a few hundred million fixed numbers write fluent text.

…empowers users to prompt + create feed back in

Figure 8. The output becomes part of the next input. Stages 01–07 repeat for every single word the model writes.

stabilityLayer Normalization

Rescales each token's vector to a consistent mean and variance before attention and before the MLP. Keeps training stable and fast.

regularizationDropout

Randomly zeroes activations during training only so the model doesn't over-rely on any one path. Off at inference.

gradient flowResidual Connections

The "+" shortcuts around attention and the MLP let signals (and gradients) skip layers — the trick that makes 12 deep blocks trainable.

A reading companion to the Transformer Explainer by Cho, Kim, Karpekov, Helbling, Wang, Lee, Hoover & Chau (Georgia Tech), which runs a live GPT-2 model in the browser. Diagrams here are redrawn to read top-to-bottom in execution order; numbers (50,257 vocab · 768 dim · 12 blocks · 12 heads · 3,072 MLP · 124M params) are GPT-2 small. Open the original to type your own prompt and watch every value update live.