Interactive Lab

Transformer Lab

Every stage of a language model, simulated live from whatever you type. Nothing here is pretrained — the weights are random, so you're watching the mechanism, not a smart model.

Start here

How a language model gets made

Three phases turn raw text into something you can chat with. This lab lets you drive every one of them by hand, on your own input, in the browser. Click a phase to jump straight there.

Phase 1
Architecture — how one forward pass works: tokens → attention → predictions
Phase 2
Pretraining — predict the next token, over and over, on huge amounts of text
Phase 3
Post-training — SFT, RLHF, DPO, GRPO: turning a text-predictor into an assistant

Whysimulate instead of just explaining

The words "attention" and "reinforcement learning" stay abstract until you've watched a number change because you changed something. Every panel in this lab does a real computation — real softmax, real dot products, real cross-entropy — just at a toy scale (8 dimensions instead of 12,288) so you can see every value at once instead of drowning in a 175-billion-parameter matrix.

Type your own sentence in the Tokenizer section and it will flow through every downstream section automatically — embeddings, attention, the output distribution, all recomputed live. Come back to 00 any time from the sidebar.

What you'll be able to answer afterward

  • What actually happens, numerically, when a sentence goes into a transformer
  • Why attention is "queries, keys and values" and not just one vector
  • Why we need positional encoding at all when attention itself is order-blind
  • What a residual connection and layer norm are protecting against
  • Why pretraining is "just" next-token prediction, and why that's enough to learn a lot
  • What SFT, RLHF (reward model + PPO), DPO and GRPO each optimize, and why teams pick one over another
01 · Architecture

Tokenizer

Models don't read letters or words — they read a fixed vocabulary of tokens, learned by finding the most common repeated chunks of text. This is a real byte-pair-encoding (BPE) loop, trained live on whatever you type.

Input text
Special tokens
<bos> begins every sequence
<eos> ends every sequence
<unk> catches unseen symbols
Unknown probe
— run the tokenizer —
Merge steps (most frequent adjacent pair wins each round)
— run the tokenizer —
Resulting tokens
Fewer merges → tokens closer to raw characters (large "vocabulary" of possible sequences, but each token carries little meaning). More merges → tokens closer to whole words (smaller sequences, each token carries more meaning). Real tokenizers like GPT's run ~50,000 merges over hundreds of billions of characters; try dragging the slider to 0 and to 40 to feel both ends of that spectrum.
02 · Architecture

Token embeddings

Each token in the vocabulary owns one learned vector — its "meaning" as a list of numbers. Real models use ~4,000–12,000 numbers per token; here we use 8 so you can see every one. These particular numbers are random (untrained) — pretraining is exactly the process that tunes them into something meaningful.

Embedding table lookup
Notice every occurrence of the same token (e.g. "the") pulls the exact same vector from the table — the embedding table has one row per vocabulary entry, not per position in your sentence. What makes "the" at position 1 different from "the" at position 7 is entirely the job of the next section.
03 · Architecture

Positional encoding

Self-attention (next section) looks at every token at once with no sense of order — "cat sat on mat" and "mat on sat cat" would look identical to it. So before attention runs, we add a wave-pattern vector for each position that lets the model tell position 1 from position 7.

Formula
PE(pos, 2i) = sin( pos / 10000^(2i/d) ) PE(pos, 2i+1) = cos( pos / 10000^(2i/d) )

Each dimension i oscillates at a different frequency — low dimensions wiggle fast (distinguish neighboring positions), high dimensions wiggle slow (distinguish far-apart positions). Added together across all 8 dimensions, every position ends up with a unique fingerprint.

Live heatmap for your sentence
Rows = token position, columns = embedding dimension. Scan down any single column and you'll see a clean sine or cosine wave — scan across a row and you get that position's unique code, which gets added directly onto the token embedding.
Embedding + position, added together (first token)
04 · Architecture

Self-attention

This is the mechanism that lets a token gather context from every other token. Each position emits a query ("what am I looking for?"), and every position (including itself) offers a key ("what do I contain?") and a value ("what do I actually give you if you attend to me?").

1. Project into Q, K, V
Q = X · W_Q K = X · W_K V = X · W_V X : (seq_len × d_model) W_* : (d_model × d_k) — one fixed random matrix per head
2. Score every pair, scale, softmax
scores = (Q · Kᵀ) / √d_k attention_weights = softmax(scores, per row)

Dividing by √d_k keeps the dot products from growing huge as dimensions increase — without it, softmax saturates and gradients vanish. Softmax turns each row into a probability distribution: "how much should this token attend to every other token."

Heads

Each head learns its own W_Q/W_K/W_V, so it can specialize — one head might track "which noun does this adjective describe," another "what's the previous verb." Their outputs get concatenated and mixed back down with one more matrix, W_O.

Click a token to see who it attends to
Try it: type a sentence with a clear pronoun, like "the trophy didn't fit in the suitcase because it was too big", then click "it." Even with random, untrained weights the pattern is meaningless right now — but this is precisely the computation a trained model uses to correctly link "it" back to "trophy."
05 · Architecture

Residual connections, layer norm & feed-forward

Attention's output doesn't replace the token's representation — it's added to it. Then two more ingredients finish the "transformer block": normalization to keep numbers stable, and a small per-token neural net to add nonlinear processing.

Residual (skip) connection
X' = X + Attention(X)

Without this "+X", stacking many layers would make gradients vanish or representations drift arbitrarily far from the input. The residual path is a direct, always-available shortcut for information (and gradient) to flow through every one of the network's layers unchanged if that's the best option.

Layer normalization
LN(x) = γ · (x − μ) / √(σ² + ε) + β

Re-centers and re-scales each token's vector to mean 0, variance 1 (then lets the model learn a new scale γ and shift β). Keeps values from exploding or shrinking as they pass through dozens of layers.

Feed-forward network (applied to every position independently)
FFN(x) = W2 · GELU(W1 · x + b1) + b2 d_model → d_ff (usually 4×) → d_model

Attention is the only place information moves between positions. The feed-forward network is where most of a transformer's parameters live, and it does per-token computation — think of attention as "gather the right context" and the FFN as "now think about it."

Full block, in order
06 · Architecture

Stacking blocks into a model

One block gathers context and thinks about it once. A real model chains dozens of them, each refining the representation further — early layers tend to pick up on syntax and local patterns, later layers on more abstract, task-relevant meaning.

Depth
Rough approximation: params ≈ 12 · L · d_model² (each block's attention + FFN projections dominate). This is the formula behind why GPT-3–scale models (96 layers, d_model 12,288) land near 175B parameters — try setting the sliders to those values.

Depth vs. widthtradeoff

Going deeper (more layers)Going wider (bigger d_model)
More sequential refinement steps; better at multi-step compositionMore capacity per step; more room to represent nuance at once
Harder to train — needs residuals/normalization to avoid vanishing signalQuadratic parameter cost in d_model; attention cost grows too
Slower at inference (strictly sequential through layers)More parallelizable per layer on modern hardware
07 · Architecture

Output layer & sampling

After the last block, the final position's vector is projected onto every token in the vocabulary, producing one score (logit) per token. Softmax turns those into probabilities. How you turn probabilities into an actual next token is a design choice — try the controls below.

Next-token distribution over your session's vocabulary
— generated tokens appear here —
TemperatureDivides logits before softmax. Low (→0) sharpens the distribution toward the top choice (deterministic, repetitive); high (>1) flattens it (more random, more diverse, more mistakes).
Top-kZero out every token outside the k highest-probability options, then renormalize. Hard cutoff on how many candidates are even eligible.
Top-p (nucleus)Keep the smallest set of top tokens whose probabilities sum to p, then renormalize. Adapts the candidate pool size to how confident the model is.
08 · Training

Pretraining

Every mechanism above starts with random weights. Pretraining is the process that tunes billions of numbers so the forward pass you just explored actually produces sensible text.

The objectivenext-token prediction

Take huge amounts of raw text. For every position in every document, hide what comes next and ask the model to predict it from everything before. Compare the model's predicted distribution to the actual next token using cross-entropy loss, and nudge every weight slightly in the direction that would have made the correct token more likely.

loss = −log( P(correct_next_token) ) averaged over every token position in the batch

That's it — no labels, no human annotation, just "predict what comes next." It works because doing this well at scale forces the model to implicitly learn grammar, facts, reasoning patterns, and style, since all of those help predict text.

Simulated training run
What this simulation shows: train loss (cyan) falls smoothly as steps increase — a real, expected curve shape from scaling laws. Validation loss (amber) tracks it closely when data is plentiful relative to model size, but visibly diverges (overfitting — the model starts memorizing instead of generalizing) when you push model size up and data size down. This is illustrative, not a real training run.

Scaling lawsthe empirical headline

Loss falls predictably as a power law in three resources: model parameters (N), training tokens (D), and compute (C). Given a fixed compute budget, there is a roughly optimal split between "make the model bigger" and "train on more data" (this is the intuition behind results like Chinchilla) — over-invest in either alone and you leave loss on the table.

09 · Post-training

From text-predictor to assistant

A pretrained model is very good at continuing text, but it isn't automatically a good assistant — asked a question, it might continue with more questions (that's what usually follows a question in web text). Post-training reshapes its behavior.

SFT
RLHF
DPO
GRPO

Side-by-side

MethodNeeds a separate reward model?Needs on-policy rollouts?Relative compute / complexityTypical use
SFTNoNoLow — same recipe as pretraining, on curated dataTeach the response format & baseline behavior
RLHF (PPO)Yes — trained on human preference pairsYes — generate, score, update, repeatHigh — 3-4 models in memory (policy, reference, reward, critic)General alignment; strong but expensive, unstable to tune
DPONo — preference pairs used directly in the lossNo — trains offline on a static preference datasetLow-Medium — one model, one loss functionCheaper, more stable alternative to RLHF for preference alignment
GRPONo critic network — reward can come from a rule/verifier or modelYes — samples a group of completions per promptMedium — no critic to train, but needs group samplingReasoning/math/code tasks with checkable rewards
10 · Check yourself

Quiz

Fifteen questions spanning everything above. Click an answer to check it.

Score: 0 / 0
11 · Full pass

Full transformer architecture

This is the whole route in one view: your text is tokenized, embedded, given position, passed through stacked blocks, projected to logits, and sampled back into new text. Change the prompt or generation controls here and the rest of the lab updates with it.

Prompt in, continuation out
Live state
tokens 0
vocab 0
specials BOS / EOS / UNK active
— run the full pass —
Architecture map
What just changed
Prompt changes update tokenization, embeddings, attention, and the output distribution in one pass.