T∿TRANSFORMER.LAB / interactive field guide
← Blog LIVE NUMERICAL DEMOS
FROM RAW TEXT TO NEXT-TOKEN PROBABILITIES

MANAV BAROT / INTERACTIVE NOTEBOOK

Inside the
Transformer.

An interactive, code-first guide to the architecture behind modern language models. Change the input, inspect tensors, click attention weights, and trace a token through a complete forward pass.

12 MODULESLIVE TENSORS0 DEPENDENCIES
model.forward() / decoder-only
"the robot learns"raw UTF-8 text
Token IDs → embedding lookup[batch, sequence, d_model]
Masked multi-head attentionQ · Kᵀ / √dₖ → softmax → V
Add + Norm + Feed-forwardnonlinear channel mixing
↳ repeated N transformer blocks
Linear projection → logits[sequence, vocabulary]
SIMULATION ENGINE: ONLINE● READY
00// SYSTEM OVERVIEW

One forward pass. Five big ideas.

At its core, a Transformer converts text into vectors, repeatedly mixes information between token positions, transforms features, and predicts what comes next. Click each stage to inspect its role and tensor shape.

⌁
Which Transformer? This walkthrough uses a decoder-only, causal language model as the default (GPT-style). You can switch to bidirectional encoder and encoder–decoder architectures in Chapter 07. The original 2017 Transformer was an encoder–decoder model.
01// TEXT → DISCRETE SYMBOLS

Tokenization

A neural network doesn't read words directly. A tokenizer maps text fragments to integer IDs. Edit the prompt below — its tokens feed the live visualizations throughout this page.

INPUT_BUFFER
Editable prompt · up to 8 demonstration tokens
LIVE INPUT
TOKEN COUNT
5
VOCAB ID
—
SELECTED INDEX
0
i
This demo uses whitespace/punctuation splitting and illustrative token IDs so each step is visible. Real LLMs typically use learned subword tokenizers (e.g., BPE or Unigram); a word may span multiple tokens. These IDs are not from a production vocabulary.
02// TOKEN ID → DENSE VECTOR

Embeddings & positional information

Embedding lookup gives each token a learnable vector. A Transformer must also encode where a token is in the sequence; otherwise, attention alone does not know token order.

X = EMBEDDING + POSITION
Rows = tokens · columns = feature dimensions
−1+1click a token to inspect its row
SELECTED TOKEN VECTOR
—
SINUSOIDAL POSITION ENCODING
PE(pos, 2i) = sin(pos / 100002i/d)
PE(pos, 2i+1) = cos(pos / 100002i/d)

This visualization uses sinusoidal encoding. For clarity, it omits the original model’s √d_model embedding scale. Modern models also use learned positions, RoPE (rotary position embeddings), and relative position methods. Changing position changes the resulting vectors.

03// LEARNABLE LINEAR PROJECTIONS

Queries, keys & values

Every input vector is projected into three distinct representations. Queries ask what a position needs; keys describe what positions match; values carry the information to combine.

PROJECTION_INSPECTOR
Selected token and head determine the numbers
token 0 · head 0
Q = XWQ  ·  K = XWK  ·  V = XWV
Illustrative sizes: X ∈ ℝn×8 ; Q, K, V for one head ∈ ℝn×2
→
The projection matrices are learned parameters shared across token positions. Each attention head has its own effective Q/K/V projections. The demo's weights are deterministic synthetic values, not pretrained weights.
04// THE HEART OF THE TRANSFORMER

Scaled dot-product attention

Each query compares itself against every key. The similarity scores are scaled, optionally masked, normalized with softmax, and used to weight the values. Click a heatmap row or cell to explore exactly where a token attends.

ATTENTION_EXPLORER
Rows are queries · columns are keys
0%100%click any cell
Selected query
Softmax probability mass by key position
# Scaled dot-product attention — a single head
scores = Q @ K.T / sqrt(d_head)
scores = causal_mask(scores) # optional: future positions → −∞
weights = softmax(scores, axis=-1)
output = weights @ V
05// PARALLEL ATTENTION SUBSPACES

Multi-head attention

Instead of one attention map, Transformers calculate several in parallel. Their outputs are concatenated and projected back into the model dimension. Select a head to inspect its pattern in the attention lab above.

4 PARALLEL HEADS / d_head = 2
Synthetic per-head maps — each head has different projections
SELECT A HEAD
CONCATENATE → OUTPUT PROJECTION
For the selected token
MultiHead(X) = Concat(head₁, head₂, head₃, head₄) WO
4 heads × 2 channels = 8 channels, then WO ∈ ℝ8×8
i
People often interpret attention heads as learning different linguistic or structural relations. This can happen, but individual heads don't always have a clean human-interpretable role. The maps here demonstrate the mathematics, not explanations of a real model's decisions.
06// ONE TRANSFORMER BLOCK

Residuals, LayerNorm & the FFN

Attention moves information between tokens; the position-wise feed-forward network (MLP) mixes features within each token. Skip connections preserve a direct information path, while normalization stabilizes activations.

TRANSFORMER_BLOCK_TRACE
Observe one selected token's activation statistics
d_model
8
FFN HIDDEN
32
EXPANSION
4×
01 / RESIDUAL

The toy block omits dropout, uses zero FFN biases and fixed LayerNorm gain 1 / bias 0. The skip path adds the input back to a sublayer's result: y = x + f(x). This helps gradient flow.

02 / NORMALIZATION

LayerNorm centers and scales features of each token using its own mean and variance, with learnable gain and bias.

03 / NONLINEAR MLP

W₂ · GELU(W₁x+b₁)+b₂. The same MLP weights apply independently to every position.

07// THE ARCHITECTURE FAMILY

Encoder, decoder, or both?

Attention masking and information flow determine what tokens are allowed to see. Explore the three main Transformer layouts, including cross-attention in sequence-to-sequence models.

CAUSAL VISIBILITY MASK
Each row is a query; each column is a key.
DATAFLOW / BLOCK LAYOUT
08// FAST AUTOREGRESSIVE INFERENCE

The key–value cache

Without caching, generation would repeatedly recompute past keys and values. A KV cache stores K/V for previous tokens, so each decoding step projects only the new token while attending to earlier cached positions.

DECODE_STEP_SIMULATOR
Token-by-token decoding, after prompt prefill
K/V rows newly computed: 1Keys available to Q: 4
Step 4 / 8
↗
The new query still attends over all available keys. Caching avoids repeated K/V projections for old tokens; it does not make attention over a growing context free. Production systems have additional memory and prefill/decode tradeoffs.
09// HIDDEN STATE → WORD DISTRIBUTION

Logits, softmax & sampling

A final projection maps the last token's hidden vector into one logit for each vocabulary entry. Softmax converts logits into probabilities. Temperature and top-k change how the next token gets selected.

AUTOREGRESSIVE_GENERATOR
A toy vocabulary and illustrative logits, not a real pretrained LM
RUN INTERACTIVELY
1.0
p(tokenᵢ) = exp(logitᵢ / T) / Σⱼ exp(logitⱼ / T)
Lower T → sharper distribution · higher T → flatter distribution · top-k → restrict to k highest logits, renormalize
!
These logits are hand-designed for teaching the sampling algorithm. This demo does not run GPT, does not download a model, and cannot be used to judge real Transformer text quality. Click a candidate bar to force that token.
10// HOW THE WEIGHTS ARE LEARNED

Next-token training & cross-entropy

During autoregressive training, a sequence is shifted by one position: each token predicts the next. The loss penalizes low probability assigned to the correct next token, and backpropagation updates the weights.

SHIFTED SUPERVISION
The same sequence supplies input and labels
L = −log p(target | preceding tokens)
Perplexity = exp(mean cross-entropy)

Production training sums or averages over many positions, examples, and batches. Padding and other tokens may be excluded from loss.

CROSS-ENTROPY EXPERIMENT
Adjust the model's probability of the correct token
0.18
NLL LOSS
1.715
PERPLEXITY*
5.56
*Perplexity shown for this single target. Gradient step uses a simplified two-class logit.
11// SELF TEST

Check your mental model.

Three quick questions to test whether the pieces fit together. Select an answer for immediate feedback.